repo
stringlengths 5
75
| commit
stringlengths 40
40
| message
stringlengths 6
18.2k
| diff
stringlengths 60
262k
|
---|---|---|---|
antoine-levitt/ACCQUAREL
|
ace2750890329ac1d618e5c0cefefb8815218129
|
Simplify use of bielectronic integrals
|
diff --git a/src/Makefile b/src/Makefile
index c75a9b0..31d9103 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -1,99 +1,102 @@
### MAKEFILE PREAMBLE ###
F95 = g95
#F95 = gfortran
#F95 = ifort
# common to compilers and linker
DEBUGFFLAGS = -fbounds-check -fimplicit-none -ffpe-trap=invalid,zero,denormal
PRODFFLAGS = -fimplicit-none
COMMONFLAGS = -O3 -g
FFLAGS = $(PRODFFLAGS) $(COMMONFLAGS)
ifndef ASPICROOT
ASPICROOT=../A.S.P.I.C
endif
ifeq ($(F95),g95)
F95FLAGS = -c $(FLAGS) -fmod=$(MODDIR) $(FFLAGS)
LD = g95
FLIBS = -llapack -lblas -lm
endif
ifeq ($(F95),gfortran)
F95FLAGS = -c $(FLAGS) -fopenmp -J $(MODDIR) $(FFLAGS)
LD = gfortran
FLIBS = -lgomp -llapack -lblas -lm
endif
ifeq ($(F95),ifort)
F95FLAGS = -c $(FLAGS) -module $(MODDIR) $(FFLAGS)
LD = ifort
FLIBS = -llapack -lblas -lm
endif
LDFLAGS = $(COMMONFLAGS)
CPP = g++
CXXFLAGS = -c $(COMMONFLAGS)
## DIRECTORIES ##
TARGET = accquarel.exe
EXEDIR = ../
MODDIR = ../mod/
OBJDIR = ../obj/
SRCDIR = ./
## ASPIC code ##
ASPICINCPATH = -I$(ASPICROOT)/include
ASPICLIBPATH = -L$(ASPICROOT)/lib
XERCESCLIBPATH = -L$(XERCESCROOT)/lib
ifeq ($(shell uname),Darwin)
## cluster osx darwin
ASPICLIBS = $(ASPICLIBPATH) -lgIntegrals -lchemics -lxmlParser -lgaussian -lpolynome -lcontainor -laspicUtils $(XERCESCLIBPATH) -lxerces-c -L/usr/lib/gcc/i686-apple-darwin9/4.0.1 -lstdc++
endif
ifeq ($(shell uname),Linux)
## linux ubuntu
ASPICLIBS = $(ASPICLIBPATH) -lgIntegrals -lchemics -lxmlParser -lgaussian -lpolynome -lcontainor -laspicUtils $(XERCESCLIBPATH) -lxerces-c -L/usr/lib/gcc/i686-linux-gnu/4.4/ -lstdc++
endif
## ACCQUAREL code ##
OBJ = \
$(OBJDIR)expokit.o \
$(OBJDIR)optimization.o \
$(OBJDIR)rootfinding.o \
$(OBJDIR)tools.o \
$(OBJDIR)setup.o \
$(OBJDIR)common.o \
$(OBJDIR)integrals_c.o \
$(OBJDIR)integrals_f.o \
$(OBJDIR)basis.o \
$(OBJDIR)matrices.o \
$(OBJDIR)scf.o \
$(OBJDIR)roothaan.o \
$(OBJDIR)levelshifting.o \
$(OBJDIR)diis.o \
$(OBJDIR)oda.o \
$(OBJDIR)esa.o \
$(OBJDIR)gradient.o \
$(OBJDIR)algorithms.o \
$(OBJDIR)drivers.o \
$(OBJDIR)main.o
# Compilation rules
$(TARGET) : $(OBJ)
$(LD) $(LDFLAGS) $(OBJ) -o $(EXEDIR)$(TARGET) $(FLIBS) $(ASPICLIBS)
@echo " ----------- $(TARGET) created ----------- "
+$(OBJDIR)%.o : $(SRCDIR)%.F90
+ $(F95) $(F95FLAGS) -o $@ $<
+
$(OBJDIR)%.o : $(SRCDIR)%.f90
$(F95) $(F95FLAGS) -o $@ $<
$(OBJDIR)%.o : $(SRCDIR)%.f
$(F95) $(F95FLAGS) -o $@ $<
$(OBJDIR)%.o : $(SRCDIR)%.cpp
$(CPP) $(CXXFLAGS) -o $@ $(ASPICINCPATH) $<
#
clean :
rm $(EXEDIR)$(TARGET) $(OBJ) $(MODDIR)*.mod
diff --git a/src/forall.f90 b/src/forall.f90
new file mode 100644
index 0000000..8c84c32
--- /dev/null
+++ b/src/forall.f90
@@ -0,0 +1,104 @@
+ IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
+ DO N=1,BINMBR
+ IF (DIRECT) THEN
+! the values of the bielectronic integrals are computed "on the fly"
+ I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
+ INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
+ ELSE
+ IF (USEDISK) THEN
+! the list and values of the bielectronic integrals are read on disk
+ READ(BIUNIT)I,J,K,L,INTGRL
+ ELSE
+! the list and values of the bielectronic integrals are read in memory
+ I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
+ INTGRL=RBIVALUES(N)
+ END IF
+ END IF
+! 1 value for the 4 indices
+ IF ((I==J).AND.(J==K).AND.(K==L)) THEN
+ ACTION(I,I,I,I)
+! 2 distinct values for the 4 indices
+ ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
+ ACTION(I,J,J,J)
+ ACTION(J,J,I,J)
+ ACTION(J,J,J,I)
+ ACTION(J,I,J,J)
+ ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
+ ACTION(L,I,I,I)
+ ACTION(I,I,L,I)
+ ACTION(I,I,I,L)
+ ACTION(I,L,I,I)
+ ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
+ ACTION(I,I,K,K)
+ ACTION(K,K,I,I)
+ ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
+ ACTION(I,J,I,J)
+ ACTION(J,I,J,I)
+ ACTION(J,I,I,J)
+ ACTION(I,J,J,I)
+! 3 distinct values for the 4 indices
+ ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
+ ACTION(I,J,I,L)
+ ACTION(J,I,I,L)
+ ACTION(I,J,L,I)
+ ACTION(J,I,L,I)
+
+ ACTION(I,L,I,J)
+ ACTION(L,I,I,J)
+ ACTION(I,L,J,I)
+ ACTION(L,I,J,I)
+ ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
+ ACTION(I,J,J,L)
+ ACTION(J,I,J,L)
+ ACTION(I,J,L,J)
+ ACTION(J,I,L,J)
+
+ ACTION(J,L,I,J)
+ ACTION(L,J,I,J)
+ ACTION(J,L,J,I)
+ ACTION(L,J,J,I)
+ ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
+ ACTION(I,J,K,J)
+ ACTION(J,I,K,J)
+ ACTION(I,J,J,K)
+ ACTION(J,I,J,K)
+
+ ACTION(K,J,I,J)
+ ACTION(J,K,I,J)
+ ACTION(K,J,J,I)
+ ACTION(J,K,J,I)
+ ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
+ ACTION(I,J,K,K)
+ ACTION(J,I,K,K)
+
+ ACTION(K,K,I,J)
+ ACTION(K,K,J,I)
+ ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
+ ACTION(I,I,K,L)
+ ACTION(I,I,L,K)
+
+ ACTION(K,L,I,I)
+ ACTION(L,K,I,I)
+! 4 distinct values for the 4 indices
+ ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
+ .OR.((I>K).AND.(K>J).AND.(J>L)) &
+ .OR.((I>K).AND.(K>L).AND.(L>J))) THEN
+ ACTION(I,J,K,L)
+ ACTION(J,I,K,L)
+ ACTION(I,J,L,K)
+ ACTION(J,I,L,K)
+
+ ACTION(K,L,I,J)
+ ACTION(L,K,I,J)
+ ACTION(K,L,J,I)
+ ACTION(L,K,J,I)
+ END IF
+ END DO
+ IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
+
+
+
+
+
+
+
diff --git a/src/matrices.f90 b/src/matrices.F90
similarity index 86%
rename from src/matrices.f90
rename to src/matrices.F90
index 283c14b..70d3e09 100644
--- a/src/matrices.f90
+++ b/src/matrices.F90
@@ -76,1104 +76,960 @@ SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
DOUBLE COMPLEX :: VALUE
POM=(0.D0,0.D0)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOM_relativistic
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J
DO J=1,NBAST
DO I=1,J
POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J))
END DO
END DO
END SUBROUTINE BUILDOM_nonrelativistic
SUBROUTINE BUILDOM_GHF(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! matrix is block-diagonal
CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOM_GHF
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
DO J=1,NBAST
DO I=1,J
PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0
END DO
END DO
END SUBROUTINE BUILDKPFM_nonrelativistic
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M,N
DOUBLE COMPLEX :: TMP,VALUE
POEFM=(0.D0,0.D0)
! potential energy for L spinors
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
DO N=1,NBN
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
IF(MODEL == 3) THEN
! schrodinger kinetic energy
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L)*&
&KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2) + VALUE
END DO
END DO
ELSE
! kinetic energy alpha.p
DO J=NBAS(1)+1,SUM(NBAS)
DO I=1,NBAS(1)
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), &
& DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), &
& DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3))
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
!potential energy for S spinors
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
DO N=1,NBN
TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END IF
END SUBROUTINE BUILDOEFM_relativistic
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
POEFM=0.D0
DO J=1,NBAST
DO I=1,J
VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0
DO N=1,NBN
VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N))
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOEFM_nonrelativistic
SUBROUTINE BUILDOEFM_GHF(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! the one-electron Fock operator does not couple spins, matrix is block-diagonal
CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOEFM_GHF
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM
TEFM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
! IF ((I==J).AND.(I==K).AND.(I==L)) THEN
! NO CONTRIBUTION
! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K))
! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN
! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I))
! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K))
! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I))
ELSE
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_relativistic
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
TEFM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I)
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J)
TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J))
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I))
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I))
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I)
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_RHF
SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
PTEFM=PCM-PEM
END SUBROUTINE BUILDTEFM_GHF
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM
CM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(I,J)
ELSE
CM(I,J)=CM(I,J)+INTGRL*DM(K,L)
CM(K,L)=CM(K,L)+INTGRL*DM(I,J)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_relativistic
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! The formula is CM(I,J) = sum over k,l of (IJ|KL) D(I,J)
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
CM=0.D0
DM=UNPACK(PDM,NBAST)
- IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
- DO N=1,BINMBR
- IF (DIRECT) THEN
-! the values of the bielectronic integrals are computed "on the fly"
- I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
- INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
- ELSE
- IF (USEDISK) THEN
-! the list and values of the bielectronic integrals are read on disk
- READ(BIUNIT)I,J,K,L,INTGRL
- ELSE
-! the list and values of the bielectronic integrals are read in memory
- I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
- INTGRL=RBIVALUES(N)
- END IF
- END IF
-! 1 value for the 4 indices
- IF ((I==J).AND.(J==K).AND.(K==L)) THEN
- CM(I,I)=CM(I,I)+INTGRL*DM(I,I)
-! 2 distinct values for the 4 indices
- ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
- CM(I,J)=CM(I,J)+INTGRL*DM(J,J)
- CM(J,I)=CM(J,I)+INTGRL*DM(J,J)
- CM(J,J)=CM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
- ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
- CM(L,I)=CM(L,I)+INTGRL*DM(I,I)
- CM(I,L)=CM(I,L)+INTGRL*DM(I,I)
- CM(I,I)=CM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
- ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
- CM(I,I)=CM(I,I)+INTGRL*DM(K,K)
- CM(K,K)=CM(K,K)+INTGRL*DM(I,I)
- ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
- CM(I,J)=CM(I,J)+INTGRL*(DM(I,J)+DM(J,I))
- CM(J,I)=CM(J,I)+INTGRL*(DM(J,I)+DM(I,J))
-! 3 distinct values for the 4 indices
- ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
- CM(I,J)=CM(I,J)+INTGRL*(DM(I,L)+DM(L,I))
- CM(J,I)=CM(J,I)+INTGRL*(DM(I,L)+DM(L,I))
- CM(I,L)=CM(I,L)+INTGRL*(DM(I,J)+DM(J,I))
- CM(L,I)=CM(L,I)+INTGRL*(DM(I,J)+DM(J,I))
- ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
- CM(J,I)=CM(J,I)+INTGRL*(DM(J,L)+DM(L,J))
- CM(I,J)=CM(I,J)+INTGRL*(DM(J,L)+DM(L,J))
- CM(J,L)=CM(J,L)+INTGRL*(DM(J,I)+DM(I,J))
- CM(L,J)=CM(L,J)+INTGRL*(DM(J,I)+DM(I,J))
- ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
- CM(J,I)=CM(J,I)+INTGRL*(DM(J,K)+DM(K,J))
- CM(I,J)=CM(I,J)+INTGRL*(DM(J,K)+DM(K,J))
- CM(J,K)=CM(J,K)+INTGRL*(DM(J,I)+DM(I,J))
- CM(K,J)=CM(K,J)+INTGRL*(DM(J,I)+DM(I,J))
- ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
- CM(I,J)=CM(I,J)+INTGRL*DM(K,K)
- CM(J,I)=CM(J,I)+INTGRL*DM(K,K)
- CM(K,K)=CM(K,K)+INTGRL*(DM(I,J)+DM(J,I))
- ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
- CM(K,L)=CM(K,L)+INTGRL*DM(I,I)
- CM(L,K)=CM(L,K)+INTGRL*DM(I,I)
- CM(I,I)=CM(I,I)+INTGRL*(DM(K,L)+DM(L,K))
-! 4 distinct values for the 4 indices
- ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
- .OR.((I>K).AND.(K>J).AND.(J>L)) &
- .OR.((I>K).AND.(K>L).AND.(L>J))) THEN
- CM(I,J)=CM(I,J)+INTGRL*(DM(K,L)+DM(L,K))
- CM(J,I)=CM(J,I)+INTGRL*(DM(K,L)+DM(L,K))
- CM(K,L)=CM(K,L)+INTGRL*(DM(I,J)+DM(J,I))
- CM(L,K)=CM(L,K)+INTGRL*(DM(I,J)+DM(J,I))
- END IF
- END DO
- IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
+
+#define ACTION(I,J,K,L) CM(I,J) = CM(I,J) + INTGRL*DM(K,L)
+#include "forall.f90"
+#undef ACTION
+
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_nonrelativistic
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM
EM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
ELSE
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_relativistic
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J)
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
EM=0.D0
DM=UNPACK(PDM,NBAST)
- IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
- DO N=1,BINMBR
- IF (DIRECT) THEN
-! the values of the bielectronic integrals are computed "on the fly"
- I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
- INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
- ELSE
- IF (USEDISK) THEN
-! the list and values of the bielectronic integrals are read on disk
- READ(BIUNIT)I,J,K,L,INTGRL
- ELSE
-! the list and values of the bielectronic integrals are read in memory
- I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
- INTGRL=RBIVALUES(N)
- END IF
- END IF
-! 1 value for the 4 indices
- IF ((I==J).AND.(J==K).AND.(K==L)) THEN
- EM(I,I)=EM(I,I)+INTGRL*DM(I,I)
-! 2 distinct values for the 4 indices
- ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
- EM(I,J)=EM(I,J)+INTGRL*DM(J,J)
- EM(J,I)=EM(J,I)+INTGRL*DM(J,J)
- EM(J,J)=EM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
- ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
- EM(L,I)=EM(L,I)+INTGRL*DM(I,I)
- EM(I,L)=EM(I,L)+INTGRL*DM(I,I)
- EM(I,I)=EM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
- ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
- EM(I,K)=EM(I,K)+INTGRL*DM(I,K)
- EM(K,I)=EM(K,I)+INTGRL*DM(K,I)
- ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
- EM(I,I)=EM(I,I)+INTGRL*DM(J,J)
- EM(J,J)=EM(J,J)+INTGRL*DM(I,I)
- EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
- EM(J,I)=EM(J,I)+INTGRL*DM(I,J)
-! 3 distinct values for the 4 indices
- ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
- EM(I,I)=EM(I,I)+INTGRL*(DM(J,L)+DM(L,J))
- EM(L,I)=EM(L,I)+INTGRL*DM(I,J)
- EM(I,J)=EM(I,J)+INTGRL*DM(L,I)
- EM(L,J)=EM(L,J)+INTGRL*DM(I,I)
- EM(I,L)=EM(I,L)+INTGRL*DM(J,I)
- EM(J,I)=EM(J,I)+INTGRL*DM(I,L)
- EM(J,L)=EM(J,L)+INTGRL*DM(I,I)
- ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
- EM(J,J)=EM(J,J)+INTGRL*(DM(I,L)+DM(L,I))
- EM(L,J)=EM(L,J)+INTGRL*DM(J,I)
- EM(J,I)=EM(J,I)+INTGRL*DM(L,J)
- EM(L,I)=EM(L,I)+INTGRL*DM(J,J)
- EM(J,L)=EM(J,L)+INTGRL*DM(I,J)
- EM(I,J)=EM(I,J)+INTGRL*DM(J,L)
- EM(I,L)=EM(I,L)+INTGRL*DM(J,J)
- ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
- EM(J,J)=EM(J,J)+INTGRL*(DM(I,K)+DM(K,I))
- EM(K,J)=EM(K,J)+INTGRL*DM(J,I)
- EM(J,I)=EM(J,I)+INTGRL*DM(K,J)
- EM(K,I)=EM(K,I)+INTGRL*DM(J,J)
- EM(J,K)=EM(J,K)+INTGRL*DM(I,J)
- EM(I,J)=EM(I,J)+INTGRL*DM(J,K)
- EM(I,K)=EM(I,K)+INTGRL*DM(J,J)
- ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
- EM(K,I)=EM(K,I)+INTGRL*DM(K,J)
- EM(K,J)=EM(K,J)+INTGRL*DM(K,I)
- EM(I,K)=EM(I,K)+INTGRL*DM(J,K)
- EM(J,K)=EM(J,K)+INTGRL*DM(I,K)
- ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
- EM(I,K)=EM(I,K)+INTGRL*DM(I,L)
- EM(I,L)=EM(I,L)+INTGRL*DM(I,K)
- EM(K,I)=EM(K,I)+INTGRL*DM(L,I)
- EM(L,I)=EM(L,I)+INTGRL*DM(K,I)
-! 4 distinct values for the 4 indices
- ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
- .OR.((I>K).AND.(K>J).AND.(J>L)) &
- .OR.((I>K).AND.(K>L).AND.(L>J))) THEN
- EM(K,I)=EM(K,I)+INTGRL*DM(L,J)
- EM(L,I)=EM(L,I)+INTGRL*DM(K,J)
- EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
- EM(L,J)=EM(L,J)+INTGRL*DM(K,I)
- EM(I,K)=EM(I,K)+INTGRL*DM(J,L)
- EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
- EM(J,K)=EM(J,K)+INTGRL*DM(I,L)
- EM(J,L)=EM(J,L)+INTGRL*DM(I,K)
- END IF
- END DO
- IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
+
+#define ACTION(I,J,K,L) EM(I,K) = EM(I,K) + INTGRL*DM(L,J)
+#include "forall.f90"
+#undef ACTION
+
+
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_nonrelativistic
SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
PSAMCM=(0.D0,0.D0)
SELECT CASE (COMPONENT)
CASE (1)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (2)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (3)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SELECT
END SUBROUTINE BUILDSAMCM
SUBROUTINE BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the orbital angular momentum operator L=x^p (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POAMCM=(0.D0,0.D0)
SELECT CASE (COMPONENT)
CASE (1)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (2)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (3)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SELECT
END SUBROUTINE BUILDOAMCM
SUBROUTINE BUILDTAMCM(PTAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the total angular momentum operator J=L+S (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PSAMCM,POAMCM
CALL BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT)
CALL BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT)
PTAMCM=PSAMCM+POAMCM
END SUBROUTINE BUILDTAMCM
MODULE matrices
INTERFACE FORMDM
SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON)
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
END SUBROUTINE
SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON)
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
END SUBROUTINE
END INTERFACE
INTERFACE BUILDOM
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
END SUBROUTINE
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDKPFM
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDOEFM
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
END SUBROUTINE
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDTEFM
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
INTERFACE BUILDCOULOMB
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
INTERFACE BUILDEXCHANGE
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
END MODULE
|
antoine-levitt/ACCQUAREL
|
523a5f5c7c02e906472bb16089d480c004d02aab
|
Add formulae as comments
|
diff --git a/src/matrices.f90 b/src/matrices.f90
index e69a415..283c14b 100644
--- a/src/matrices.f90
+++ b/src/matrices.f90
@@ -63,1115 +63,1117 @@ SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON)
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM)
END DO
END SUBROUTINE FORMPROJ
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POM=(0.D0,0.D0)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOM_relativistic
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J
DO J=1,NBAST
DO I=1,J
POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J))
END DO
END DO
END SUBROUTINE BUILDOM_nonrelativistic
SUBROUTINE BUILDOM_GHF(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! matrix is block-diagonal
CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOM_GHF
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
DO J=1,NBAST
DO I=1,J
PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0
END DO
END DO
END SUBROUTINE BUILDKPFM_nonrelativistic
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M,N
DOUBLE COMPLEX :: TMP,VALUE
POEFM=(0.D0,0.D0)
! potential energy for L spinors
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
DO N=1,NBN
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
IF(MODEL == 3) THEN
! schrodinger kinetic energy
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L)*&
&KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2) + VALUE
END DO
END DO
ELSE
! kinetic energy alpha.p
DO J=NBAS(1)+1,SUM(NBAS)
DO I=1,NBAS(1)
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), &
& DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), &
& DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3))
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
!potential energy for S spinors
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
DO N=1,NBN
TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END IF
END SUBROUTINE BUILDOEFM_relativistic
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
POEFM=0.D0
DO J=1,NBAST
DO I=1,J
VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0
DO N=1,NBN
VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N))
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOEFM_nonrelativistic
SUBROUTINE BUILDOEFM_GHF(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! the one-electron Fock operator does not couple spins, matrix is block-diagonal
CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOEFM_GHF
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM
TEFM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
! IF ((I==J).AND.(I==K).AND.(I==L)) THEN
! NO CONTRIBUTION
! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K))
! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN
! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I))
! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K))
! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I))
ELSE
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_relativistic
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
TEFM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I)
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J)
TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J))
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I))
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I))
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I)
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_RHF
SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
PTEFM=PCM-PEM
END SUBROUTINE BUILDTEFM_GHF
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM
CM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(I,J)
ELSE
CM(I,J)=CM(I,J)+INTGRL*DM(K,L)
CM(K,L)=CM(K,L)+INTGRL*DM(I,J)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_relativistic
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
+ ! The formula is CM(I,J) = sum over k,l of (IJ|KL) D(I,J)
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
CM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
CM(I,I)=CM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(J,J)
CM(J,I)=CM(J,I)+INTGRL*DM(J,J)
CM(J,J)=CM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
CM(L,I)=CM(L,I)+INTGRL*DM(I,I)
CM(I,L)=CM(I,L)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
CM(I,I)=CM(I,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*DM(I,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(I,J)+DM(J,I))
CM(J,I)=CM(J,I)+INTGRL*(DM(J,I)+DM(I,J))
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(I,L)+DM(L,I))
CM(J,I)=CM(J,I)+INTGRL*(DM(I,L)+DM(L,I))
CM(I,L)=CM(I,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,I)=CM(L,I)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,L)+DM(L,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,L)+DM(L,J))
CM(J,L)=CM(J,L)+INTGRL*(DM(J,I)+DM(I,J))
CM(L,J)=CM(L,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,K)+DM(K,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,K)+DM(K,J))
CM(J,K)=CM(J,K)+INTGRL*(DM(J,I)+DM(I,J))
CM(K,J)=CM(K,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(K,K)
CM(J,I)=CM(J,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
CM(K,L)=CM(K,L)+INTGRL*DM(I,I)
CM(L,K)=CM(L,K)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(K,L)+DM(L,K))
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(K,L)+DM(L,K))
CM(J,I)=CM(J,I)+INTGRL*(DM(K,L)+DM(L,K))
CM(K,L)=CM(K,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,K)=CM(L,K)+INTGRL*(DM(I,J)+DM(J,I))
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_nonrelativistic
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM
EM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
ELSE
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_relativistic
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
+ ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J)
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
EM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,J)
EM(J,I)=EM(J,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
EM(L,I)=EM(L,I)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(I,I)
EM(I,I)=EM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
EM(I,K)=EM(I,K)+INTGRL*DM(I,K)
EM(K,I)=EM(K,I)+INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*DM(I,I)
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(I,J)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
EM(I,I)=EM(I,I)+INTGRL*(DM(J,L)+DM(L,J))
EM(L,I)=EM(L,I)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(L,I)
EM(L,J)=EM(L,J)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(I,L)
EM(J,L)=EM(J,L)+INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
EM(J,J)=EM(J,J)+INTGRL*(DM(I,L)+DM(L,I))
EM(L,J)=EM(L,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(L,J)
EM(L,I)=EM(L,I)+INTGRL*DM(J,J)
EM(J,L)=EM(J,L)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(J,L)
EM(I,L)=EM(I,L)+INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
EM(J,J)=EM(J,J)+INTGRL*(DM(I,K)+DM(K,I))
EM(K,J)=EM(K,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(K,J)
EM(K,I)=EM(K,I)+INTGRL*DM(J,J)
EM(J,K)=EM(J,K)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(J,K)
EM(I,K)=EM(I,K)+INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
EM(K,I)=EM(K,I)+INTGRL*DM(K,J)
EM(K,J)=EM(K,J)+INTGRL*DM(K,I)
EM(I,K)=EM(I,K)+INTGRL*DM(J,K)
EM(J,K)=EM(J,K)+INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
EM(I,K)=EM(I,K)+INTGRL*DM(I,L)
EM(I,L)=EM(I,L)+INTGRL*DM(I,K)
EM(K,I)=EM(K,I)+INTGRL*DM(L,I)
EM(L,I)=EM(L,I)+INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
EM(K,I)=EM(K,I)+INTGRL*DM(L,J)
EM(L,I)=EM(L,I)+INTGRL*DM(K,J)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
EM(L,J)=EM(L,J)+INTGRL*DM(K,I)
EM(I,K)=EM(I,K)+INTGRL*DM(J,L)
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(J,K)=EM(J,K)+INTGRL*DM(I,L)
EM(J,L)=EM(J,L)+INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_nonrelativistic
SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
PSAMCM=(0.D0,0.D0)
SELECT CASE (COMPONENT)
CASE (1)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (2)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (3)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SELECT
END SUBROUTINE BUILDSAMCM
SUBROUTINE BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the orbital angular momentum operator L=x^p (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POAMCM=(0.D0,0.D0)
SELECT CASE (COMPONENT)
CASE (1)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (2)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (3)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SELECT
END SUBROUTINE BUILDOAMCM
SUBROUTINE BUILDTAMCM(PTAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the total angular momentum operator J=L+S (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PSAMCM,POAMCM
CALL BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT)
CALL BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT)
PTAMCM=PSAMCM+POAMCM
END SUBROUTINE BUILDTAMCM
MODULE matrices
INTERFACE FORMDM
SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON)
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
END SUBROUTINE
SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON)
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
END SUBROUTINE
END INTERFACE
INTERFACE BUILDOM
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
END SUBROUTINE
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDKPFM
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDOEFM
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
END SUBROUTINE
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDTEFM
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
INTERFACE BUILDCOULOMB
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
INTERFACE BUILDEXCHANGE
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
END MODULE
|
antoine-levitt/ACCQUAREL
|
3b99352127c2f73e19d8fdb83851b3167a14c563
|
Cleaner output, suppress infinity norms
|
diff --git a/src/scf.f90 b/src/scf.f90
index 61f30e8..91b5ac2 100644
--- a/src/scf.f90
+++ b/src/scf.f90
@@ -1,460 +1,449 @@
MODULE scf_tools
INTERFACE CHECKNUMCONV
MODULE PROCEDURE CHECKNUMCONV_relativistic,CHECKNUMCONV_AOCOSDHF,CHECKNUMCONV_RHF,CHECKNUMCONV_UHF
END INTERFACE
CONTAINS
SUBROUTINE CHECKORB(EIG,N,LOON)
! Subroutine that determines the number of the lowest and highest occupied electronic orbitals and checks if they are both in the spectral gap (in the relavistic case).
USE case_parameters ; USE data_parameters
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N),INTENT(IN) :: EIG
INTEGER,INTENT(IN) :: N
INTEGER,INTENT(OUT) :: LOON
INTEGER :: HGEN
! Determination of the number of the lowest occupied orbital (i.e., the one relative to the first eigenvalue associated to an electronic state in the gap)
LOON=MINLOC(EIG,DIM=1,MASK=EIG>-C*C)
IF (LOON.EQ.0) THEN
STOP'Subroutine CHECKORB: no eigenvalue associated to an electronic state.'
ELSE
WRITE(*,'(a,i3,a,i3,a)')' Number of the lowest occupied electronic orbital = ',LOON,'(/',N,')'
IF (N-LOON.LT.NBE) THEN
WRITE(*,'(a)')' Subroutine CHECKORB: there are not enough eigenvalues associated to electronic states (',N-LOON,').'
STOP
END IF
! Determination of the number of the highest orbital relative to an eigenvalue associated to an electronic state in the gap
HGEN=MAXLOC(EIG,DIM=1,MASK=EIG<0.D0)
WRITE(*,'(a,i3)')' Number of eigenvalues associated to electronic states in the gap = ',HGEN-LOON+1
IF (HGEN-LOON+1.LT.NBE) THEN
WRITE(*,'(a,i2,a)')' Warning: there are less than ',NBE,' eigenvalues associated to electronic states in the gap.'
END IF
END IF
END SUBROUTINE CHECKORB
SUBROUTINE CHECKNUMCONV_relativistic(PDMN,PDMO,PFM,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock equations (restricted closed-shell Hartree-Fock and closed-shell Dirac-Hartree-Fock formalisms).
USE matrix_tools ; USE metric_relativistic
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMN,PDMO,PFM
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE COMPLEX,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMT
DOUBLE PRECISION,DIMENSION(N) :: WORK
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMN-PDMO,N)
- WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
WRITE(17,'(e22.14)')FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFM,PDMN,PS,N),ISRS))
- WRITE(*,*)'Infinity norm of the commutator [F(D_n),D_n] =',NORM(CMT,N,'I')
FNCMT=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n),D_n] =',FNCMT
WRITE(18,'(e22.14)')FNCMT
IF (FNCMT<=TRSHLD) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
WRITE(16,'(e22.14)')ETOTN
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_relativistic
SUBROUTINE CHECKNUMCONV_RHF(PDMN,PDMO,PFM,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock equations (restricted closed-shell Hartree-Fock formalism).
USE matrix_tools ; USE metric_nonrelativistic
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMN,PDMO,PFM
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE PRECISION,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMT
DOUBLE PRECISION,DIMENSION(N) :: WORK
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMN-PDMO,N)
- WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
WRITE(17,'(e22.14)')FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFM,PDMN,PS,N),ISRS))
- WRITE(*,*)'Infinity norm of the commutator [F(D_n),D_n] =',NORM(CMT,N,'I')
FNCMT=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n),D_n] =',FNCMT
WRITE(18,'(e22.14)')FNCMT
IF (FNCMT<=TRSHLD) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
WRITE(16,'(e22.14)')ETOTN
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_RHF
SUBROUTINE CHECKNUMCONV_UHF(PDMA,PDMB,PTDMO,PFMA,PFMB,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock type equations (unrestricted open-shell Hartree-Fock formalism).
USE matrix_tools ; USE metric_nonrelativistic
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMA,PDMB,PTDMO,PFMA,PFMB
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE PRECISION,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMTA,FNCMTB
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMA+PDMB-PTDMO,N)
- WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMA,PDMA,PS,N),ISRS))
- WRITE(*,*)'Infinity norm of the commutator [F(D_n^a),D_n^a] =',NORM(CMT,N,'I')
FNCMTA=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^a),D_n^a] =',FNCMTA
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMB,PDMB,PS,N),ISRS))
- WRITE(*,*)'Infinity norm of the commutator [F(D_n^b),D_n^b] =',NORM(CMT,N,'I')
FNCMTB=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^b),D_n^b] =',FNCMTB
IF ((FNCMTA<=TRSHLD).AND.(FNCMTB<=TRSHLD)) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_UHF
SUBROUTINE CHECKNUMCONV_AOCOSDHF(PDMCN,PDMON,PDMCO,PDMOO,PFMC,PFMO,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock type equations (average-of-configuration open-shell Dirac-Hartree-Fock formalism).
USE matrix_tools ; USE metric_relativistic
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMCN,PDMON,PDMCO,PDMOO,PFMC,PFMO
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE COMPLEX,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDNC,FNDFDNO,FNCMTC,FNCMTO
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=PDMCN-PDMCO
FNDFDNC=NORM(PDIFF,N,'F')
- WRITE(*,*)'Infinity norm of the difference D_n^c-DC_{n-1}^c =',NORM(PDIFF,N,'I')
WRITE(*,*)'Frobenius norm of the difference D_n^c-DC_{n-1}^c =',FNDFDNC
PDIFF=PDMON-PDMOO
FNDFDNO=NORM(PDIFF,N,'F')
- WRITE(*,*)'Infinity norm of the difference D_n^o-DC_{n-1}^o =',NORM(PDIFF,N,'I')
WRITE(*,*)'Frobenius norm of the difference D_n^o-DC_{n-1}^o =',FNDFDNO
IF ((FNDFDNC<=TRSHLD).AND.(FNDFDNO<=TRSHLD)) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMC,PDMCN,PS,N),ISRS))
FNCMTC=NORM(CMT,N,'F')
- WRITE(*,*)'Infinity norm of the commutator [F(D_n^c),D_n^c] =',NORM(CMT,N,'I')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^c),D_n^c] =',FNCMTC
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMO,PDMON,PS,N),ISRS))
FNCMTO=NORM(CMT,N,'F')
- WRITE(*,*)'Infinity norm of the commutator [F(D_n^o),D_n^o] =',NORM(CMT,N,'I')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^o),D_n^o] =',FNCMTO
IF ((FNCMTC<=TRSHLD).AND.(FNCMTO<=TRSHLD)) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_AOCOSDHF
END MODULE
MODULE graphics_tools
INTERFACE DENSITY_POINTWISE_VALUE
MODULE PROCEDURE DENSITY_POINTWISE_VALUE_relativistic,DENSITY_POINTWISE_VALUE_nonrelativistic
END INTERFACE
INTERFACE EXPORT_DENSITY
MODULE PROCEDURE EXPORT_DENSITY_relativistic,EXPORT_DENSITY_nonrelativistic
END INTERFACE
CONTAINS
FUNCTION DENSITY_POINTWISE_VALUE_relativistic(DM,PHI,NBAST,POINT) RESULT(VALUE)
! Function that computes the value of the electronic density associated to a given density matrix (only the upper triangular part of this matrix is stored in packed format) at a given point of space.
USE basis_parameters ; USE matrix_tools
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE PRECISION :: VALUE
INTEGER :: I
DOUBLE COMPLEX,DIMENSION(NBAST,2) :: POINTWISE_VALUES
DOUBLE COMPLEX,DIMENSION(2,2) :: MATRIX
DO I=1,NBAST
POINTWISE_VALUES(I,:)=TWOSPINOR_POINTWISE_VALUE(PHI(I),POINT)
END DO
MATRIX=MATMUL(TRANSPOSE(CONJG(POINTWISE_VALUES)),MATMUL(DM,POINTWISE_VALUES))
VALUE=REAL(MATRIX(1,1)+MATRIX(2,2))
END FUNCTION DENSITY_POINTWISE_VALUE_relativistic
FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic(DM,PHI,NBAST,POINT) RESULT(VALUE)
! Function that computes the value of the electronic density associated to a given density matrix (only the upper triangular part of this matrix is stored in packed format) at a given point of space.
USE basis_parameters ; USE matrix_tools
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE PRECISION :: VALUE
INTEGER :: I
REAL(KIND=C_DOUBLE),DIMENSION(NBAST) :: POINTWISE_VALUES
DO I=1,NBAST
POINTWISE_VALUES(I)=GBF_POINTWISE_VALUE(PHI(I),POINT)
END DO
VALUE=DOT_PRODUCT(POINTWISE_VALUES,MATMUL(DM,POINTWISE_VALUES))
END FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic
SUBROUTINE EXPORT_DENSITY_relativistic(DM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
USE basis_parameters ; USE data_parameters ; USE matrices
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST,NPOINTS
DOUBLE PRECISION,INTENT(IN) :: RMIN,RMAX
CHARACTER(*),INTENT(IN) :: FILENAME
CHARACTER(*),INTENT(IN) :: FILEFORMAT
INTEGER :: I,J,K
DOUBLE PRECISION :: GRID_STEPSIZE
DOUBLE PRECISION,DIMENSION(3) :: X
IF (NPOINTS/=1) THEN
GRID_STEPSIZE=(RMAX-RMIN)/(NPOINTS-1)
ELSE
STOP
END IF
IF ((FILEFORMAT=='matlab').OR.(FILEFORMAT=='MATLAB')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME)
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
ELSE IF ((FILEFORMAT=='cube').OR.(FILEFORMAT=='CUBE')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME//'.cube')
WRITE(42,*)'CUBE FILE.'
WRITE(42,*)'OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z'
WRITE(42,*)NBN,RMIN,RMIN,RMIN
WRITE(42,*)NPOINTS,(RMAX-RMIN)/NPOINTS,0.D0,0.D0
WRITE(42,*)NPOINTS,0.D0,(RMAX-RMIN)/NPOINTS,0.D0
WRITE(42,*)NPOINTS,0.D0,0.D0,(RMAX-RMIN)/NPOINTS
DO I=1,NBN
WRITE(42,*)Z(I),0.D0,CENTER(:,I)
END DO
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
END IF
END SUBROUTINE EXPORT_DENSITY_relativistic
SUBROUTINE EXPORT_DENSITY_nonrelativistic(DM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
USE basis_parameters ; USE data_parameters ; USE matrices
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST,NPOINTS
DOUBLE PRECISION,INTENT(IN) :: RMIN,RMAX
CHARACTER(*),INTENT(IN) :: FILENAME
CHARACTER(*),INTENT(IN) :: FILEFORMAT
INTEGER :: I,J,K
DOUBLE PRECISION :: GRID_STEPSIZE
DOUBLE PRECISION,DIMENSION(3) :: X
IF (NPOINTS/=1) THEN
GRID_STEPSIZE=(RMAX-RMIN)/(NPOINTS-1)
ELSE
STOP
END IF
IF ((FILEFORMAT=='matlab').OR.(FILEFORMAT=='MATLAB')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME)
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
ELSE IF ((FILEFORMAT=='cube').OR.(FILEFORMAT=='CUBE')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME//'.cube')
WRITE(42,*)'CUBE FILE.'
WRITE(42,*)'OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z'
WRITE(42,*)NBN,RMIN,RMIN,RMIN
WRITE(42,*)NPOINTS,(RMAX-RMIN)/NPOINTS,0.D0,0.D0
WRITE(42,*)NPOINTS,0.D0,(RMAX-RMIN)/NPOINTS,0.D0
WRITE(42,*)NPOINTS,0.D0,0.D0,(RMAX-RMIN)/NPOINTS
DO I=1,NBN
WRITE(42,*)Z(I),0.D0,CENTER(:,I)
END DO
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
END IF
END SUBROUTINE EXPORT_DENSITY_nonrelativistic
END MODULE
MODULE output
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ALL_EIG
INTERFACE OUTPUT_ITER
MODULE PROCEDURE OUTPUT_ITER_nonrelativistic,OUTPUT_ITER_relativistic
END INTERFACE OUTPUT_ITER
INTERFACE OUTPUT_FINALIZE
MODULE PROCEDURE OUTPUT_FINALIZE_nonrelativistic,OUTPUT_FINALIZE_relativistic
END INTERFACE OUTPUT_FINALIZE
CONTAINS
SUBROUTINE OUTPUT_ITER_relativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE scf_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
IF (ITER==1) ALLOCATE(ALL_EIG(NBAST,MAXITR))
ALL_EIG(:,ITER)=EIG
END SUBROUTINE OUTPUT_ITER_relativistic
SUBROUTINE OUTPUT_ITER_nonrelativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE scf_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
IF (ITER==1) ALLOCATE(ALL_EIG(NBAST,MAXITR))
ALL_EIG(:,ITER)=EIG
END SUBROUTINE OUTPUT_ITER_nonrelativistic
SUBROUTINE OUTPUT_FINALIZE_relativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE graphics_tools ; USE matrix_tools
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
OPEN(42,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,ITER
WRITE(42,*)ALL_EIG(:,I)
END DO
CLOSE(42)
DEALLOCATE(ALL_EIG)
CALL EXPORT_DENSITY(UNPACK(PDM,NBAST),PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
END SUBROUTINE OUTPUT_FINALIZE_relativistic
SUBROUTINE OUTPUT_FINALIZE_nonrelativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE graphics_tools ; USE matrix_tools
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
OPEN(42,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,ITER
WRITE(42,*)ALL_EIG(:,I)
END DO
CLOSE(42)
DEALLOCATE(ALL_EIG)
CALL EXPORT_DENSITY(UNPACK(PDM,NBAST),PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
END SUBROUTINE OUTPUT_FINALIZE_nonrelativistic
END MODULE output
|
antoine-levitt/ACCQUAREL
|
76134bae6a480228dfdfae806740d929246fb781
|
add a FORMDM_nonrelativistic that doesn't expect orthogonal eigenvectors
|
diff --git a/src/matrices.f90 b/src/matrices.f90
index a13d01a..e69a415 100644
--- a/src/matrices.f90
+++ b/src/matrices.f90
@@ -1,526 +1,550 @@
SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON)
! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PDM=(0.D0,0.D0)
DO I=LOON,HOON
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
END DO
END SUBROUTINE FORMDM_relativistic
+SUBROUTINE FORMDM_nonrelativistic_nonorthogonal(PDM,EIGVEC,NBAST,LOON,HOON)
+! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). Same as FORMDM_nonrelativistic, but does not expect orthogonal eigenvectors
+ USE metric_nonrelativistic ; USE matrix_tools
+ INTEGER,INTENT(IN) :: NBAST,LOON,HOON
+ DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC_GS,S
+
+ INTEGER :: I,J
+
+ EIGVEC_GS = EIGVEC
+ S = UNPACK(PS,NBAST)
+
+ PDM=0.D0
+ DO I=LOON,HOON
+ DO J=LOON,I-1
+ EIGVEC_GS(:,I) = EIGVEC_GS(:,I) - dot_product(EIGVEC_GS(:,J),MATMUL(S,EIGVEC_GS(:,I))) * EIGVEC_GS(:,J)
+ END DO
+ EIGVEC_GS(:,I) = EIGVEC_GS(:,I) / SQRT(dot_product(EIGVEC_GS(:,I),MATMUL(S,EIGVEC_GS(:,I))))
+ CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
+ END DO
+END SUBROUTINE FORMDM_nonrelativistic_nonorthogonal
+
+
SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON)
! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PDM=0.D0
DO I=LOON,HOON
CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
END DO
END SUBROUTINE FORMDM_nonrelativistic
SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON)
! Assembly of the matrix of the projector on the "positive" space (i.e., the electronic states) associated to a Dirac-Fock Hamiltonian (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PPROJM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PPROJM=(0.D0,0.D0)
DO I=0,NBAST-LOON
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM)
END DO
END SUBROUTINE FORMPROJ
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POM=(0.D0,0.D0)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOM_relativistic
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J
DO J=1,NBAST
DO I=1,J
POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J))
END DO
END DO
END SUBROUTINE BUILDOM_nonrelativistic
SUBROUTINE BUILDOM_GHF(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! matrix is block-diagonal
CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOM_GHF
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
DO J=1,NBAST
DO I=1,J
PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0
END DO
END DO
END SUBROUTINE BUILDKPFM_nonrelativistic
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M,N
DOUBLE COMPLEX :: TMP,VALUE
POEFM=(0.D0,0.D0)
! potential energy for L spinors
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
DO N=1,NBN
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
IF(MODEL == 3) THEN
! schrodinger kinetic energy
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L)*&
&KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2) + VALUE
END DO
END DO
ELSE
! kinetic energy alpha.p
DO J=NBAS(1)+1,SUM(NBAS)
DO I=1,NBAS(1)
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), &
& DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), &
& DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3))
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
!potential energy for S spinors
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
DO N=1,NBN
TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END IF
END SUBROUTINE BUILDOEFM_relativistic
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
POEFM=0.D0
DO J=1,NBAST
DO I=1,J
VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0
DO N=1,NBN
VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N))
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOEFM_nonrelativistic
SUBROUTINE BUILDOEFM_GHF(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! the one-electron Fock operator does not couple spins, matrix is block-diagonal
CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOEFM_GHF
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM
TEFM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
! IF ((I==J).AND.(I==K).AND.(I==L)) THEN
! NO CONTRIBUTION
! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K))
! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN
! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I))
! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K))
! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I))
ELSE
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_relativistic
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
TEFM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I)
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J)
TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J))
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I))
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I))
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I)
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_RHF
SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
PTEFM=PCM-PEM
END SUBROUTINE BUILDTEFM_GHF
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM
CM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
|
antoine-levitt/ACCQUAREL
|
056268651503d5786351f9cc2fecd3f3914e21b8
|
Implement DIIS_GHF (in contrast to other methods, it converges quickly with random IC, for some reason)
|
diff --git a/src/diis.f90 b/src/diis.f90
index 892c6da..2edc358 100644
--- a/src/diis.f90
+++ b/src/diis.f90
@@ -1,299 +1,451 @@
SUBROUTINE DIIS_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! DIIS (Direct Inversion in the Iterative Subspace) algorithm (relativistic case)
! Reference: P. Pulay, Convergence acceleration of iterative sequences. The case of SCF iteration, Chem. Phys. Lett., 73(2), 393-398, 1980.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I,J,IJ,K
INTEGER :: MXSET,MSET,MM
INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PTDM,PBM,DIISV
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: PDMSET,TMP,ISRS
DOUBLE COMPLEX,DIMENSION(:,:,:),ALLOCATABLE :: ERRSET
LOGICAL :: NUMCONV
! INITIALIZATIONS AND PRELIMINARIES
! Reading of the maximum dimension of the density matrix simplex
OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO)
READ(100,'(/,i2)')MXSET
CLOSE(100)
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(ERRSET(1:MXSET,1:NBAST,1:NBAST),PDMSET(1:MXSET,1:NBAST*(NBAST+1)/2))
ALLOCATE(ISRS(1:NBAST,1:NBAST),TMP(1:NBAST,1:NBAST))
ISRS=UNPACK(PISRS,NBAST)
ITER=0
MSET=0 ; PDMSET=(0.D0,0.D0)
IF (RESUME) THEN
CALL CHECKORB(EIG,NBAST,LOON)
CALL FORMDM(PTDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
ELSE
PTDM=(0.D0,0.D0)
ETOT1=0.D0
END IF
OPEN(16,FILE='plots/diisenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/diiscrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/diiscrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 5
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the total energy
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
IF (ITER==1) THEN
CALL CHECKNUMCONV(PDM,PDMSET(1,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
ELSE
CALL CHECKNUMCONV(PDM,PDMSET(MSET,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
END IF
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
! Storage of the current density matrix, computation and storage of a new DIIS error vector
IF (MSET==MXSET) THEN
! we have reached the maximum allowed dimension for the simplex
PDMSET=EOSHIFT(PDMSET,SHIFT=1) ! elimination of the oldest stored density matrix
ERRSET=EOSHIFT(ERRSET,SHIFT=1) ! elimination of the oldest stored error vector
ELSE
MSET=MSET+1 ! the current dimension of the simplex is increased by one
END IF
PDMSET(MSET,:)=PDM
ERRSET(MSET,:,:)=COMMUTATOR(POEFM+PTEFM,PDMSET(MSET,:),PS,NBAST)
IF (ITER==1) THEN
PTDM=PDM
ELSE
! TO DO: check LINEAR DEPENDENCE???
WRITE(*,*)'Dimension of the density matrix simplex =',MSET
! Computation of the new pseudo-density matrix
! assembly and solving of the linear system associated to the DIIS equations
MM=(MSET+1)*(MSET+2)/2
ALLOCATE(PBM(1:MM))
PBM=(0.D0,0.D0) ; PBM(MM-MSET:MM-1)=(-1.D0,0.D0)
IJ=0
DO J=1,MSET
DO I=1,J
IJ=IJ+1 ; PBM(IJ)=&
&FINNERPRODUCT(MATMUL(ISRS,MATMUL(ERRSET(J,:,:),ISRS)),MATMUL(ISRS,MATMUL(ERRSET(I,:,:),ISRS)),NBAST)
END DO
END DO
ALLOCATE(DIISV(1:MSET+1))
DIISV(1:MSET)=(0.D0,0.D0) ; DIISV(MSET+1)=(-1.D0,0.D0)
ALLOCATE(IPIV(1:MSET+1))
CALL ZHPSV('U',MSET+1,1,PBM,IPIV,DIISV,MSET+1,INFO)
DEALLOCATE(IPIV,PBM)
IF (INFO/=0) GO TO 4
! assembly of the pseudo-density matrix
PTDM=(0.D0,0.D0)
DO I=1,MSET
PTDM=PTDM+DIISV(I)*PDMSET(I,:)
END DO
DEALLOCATE(DIISV)
END IF
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: no convergence after',MAXITR,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPSV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPSV: the factorization has been completed, but the block diagonal matrix is &
&exactly singular, so the solution could not be computed'
END IF
GO TO 5
5 WRITE(*,*)'(called from subroutine DIIS)'
6 DEALLOCATE(PDM,PTDM,PDMSET,PTEFM,PFM,TMP,ISRS,ERRSET)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE DIIS_relativistic
SUBROUTINE DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! DIIS (Direct Inversion in the Iterative Subspace) algorithm (restricted closed-shell Hartree-Fock formalism)
! Reference: P. Pulay, Convergence acceleration of iterative sequences. The case of SCF iteration, Chem. Phys. Lett., 73(2), 393-398, 1980.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE setup_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I,J,IJ,K
INTEGER :: MXSET,MSET,MM
INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PTDM,PBM,DIISV
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ERRSET,PDMSET,TMP
LOGICAL :: NUMCONV
! INITIALIZATIONS AND PRELIMINARIES
! Reading of the maximum dimension of the density matrix simplex
OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO)
READ(100,'(/,i2)')MXSET
CLOSE(100)
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(ERRSET(1:MXSET,1:NBAST*NBAST),PDMSET(1:MXSET,1:NBAST*(NBAST+1)/2),TMP(1:NBAST,1:NBAST))
ITER=0
MSET=0 ; PDMSET=0.D0
PTDM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/diisenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/diiscrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/diiscrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTEFM
- CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
- IF (INFO/=0) GO TO 5
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 5
+ END IF
! Assembly of the density matrix according to the aufbau principle
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the total energy
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'Total energy =',ETOT
! Numerical convergence check
IF (ITER==1) THEN
CALL CHECKNUMCONV(PDM,PDMSET(1,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
ELSE
CALL CHECKNUMCONV(PDM,PDMSET(MSET,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
END IF
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
! Storage of the current density matrix, computation and storage of a new DIIS error vector
IF (MSET==MXSET) THEN
! we have reached the maximum allowed dimension for the simplex
PDMSET=EOSHIFT(PDMSET,SHIFT=1) ! elimination of the oldest stored density matrix
ERRSET=EOSHIFT(ERRSET,SHIFT=1) ! elimination of the oldest stored error vector
ELSE
MSET=MSET+1 ! the current dimension of the simplex is increased by one
END IF
PDMSET(MSET,:)=PDM
TMP=COMMUTATOR(POEFM+PTEFM,PDMSET(MSET,:),PS,NBAST)
IJ=0
DO I=1,NBAST
DO J=1,NBAST
IJ=IJ+1
ERRSET(MSET,IJ)=TMP(I,J)
END DO
END DO
IF (ITER==1) THEN
PTDM=PDM
ELSE
! TO DO: check LINEAR DEPENDENCE by computing a Gram determinant??
WRITE(*,*)'Dimension of the density matrix simplex =',MSET
! Computation of the new pseudo-density matrix
! assembly and solving of the linear system associated to the DIIS equations
MM=(MSET+1)*(MSET+2)/2
ALLOCATE(PBM(1:MM))
PBM=0.D0 ; PBM(MM-MSET:MM-1)=-1.D0
IJ=0
DO J=1,MSET
DO I=1,J
IJ=IJ+1 ; PBM(IJ)=PBM(IJ)+DOT_PRODUCT(ERRSET(J,:),ERRSET(I,:))
END DO
END DO
ALLOCATE(DIISV(1:MSET+1))
DIISV(1:MSET)=0.D0 ; DIISV(MSET+1)=-1.D0
ALLOCATE(IPIV(1:MSET+1))
CALL DSPSV('U',MSET+1,1,PBM,IPIV,DIISV,MSET+1,INFO)
DEALLOCATE(IPIV,PBM)
IF (INFO/=0) GO TO 4
! assembly of the pseudo-density matrix
PTDM=0.D0
DO I=1,MSET
PTDM=PTDM+DIISV(I)*PDMSET(I,:)
END DO
DEALLOCATE(DIISV)
END IF
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: no convergence after',MAXITR,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPSV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPSV: the factorization has been completed, but the block diagonal matrix is &
&exactly singular, so the solution could not be computed'
END IF
GO TO 5
5 WRITE(*,*)'(called from subroutine DIIS)'
6 DEALLOCATE(PDM,PTDM,PDMSET,PTEFM,PFM,TMP,ERRSET)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE DIIS_RHF
+
+SUBROUTINE DIIS_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+! DIIS (Direct Inversion in the Iterative Subspace) algorithm (restricted closed-shell Hartree-Fock formalism)
+! Reference: P. Pulay, Convergence acceleration of iterative sequences. The case of SCF iteration, Chem. Phys. Lett., 73(2), 393-398, 1980.
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE setup_tools
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
+ DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+
+ INTEGER :: ITER,INFO,I,J,IJ,K
+ INTEGER :: MXSET,MSET,MM
+ INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV
+ DOUBLE PRECISION :: ETOT,ETOT1
+ DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PTDM,PBM,DIISV
+ DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ERRSET,PDMSET,TMP
+ LOGICAL :: NUMCONV
+
+! INITIALIZATIONS AND PRELIMINARIES
+! Reading of the maximum dimension of the density matrix simplex
+ OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
+ CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO)
+ READ(100,'(/,i2)')MXSET
+ CLOSE(100)
+
+ ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(ERRSET(1:MXSET,1:NBAST*NBAST),PDMSET(1:MXSET,1:NBAST*(NBAST+1)/2),TMP(1:NBAST,1:NBAST))
+
+ ITER=0
+ MSET=0 ; PDMSET=0.D0
+ PTDM=0.D0
+ ETOT1=0.D0
+ OPEN(16,FILE='plots/diisenrgy.txt',STATUS='unknown',ACTION='write')
+ OPEN(17,FILE='plots/diiscrit1.txt',STATUS='unknown',ACTION='write')
+ OPEN(18,FILE='plots/diiscrit2.txt',STATUS='unknown',ACTION='write')
+
+! LOOP
+1 CONTINUE
+ ITER=ITER+1
+ WRITE(*,*)' '
+ WRITE(*,*)'# ITER =',ITER
+
+! Assembly and diagonalization of the Fock matrix
+ CALL BUILDTEFM_GHF(PTEFM,NBAST,PHI,PTDM)
+ PFM=POEFM+PTEFM
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 5
+ END IF
+! Assembly of the density matrix according to the aufbau principle
+ CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE)
+! Computation of the total energy
+ CALL BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY_GHF(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'Total energy =',ETOT
+! Numerical convergence check
+ IF (ITER==1) THEN
+ CALL CHECKNUMCONV(PDM,PDMSET(1,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ ELSE
+ CALL CHECKNUMCONV(PDM,PDMSET(MSET,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ END IF
+ IF (NUMCONV) THEN
+! Convergence reached
+ GO TO 2
+ ELSE IF (ITER==MAXITR) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 3
+ ELSE
+! Convergence not reached, increment
+ ETOT1=ETOT
+! Storage of the current density matrix, computation and storage of a new DIIS error vector
+ IF (MSET==MXSET) THEN
+! we have reached the maximum allowed dimension for the simplex
+ PDMSET=EOSHIFT(PDMSET,SHIFT=1) ! elimination of the oldest stored density matrix
+ ERRSET=EOSHIFT(ERRSET,SHIFT=1) ! elimination of the oldest stored error vector
+ ELSE
+ MSET=MSET+1 ! the current dimension of the simplex is increased by one
+ END IF
+ PDMSET(MSET,:)=PDM
+ TMP=COMMUTATOR(POEFM+PTEFM,PDMSET(MSET,:),PS,NBAST)
+ IJ=0
+ DO I=1,NBAST
+ DO J=1,NBAST
+ IJ=IJ+1
+ ERRSET(MSET,IJ)=TMP(I,J)
+ END DO
+ END DO
+ IF (ITER==1) THEN
+ PTDM=PDM
+ ELSE
+! TO DO: check LINEAR DEPENDENCE by computing a Gram determinant??
+ WRITE(*,*)'Dimension of the density matrix simplex =',MSET
+! Computation of the new pseudo-density matrix
+! assembly and solving of the linear system associated to the DIIS equations
+ MM=(MSET+1)*(MSET+2)/2
+ ALLOCATE(PBM(1:MM))
+ PBM=0.D0 ; PBM(MM-MSET:MM-1)=-1.D0
+ IJ=0
+ DO J=1,MSET
+ DO I=1,J
+ IJ=IJ+1 ; PBM(IJ)=PBM(IJ)+DOT_PRODUCT(ERRSET(J,:),ERRSET(I,:))
+ END DO
+ END DO
+ ALLOCATE(DIISV(1:MSET+1))
+ DIISV(1:MSET)=0.D0 ; DIISV(MSET+1)=-1.D0
+ ALLOCATE(IPIV(1:MSET+1))
+ CALL DSPSV('U',MSET+1,1,PBM,IPIV,DIISV,MSET+1,INFO)
+ DEALLOCATE(IPIV,PBM)
+ IF (INFO/=0) GO TO 4
+! assembly of the pseudo-density matrix
+ PTDM=0.D0
+ DO I=1,MSET
+ PTDM=PTDM+DIISV(I)*PDMSET(I,:)
+ END DO
+ DEALLOCATE(DIISV)
+ END IF
+ GO TO 1
+ END IF
+! MESSAGES
+2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,*)I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 6
+3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: no convergence after',MAXITR,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,*)I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 6
+4 IF (INFO<0) THEN
+ WRITE(*,*)'Subroutine ZHPSV: the',-INFO,'-th argument had an illegal value'
+ ELSE
+ WRITE(*,*)'Subroutine ZHPSV: the factorization has been completed, but the block diagonal matrix is &
+ &exactly singular, so the solution could not be computed'
+ END IF
+ GO TO 5
+5 WRITE(*,*)'(called from subroutine DIIS)'
+6 DEALLOCATE(PDM,PTDM,PDMSET,PTEFM,PFM,TMP,ERRSET)
+ CLOSE(16) ; CLOSE(17) ; CLOSE(18)
+END SUBROUTINE DIIS_GHF
diff --git a/src/drivers.f90 b/src/drivers.f90
index 78c0bd0..d136d83 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,612 +1,612 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
! complex GHF
IF(MODEL == 3) THEN
SSINTEGRALS = .FALSE.
SLINTEGRALS = .FALSE.
END IF
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
IF(RESUME) THEN
OPEN(100,FILE='eig.txt')
READ(100,*) EIG
OPEN(101,FILE='eigvec_r.txt')
OPEN(102,FILE='eigvec_i.txt')
CALL READMATRIX(EIGVEC,NBAST,101,102)
CLOSE(100)
CLOSE(101)
CLOSE(102)
END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (3)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
OPEN(100,FILE='eig.txt')
WRITE(100,*) EIG
OPEN(101,FILE='eigvec_r.txt')
OPEN(102,FILE='eigvec_i.txt')
CALL PRINTMATRIX(EIGVEC,NBAST,101,102)
CLOSE(100)
CLOSE(101)
CLOSE(102)
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
! Computation of the discretization basis
IF(MODEL == 4) THEN
CALL FORMBASIS_GHF(PHI,NBAS)
ELSE
CALL FORMBASIS(PHI,NBAS)
END IF
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOM_GHF(POM,PHI,NBAST)
ELSE
CALL BUILDOM(POM,PHI,NBAST)
END IF
PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOEFM_GHF(POEFM,PHI,NBAST)
ELSE
CALL BUILDOEFM(POEFM,PHI,NBAST)
END IF
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
IF(RESUME) THEN
OPEN(100,FILE='eig.txt')
READ(100,*) EIG
OPEN(101,FILE='eigvec.txt')
CALL READMATRIX(EIGVEC,NBAST,101)
CLOSE(100)
CLOSE(101)
END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL LEVELSHIFTING_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
- CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ CALL DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
- WRITE(*,*)' Not implemented yet!'
+ CALL DIIS_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
OPEN(100,FILE='eig.txt')
WRITE(100,*) EIG
OPEN(101,FILE='eigvec.txt')
CALL PRINTMATRIX(EIGVEC,NBAST,101)
CLOSE(100)
CLOSE(101)
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
|
antoine-levitt/ACCQUAREL
|
d7750353c72661cb210ba1ca46be1fb820539c86
|
LEVELSHIFTING_GHF
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index fa57316..78c0bd0 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,612 +1,612 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
! complex GHF
IF(MODEL == 3) THEN
SSINTEGRALS = .FALSE.
SLINTEGRALS = .FALSE.
END IF
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
IF(RESUME) THEN
OPEN(100,FILE='eig.txt')
READ(100,*) EIG
OPEN(101,FILE='eigvec_r.txt')
OPEN(102,FILE='eigvec_i.txt')
CALL READMATRIX(EIGVEC,NBAST,101,102)
CLOSE(100)
CLOSE(101)
CLOSE(102)
END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (3)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
OPEN(100,FILE='eig.txt')
WRITE(100,*) EIG
OPEN(101,FILE='eigvec_r.txt')
OPEN(102,FILE='eigvec_i.txt')
CALL PRINTMATRIX(EIGVEC,NBAST,101,102)
CLOSE(100)
CLOSE(101)
CLOSE(102)
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
! Computation of the discretization basis
IF(MODEL == 4) THEN
CALL FORMBASIS_GHF(PHI,NBAS)
ELSE
CALL FORMBASIS(PHI,NBAS)
END IF
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOM_GHF(POM,PHI,NBAST)
ELSE
CALL BUILDOM(POM,PHI,NBAST)
END IF
PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOEFM_GHF(POEFM,PHI,NBAST)
ELSE
CALL BUILDOEFM(POEFM,PHI,NBAST)
END IF
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
IF(RESUME) THEN
OPEN(100,FILE='eig.txt')
READ(100,*) EIG
OPEN(101,FILE='eigvec.txt')
CALL READMATRIX(EIGVEC,NBAST,101)
CLOSE(100)
CLOSE(101)
END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
- CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ CALL LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
- WRITE(*,*)' Not implemented yet!'
+ CALL LEVELSHIFTING_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
OPEN(100,FILE='eig.txt')
WRITE(100,*) EIG
OPEN(101,FILE='eigvec.txt')
CALL PRINTMATRIX(EIGVEC,NBAST,101)
CLOSE(100)
CLOSE(101)
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
diff --git a/src/levelshifting.f90 b/src/levelshifting.f90
index 1da47bb..ead1d06 100644
--- a/src/levelshifting.f90
+++ b/src/levelshifting.f90
@@ -1,178 +1,269 @@
SUBROUTINE LEVELSHIFTING_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Level-shifting algorithm (relativistic case)
! Reference: V. R. Saunders and I. H. Hillier, A "level-shifting" method for converging closed shell Hartree-Fock wave functions, Int. J. Quantum Chem., 7(4), 699-705, 1973.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: SHIFT,ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
! Reading of the shift parameter
OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO)
READ(100,'(/,f16.8)')SHIFT
CLOSE(100)
WRITE(*,*)'Shift parameter value =',SHIFT
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/shftenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/shftcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/shftcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM-SHIFT*ABA(PS,PDM,NBAST)
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine LEVELSHIFTING: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine LEVELSHIFTING: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine LEVELSHIFTING)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE LEVELSHIFTING_relativistic
SUBROUTINE LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Level-shifting algorithm (restricted closed-shell Hartree-Fock formalism)
! Reference: V. R. Saunders and I. H. Hillier, A "level-shifting" method for converging closed shell Hartree-Fock wave functions, Int. J. Quantum Chem., 7(4), 699-705, 1973.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE setup_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: SHIFT,ETOT,ETOT1
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
! Reading of the shift parameter
OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO)
READ(100,'(/,f16.8)')SHIFT
CLOSE(100)
WRITE(*,*)'Shift parameter value =',SHIFT
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=0.D0
PTEFM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/shftenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/shftcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/shftcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM-SHIFT*ABA(PS,PDM,NBAST)
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine LEVELSHIFTING: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine LEVELSHIFTING: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine LEVELSHIFTING)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE LEVELSHIFTING_RHF
+
+SUBROUTINE LEVELSHIFTING_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+! Level-shifting algorithm (restricted closed-shell Hartree-Fock formalism)
+! Reference: V. R. Saunders and I. H. Hillier, A "level-shifting" method for converging closed shell Hartree-Fock wave functions, Int. J. Quantum Chem., 7(4), 699-705, 1973.
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE setup_tools
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
+ DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+
+ INTEGER :: ITER,INFO,I
+ DOUBLE PRECISION :: SHIFT,ETOT,ETOT1
+ DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
+ LOGICAL :: NUMCONV
+
+! INITIALIZATION AND PRELIMINARIES
+! Reading of the shift parameter
+ OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
+ CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO)
+ READ(100,'(/,f16.8)')SHIFT
+ CLOSE(100)
+ WRITE(*,*)'Shift parameter value =',SHIFT
+
+ ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
+
+ ITER=0
+ PDM=0.D0
+ PTEFM=0.D0
+ ETOT1=0.D0
+ OPEN(16,FILE='plots/shftenrgy.txt',STATUS='unknown',ACTION='write')
+ OPEN(17,FILE='plots/shftcrit1.txt',STATUS='unknown',ACTION='write')
+ OPEN(18,FILE='plots/shftcrit2.txt',STATUS='unknown',ACTION='write')
+
+! LOOP
+1 CONTINUE
+ ITER=ITER+1
+ WRITE(*,*)' '
+ WRITE(*,*)'# ITER =',ITER
+
+! Assembly and diagonalization of the Fock matrix
+ PFM=POEFM+PTEFM-SHIFT*ABA(PS,PDM,NBAST)
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+ END IF
+! Assembly of the density matrix according to the aufbau principle
+ PDM1=PDM
+ CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE)
+! Computation of the energy associated to the density matrix
+ CALL BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY_GHF(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'E(D_n)=',ETOT
+! Numerical convergence check
+ CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ IF (NUMCONV) THEN
+! Convergence reached
+ GO TO 2
+ ELSE IF (ITER==MAXITR) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 3
+ ELSE
+! Convergence not reached, increment
+ ETOT1=ETOT
+ GO TO 1
+ END IF
+
+! MESSAGES
+2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine LEVELSHIFTING: convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,*)I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 5
+3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine LEVELSHIFTING: no convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,*)I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 5
+4 WRITE(*,*)'(called from subroutine LEVELSHIFTING)'
+5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
+ CLOSE(16) ; CLOSE(17) ; CLOSE(18)
+END SUBROUTINE LEVELSHIFTING_GHF
|
antoine-levitt/ACCQUAREL
|
368227bf4778b989c2550702727a688dd4a05934
|
Fix ODA_GHF
|
diff --git a/src/oda.f90 b/src/oda.f90
index d6cef64..9296ce9 100644
--- a/src/oda.f90
+++ b/src/oda.f90
@@ -1,227 +1,230 @@
SUBROUTINE ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Optimal Damping Algorithm (non-relativistic case: restricted closed-shell Hartree-Fock formalism)
! Reference: E. Cancès and C. Le Bris, Can we outperform the DIIS approach for electronic structure calculations?, Internat. J. Quantum Chem., 79(2), 2000.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,ETTOT
DOUBLE PRECISION :: ALPHA,BETA,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1,PTDM,PDMDIF
LOGICAL :: NUMCONV
! INITIALIZATIONS AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=0.D0 ; PTDM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/odaenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/odacrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/odacrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 5
! Assembly of the density matrix according to the aufbau principle
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
! Optimization step for the assembly of the pseudo-density matrix
PDMDIF=PDM-PTDM
BETA=TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)
IF (BETA>0.D0) THEN
WRITE(*,*)'Warning: internal computation error (beta>0).'
GO TO 4
ELSE
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF)
ALPHA=TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)
WRITE(*,*)'alpha =',ALPHA,'beta =',BETA
IF (ALPHA>0.D0) THEN
LAMBDA=-BETA/ALPHA
IF (LAMBDA<1.D0) THEN
WRITE(*,*)'lambda=',LAMBDA
PTDM=PTDM+LAMBDA*PDMDIF
ELSE
WRITE(*,*)'lambda=1.'
PTDM=PDM
END IF
ELSE IF (ALPHA<0.D0) THEN
WRITE(*,*)'lambda=1.'
PTDM=PDM
ELSE
WRITE(*,*)'Warning: internal computation error (alpha=0).'
GO TO 4
END IF
END IF
ETOT1=ETOT
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
! Energy associated to the pseudo density matrix
ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST)
WRITE(*,*)'E(tilde{D}_n)=',ETTOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: convergence after',ITER,'iteration(s).'
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: no convergence after',ITER,'iteration(s).'
GO TO 6
4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: computation stopped after',ITER,'iteration(s).'
GO TO 6
5 WRITE(*,*)'(called from subroutine ODA)'
GO TO 7
6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
7 DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM)
CLOSE(16) ; CLOSE(17) ;CLOSE(18)
END SUBROUTINE ODA_RHF
SUBROUTINE ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Optimal Damping Algorithm (non-relativistic case: general Hartree-Fock formalism)
! Reference: E. Cancès and C. Le Bris, Can we outperform the DIIS approach for electronic structure calculations?, Internat. J. Quantum Chem., 79(2), 2000.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,ETTOT
DOUBLE PRECISION :: ALPHA,BETA,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1,PTDM,PDMDIF
LOGICAL :: NUMCONV
! INITIALIZATIONS AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=0.D0 ; PTDM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/odaenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/odacrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/odacrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix
CALL BUILDTEFM_GHF(PTTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTTEFM
- CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
- IF (INFO/=0) GO TO 5
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 5
+ END IF
+
! Assembly of the density matrix according to the aufbau principle
PDM1=PDM
- CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
+ CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY_GHF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
! Optimization step for the assembly of the pseudo-density matrix
PDMDIF=PDM-PTDM
BETA=TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)
IF (BETA>0.D0) THEN
WRITE(*,*)'Warning: internal computation error (beta>0).'
write(*,*) BETA
BETA = 0
END IF
! IF (BETA>0.D0) THEN
! WRITE(*,*)'Warning: internal computation error (beta>0).'
! write(*,*) BETA
! GO TO 4
! ELSE
CALL BUILDTEFM_GHF(PTTEFM,NBAST,PHI,PDMDIF)
ALPHA=TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)
WRITE(*,*)'alpha =',ALPHA,'beta =',BETA
IF (ALPHA>0.D0) THEN
LAMBDA=-BETA/ALPHA
IF (LAMBDA<1.D0) THEN
WRITE(*,*)'lambda=',LAMBDA
PTDM=PTDM+LAMBDA*PDMDIF
ELSE
WRITE(*,*)'lambda=1.'
PTDM=PDM
END IF
ELSE IF (ALPHA<0.D0) THEN
WRITE(*,*)'lambda=1.'
PTDM=PDM
ELSE
WRITE(*,*)'Warning: internal computation error (alpha=0).'
GO TO 4
END IF
! END IF
ETOT1=ETOT
CALL BUILDTEFM_GHF(PTTEFM,NBAST,PHI,PTDM)
! Energy associated to the pseudo density matrix
ETTOT=ENERGY_GHF(POEFM,PTTEFM,PTDM,NBAST)
WRITE(*,*)'E(tilde{D}_n)=',ETTOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: convergence after',ITER,'iteration(s).'
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: no convergence after',ITER,'iteration(s).'
GO TO 6
4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: computation stopped after',ITER,'iteration(s).'
GO TO 6
5 WRITE(*,*)'(called from subroutine ODA)'
GO TO 7
6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
7 DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM)
CLOSE(16) ; CLOSE(17) ;CLOSE(18)
END SUBROUTINE ODA_GHF
|
antoine-levitt/ACCQUAREL
|
6f9e381bf42caf2aadb11bb9c5edec8e2133fe4c
|
ODA_GHF
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index 7a150c6..fa57316 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,612 +1,612 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
! complex GHF
IF(MODEL == 3) THEN
SSINTEGRALS = .FALSE.
SLINTEGRALS = .FALSE.
END IF
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
IF(RESUME) THEN
OPEN(100,FILE='eig.txt')
READ(100,*) EIG
OPEN(101,FILE='eigvec_r.txt')
OPEN(102,FILE='eigvec_i.txt')
CALL READMATRIX(EIGVEC,NBAST,101,102)
CLOSE(100)
CLOSE(101)
CLOSE(102)
END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (3)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
OPEN(100,FILE='eig.txt')
WRITE(100,*) EIG
OPEN(101,FILE='eigvec_r.txt')
OPEN(102,FILE='eigvec_i.txt')
CALL PRINTMATRIX(EIGVEC,NBAST,101,102)
CLOSE(100)
CLOSE(101)
CLOSE(102)
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
! Computation of the discretization basis
IF(MODEL == 4) THEN
CALL FORMBASIS_GHF(PHI,NBAS)
ELSE
CALL FORMBASIS(PHI,NBAS)
END IF
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOM_GHF(POM,PHI,NBAST)
ELSE
CALL BUILDOM(POM,PHI,NBAST)
END IF
PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOEFM_GHF(POEFM,PHI,NBAST)
ELSE
CALL BUILDOEFM(POEFM,PHI,NBAST)
END IF
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
IF(RESUME) THEN
OPEN(100,FILE='eig.txt')
READ(100,*) EIG
OPEN(101,FILE='eigvec.txt')
CALL READMATRIX(EIGVEC,NBAST,101)
CLOSE(100)
CLOSE(101)
END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
- CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ CALL ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
- WRITE(*,*)' Not implemented yet!'
+ CALL ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
OPEN(100,FILE='eig.txt')
WRITE(100,*) EIG
OPEN(101,FILE='eigvec.txt')
CALL PRINTMATRIX(EIGVEC,NBAST,101)
CLOSE(100)
CLOSE(101)
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
diff --git a/src/oda.f90 b/src/oda.f90
index 1d72fa7..d6cef64 100644
--- a/src/oda.f90
+++ b/src/oda.f90
@@ -1,110 +1,227 @@
SUBROUTINE ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Optimal Damping Algorithm (non-relativistic case: restricted closed-shell Hartree-Fock formalism)
! Reference: E. Cancès and C. Le Bris, Can we outperform the DIIS approach for electronic structure calculations?, Internat. J. Quantum Chem., 79(2), 2000.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,ETTOT
DOUBLE PRECISION :: ALPHA,BETA,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1,PTDM,PDMDIF
LOGICAL :: NUMCONV
! INITIALIZATIONS AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=0.D0 ; PTDM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/odaenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/odacrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/odacrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 5
! Assembly of the density matrix according to the aufbau principle
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
! Optimization step for the assembly of the pseudo-density matrix
PDMDIF=PDM-PTDM
BETA=TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)
IF (BETA>0.D0) THEN
WRITE(*,*)'Warning: internal computation error (beta>0).'
GO TO 4
ELSE
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF)
ALPHA=TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)
WRITE(*,*)'alpha =',ALPHA,'beta =',BETA
IF (ALPHA>0.D0) THEN
LAMBDA=-BETA/ALPHA
IF (LAMBDA<1.D0) THEN
WRITE(*,*)'lambda=',LAMBDA
PTDM=PTDM+LAMBDA*PDMDIF
ELSE
WRITE(*,*)'lambda=1.'
PTDM=PDM
END IF
ELSE IF (ALPHA<0.D0) THEN
WRITE(*,*)'lambda=1.'
PTDM=PDM
ELSE
WRITE(*,*)'Warning: internal computation error (alpha=0).'
GO TO 4
END IF
END IF
ETOT1=ETOT
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
! Energy associated to the pseudo density matrix
ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST)
WRITE(*,*)'E(tilde{D}_n)=',ETTOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: convergence after',ITER,'iteration(s).'
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: no convergence after',ITER,'iteration(s).'
GO TO 6
4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: computation stopped after',ITER,'iteration(s).'
GO TO 6
5 WRITE(*,*)'(called from subroutine ODA)'
GO TO 7
6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
7 DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM)
CLOSE(16) ; CLOSE(17) ;CLOSE(18)
END SUBROUTINE ODA_RHF
+
+SUBROUTINE ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+! Optimal Damping Algorithm (non-relativistic case: general Hartree-Fock formalism)
+! Reference: E. Cancès and C. Le Bris, Can we outperform the DIIS approach for electronic structure calculations?, Internat. J. Quantum Chem., 79(2), 2000.
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
+ DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+
+ INTEGER :: ITER,INFO,I
+ DOUBLE PRECISION :: ETOT,ETOT1,ETTOT
+ DOUBLE PRECISION :: ALPHA,BETA,LAMBDA
+ DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1,PTDM,PDMDIF
+ LOGICAL :: NUMCONV
+
+! INITIALIZATIONS AND PRELIMINARIES
+ ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
+
+ ITER=0
+ PDM=0.D0 ; PTDM=0.D0
+ ETOT1=0.D0
+ OPEN(16,FILE='plots/odaenrgy.txt',STATUS='unknown',ACTION='write')
+ OPEN(17,FILE='plots/odacrit1.txt',STATUS='unknown',ACTION='write')
+ OPEN(18,FILE='plots/odacrit2.txt',STATUS='unknown',ACTION='write')
+
+! LOOP
+1 CONTINUE
+ ITER=ITER+1
+ WRITE(*,*)' '
+ WRITE(*,*)'# ITER =',ITER
+
+! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix
+ CALL BUILDTEFM_GHF(PTTEFM,NBAST,PHI,PTDM)
+ PFM=POEFM+PTTEFM
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 5
+! Assembly of the density matrix according to the aufbau principle
+ PDM1=PDM
+ CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
+! Computation of the energy associated to the density matrix
+ CALL BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY_GHF(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'E(D_n)=',ETOT
+! Numerical convergence check
+ CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ IF (NUMCONV) THEN
+! Convergence reached
+ GO TO 2
+ ELSE IF (ITER==MAXITR) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 3
+ ELSE
+! Convergence not reached, increment
+! Optimization step for the assembly of the pseudo-density matrix
+ PDMDIF=PDM-PTDM
+ BETA=TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)
+ IF (BETA>0.D0) THEN
+ WRITE(*,*)'Warning: internal computation error (beta>0).'
+ write(*,*) BETA
+ BETA = 0
+ END IF
+ ! IF (BETA>0.D0) THEN
+ ! WRITE(*,*)'Warning: internal computation error (beta>0).'
+ ! write(*,*) BETA
+ ! GO TO 4
+ ! ELSE
+ CALL BUILDTEFM_GHF(PTTEFM,NBAST,PHI,PDMDIF)
+ ALPHA=TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)
+ WRITE(*,*)'alpha =',ALPHA,'beta =',BETA
+ IF (ALPHA>0.D0) THEN
+ LAMBDA=-BETA/ALPHA
+ IF (LAMBDA<1.D0) THEN
+ WRITE(*,*)'lambda=',LAMBDA
+ PTDM=PTDM+LAMBDA*PDMDIF
+ ELSE
+ WRITE(*,*)'lambda=1.'
+ PTDM=PDM
+ END IF
+ ELSE IF (ALPHA<0.D0) THEN
+ WRITE(*,*)'lambda=1.'
+ PTDM=PDM
+ ELSE
+ WRITE(*,*)'Warning: internal computation error (alpha=0).'
+ GO TO 4
+ END IF
+ ! END IF
+ ETOT1=ETOT
+ CALL BUILDTEFM_GHF(PTTEFM,NBAST,PHI,PTDM)
+! Energy associated to the pseudo density matrix
+ ETTOT=ENERGY_GHF(POEFM,PTTEFM,PTDM,NBAST)
+ WRITE(*,*)'E(tilde{D}_n)=',ETTOT
+ GO TO 1
+ END IF
+! MESSAGES
+2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: convergence after',ITER,'iteration(s).'
+ GO TO 6
+3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: no convergence after',ITER,'iteration(s).'
+ GO TO 6
+4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ODA: computation stopped after',ITER,'iteration(s).'
+ GO TO 6
+5 WRITE(*,*)'(called from subroutine ODA)'
+ GO TO 7
+6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,*)I,EIG(I)
+ END DO
+ CLOSE(9)
+7 DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM)
+ CLOSE(16) ; CLOSE(17) ;CLOSE(18)
+END SUBROUTINE ODA_GHF
|
antoine-levitt/ACCQUAREL
|
53266b4326e171c0a2005ee6f9a48272d5a52714
|
Implement a simple kind of resume
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index 031151c..7a150c6 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,581 +1,612 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
- LOGICAL :: RESUME
-
-! POUR L'INSTANT
- RESUME=.FALSE.
! complex GHF
IF(MODEL == 3) THEN
SSINTEGRALS = .FALSE.
SLINTEGRALS = .FALSE.
END IF
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
+ IF(RESUME) THEN
+ OPEN(100,FILE='eig.txt')
+ READ(100,*) EIG
+ OPEN(101,FILE='eigvec_r.txt')
+ OPEN(102,FILE='eigvec_i.txt')
+ CALL READMATRIX(EIGVEC,NBAST,101,102)
+ CLOSE(100)
+ CLOSE(101)
+ CLOSE(102)
+ END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (3)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
+
+ OPEN(100,FILE='eig.txt')
+ WRITE(100,*) EIG
+ OPEN(101,FILE='eigvec_r.txt')
+ OPEN(102,FILE='eigvec_i.txt')
+ CALL PRINTMATRIX(EIGVEC,NBAST,101,102)
+ CLOSE(100)
+ CLOSE(101)
+ CLOSE(102)
+
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
- LOGICAL :: RESUME
! Computation of the discretization basis
IF(MODEL == 4) THEN
CALL FORMBASIS_GHF(PHI,NBAS)
ELSE
CALL FORMBASIS(PHI,NBAS)
END IF
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOM_GHF(POM,PHI,NBAST)
ELSE
CALL BUILDOM(POM,PHI,NBAST)
END IF
PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOEFM_GHF(POEFM,PHI,NBAST)
ELSE
CALL BUILDOEFM(POEFM,PHI,NBAST)
END IF
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
+ IF(RESUME) THEN
+ OPEN(100,FILE='eig.txt')
+ READ(100,*) EIG
+ OPEN(101,FILE='eigvec.txt')
+ CALL READMATRIX(EIGVEC,NBAST,101)
+ CLOSE(100)
+ CLOSE(101)
+ END IF
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
+
+ OPEN(100,FILE='eig.txt')
+ WRITE(100,*) EIG
+ OPEN(101,FILE='eigvec.txt')
+ CALL PRINTMATRIX(EIGVEC,NBAST,101)
+ CLOSE(100)
+ CLOSE(101)
+
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
diff --git a/src/roothaan.f90 b/src/roothaan.f90
index 4bc8a5c..088d410 100644
--- a/src/roothaan.f90
+++ b/src/roothaan.f90
@@ -1,436 +1,442 @@
SUBROUTINE ROOTHAAN_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
- CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
- IF (INFO/=0) GO TO 4
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+ END IF
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE ROOTHAAN_relativistic
SUBROUTINE ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (restricted closed-shell Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=0.D0
PTEFM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
- CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
- IF (INFO/=0) GO TO 4
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+ END IF
! Assembly of the density matrix according to the aufbau principle
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE ROOTHAAN_RHF
SUBROUTINE ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (unrestricted open-shell Hartree-Fock formalism).
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PEMS,PFMA,PFMB,PDMA,PDMB,PTDM,PSDM,PTDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDMA(1:NBAST*(NBAST+1)/2),PDMB(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTDM(1:NBAST*(NBAST+1)/2),PSDM(1:NBAST*(NBAST+1)/2),PTDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PEMS(1:NBAST*(NBAST+1)/2),PFMA(1:NBAST*(NBAST+1)/2),PFMB(1:NBAST*(NBAST+1)/2))
ITER=0
PTDM=0.D0
PFMA=POEFM ; PFMB=POEFM
ETOT1=0.D0
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Diagonalization of the Fock matrix for $\alpha$ spin orbitals
CALL EIGENSOLVER(PFMA,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix for $\alpha$ spin orbitals according to the aufbau principle
CALL FORMDM(PDMA,EIGVEC,NBAST,1,NBEA)
! Diagonalization of the Fock matrix for $\beta$ spin orbitals
CALL EIGENSOLVER(PFMB,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix for $\beta$ spin orbitals according to the aufbau principle
CALL FORMDM(PDMB,EIGVEC,NBAST,1,NBEB)
! Assembly of the total and spin density matrices
PTDM1=PTDM
PTDM=PDMA+PDMB ; PSDM=PDMA-PDMB
! Computation of the energy associated to the density matrices
CALL BUILDTEFM(PTEFM,NBAST,PHI,PTDM)
CALL BUILDEXCHANGE(PEMS,NBAST,PHI,PSDM)
ETOT=ENERGY(POEFM,PTEFM,PEMS,PTDM,PSDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Assembly of the Fock matrices
PFMA=POEFM+0.5D0*(PTEFM-PEMS) ; PFMB=POEFM+0.5D0*(PTEFM+PEMS)
CALL OUTPUT_ITER(ITER,PTDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDMA,PDMB,PTDM1,PFMA,PFMB,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 CALL OUTPUT_FINALIZE(ITER,PTDM,PHI,NBAST,EIG,EIGVEC,ETOT)
DEALLOCATE(PDMA,PDMB,PTDM,PSDM,PTDM1,PTEFM,PEMS,PFMA,PFMB)
END SUBROUTINE ROOTHAAN_UHF
SUBROUTINE ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
! Roothaan's algorithm (average-of-configuration open-shell Dirac-Hartree-Fock formalism).
! Reference(s)?
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: f,a,alpha
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFMC,PTEFMO,PFMC,PFMO,PDMC,PDMO,PDMC1,PDMO1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDMC(1:NBAST*(NBAST+1)/2),PDMO(1:NBAST*(NBAST+1)/2),PDMC1(1:NBAST*(NBAST+1)/2),PDMO1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFMC(1:NBAST*(NBAST+1)/2),PTEFMO(1:NBAST*(NBAST+1)/2),PFMC(1:NBAST*(NBAST+1)/2),PFMO(1:NBAST*(NBAST+1)/2))
f=REAL(NBEOS)/REAL(NBOOS) ; a=REAL(NBOOS*(NBEOS-1))/REAL(NBEOS*(NBOOS-1)) ; alpha=(1.D0-a)/(1.D0-f)
ITER=0
PDMC=(0.D0,0.D0) ; PDMO=(0.D0,0.D0)
PFMC=POEFM ; PFMO=POEFM
ETOT1=0.D0
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Diagonalization of the Fock matrix for closed-shell orbitals
CALL EIGENSOLVER(PFMC,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix for closed-shell orbitals according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDMC1=PDMC
CALL FORMDM(PDMC,EIGVEC,NBAST,LOON,LOON+NBECS-1)
! Diagonalization of the Fock matrix for open-shell orbitals
CALL EIGENSOLVER(PFMO,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix for open-shell orbitals according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDMO1=PDMO
CALL FORMDM(PDMO,EIGVEC,NBAST,LOON,LOON+NBOOS-1)
PDMO=f*PDMO
! Computation of the energy associated to the closed and open-shell density matrices
CALL BUILDTEFM(PTEFMC,NBAST,PHI,PDMC)
CALL BUILDTEFM(PTEFMO,NBAST,PHI,PDMO)
ETOT=ENERGY_AOCOSDHF(POEFM,PTEFMC,PTEFMO,PDMC,PDMO,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Assembly of the Fock matrices for closed and open-shell orbitals
PFMC=POEFM+PTEFMC+PTEFMO+alpha*ABC_CBA(PS,PDMO,PTEFMO,NBAST)
PFMO=POEFM+PTEFMC+a*PTEFMO+alpha*ABC_CBA(PS,PDMC,PTEFMO,NBAST)
! TODO: CHECK PDMC+PDMO
CALL OUTPUT_ITER(ITER,PDMC+PDMO,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDMC,PDMO,PDMC1,PDMO1,PFMC,PFMO,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 CALL OUTPUT_FINALIZE(ITER,PDMC+PDMO,PHI,NBAST,EIG,EIGVEC,ETOT)
DEALLOCATE(PDMC,PDMO,PDMC1,PDMO1,PTEFMC,PTEFMO,PFMC,PFMO)
END SUBROUTINE ROOTHAAN_AOCOSDHF
-SUBROUTINE ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
+SUBROUTINE ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (restricted closed-shell Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
- ! LOGICAL,INTENT(IN) :: RESUME
+ LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=0.D0
PTEFM=0.D0
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
- CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
- IF (INFO/=0) GO TO 4
+ IF(.NOT.(RESUME .AND. ITER == 1)) THEN
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+ END IF
! Assembly of the density matrix according to the aufbau principle
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY_GHF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
END SUBROUTINE ROOTHAAN_GHF
diff --git a/src/setup.f90 b/src/setup.f90
index 52adb32..eb564d6 100644
--- a/src/setup.f90
+++ b/src/setup.f90
@@ -122,642 +122,653 @@ SUBROUTINE SETUP_FORMALISM
END IF
END IF
END IF
CLOSE(100)
RETURN
1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!'
STOP
END SUBROUTINE SETUP_FORMALISM
END MODULE
MODULE data_parameters
USE iso_c_binding
! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS **
! number of nuclei in the molecular system (at most 10)
INTEGER :: NBN
! atomic numbers of the nuclei
INTEGER,DIMENSION(10) :: Z
! positions of the nucleii
DOUBLE PRECISION,DIMENSION(3,10) :: CENTER
! total number of electrons in the molecular system
INTEGER :: NBE
! total number of electrons in the closed shells (open-shell DHF formalism)
INTEGER :: NBECS
! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism)
INTEGER :: NBEOS,NBOOS
! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms)
INTEGER :: NBEA,NBEB
! internuclear repulsion energy
DOUBLE PRECISION :: INTERNUCLEAR_ENERGY
! ** DATA FOR BOSON STAR MODEL **
DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0
! mass
DOUBLE PRECISION :: MASS
! temperature
DOUBLE PRECISION :: TEMPERATURE
! exponent for the function defining the Tsallis-related entropy term
DOUBLE PRECISION :: MB
!
INTEGER,POINTER :: RANK_P
DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I
CONTAINS
SUBROUTINE SETUP_DATA
USE case_parameters ; USE setup_tools
IMPLICIT NONE
CHARACTER(30) :: NAME
INTEGER :: INFO,N
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN
CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- **** ---'
READ(100,*) NAME
READ(100,*) MASS
WRITE(*,'(a,f5.3)')' * Mass = ',MASS
READ(100,*) TEMPERATURE
WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE
READ(100,*) MB
WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB
WRITE(*,'(a)')' --- **** ---'
ELSE
CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- Molecular system ---'
READ(100,'(3/,a)')NAME
WRITE(*,'(a,a)')' ** NAME: ',NAME
READ(100,'(i2)') NBN
DO N=1,NBN
WRITE(*,'(a,i2)')' * Nucleus #',N
READ(100,*) Z(N),CENTER(:,N)
WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')'
WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N)
END DO
CALL INTERNUCLEAR_REPULSION_ENERGY
WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY
READ(100,'(i3)') NBE
WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE
IF (RELATIVISTIC) THEN
IF (MODEL==2) THEN
READ(100,'(3(i3))')NBECS,NBEOS,NBOOS
WRITE(*,'(a,i3)')' - number of closed shell electrons = ',NBECS
WRITE(*,'(a,i3)')' - number of open shell electrons = ',NBEOS
WRITE(*,'(a,i3)')' - number of open shell orbitals = ',NBOOS
IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons'
IF (NBOOS<=NBEOS) STOP' Problem with the number of open shell orbitals!'
END IF
ELSE
IF (MODEL==1) THEN
IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!'
ELSE IF (MODEL==2) THEN
READ(100,'(2(i3))')NBEA,NBEB
WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA
WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB
IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!'
! ELSE IF (MODEL==3) THEN
END IF
END IF
WRITE(*,'(a)')' --------- **** ---------'
END IF
CLOSE(100)
END SUBROUTINE SETUP_DATA
FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL)
! Function returning the symbol of a chemical element given its atomic number Z.
INTEGER,INTENT(IN) :: Z
CHARACTER(2) :: SYMBOL
IF (Z>104) THEN
WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!'
STOP
END IF
! List of symbols from Hydrogen up to Rutherfordium.
SELECT CASE (Z)
CASE (1) ; SYMBOL='H'
CASE (2) ; SYMBOL='He'
CASE (3) ; SYMBOL='Li'
CASE (4) ; SYMBOL='Be'
CASE (5) ; SYMBOL='B'
CASE (6) ; SYMBOL='C'
CASE (7) ; SYMBOL='N'
CASE (8) ; SYMBOL='O'
CASE (9) ; SYMBOL='F'
CASE (10) ; SYMBOL='Ne'
CASE (11) ; SYMBOL='Na'
CASE (12) ; SYMBOL='Mg'
CASE (13) ; SYMBOL='Al'
CASE (14) ; SYMBOL='Si'
CASE (15) ; SYMBOL='P'
CASE (16) ; SYMBOL='S'
CASE (17) ; SYMBOL='Cl'
CASE (18) ; SYMBOL='Ar'
CASE (19) ; SYMBOL='K'
CASE (20) ; SYMBOL='Ca'
CASE (21) ; SYMBOL='Sc'
CASE (22) ; SYMBOL='Ti'
CASE (23) ; SYMBOL='V'
CASE (24) ; SYMBOL='Cr'
CASE (25) ; SYMBOL='Mn'
CASE (26) ; SYMBOL='Fe'
CASE (27) ; SYMBOL='Co'
CASE (28) ; SYMBOL='Ni'
CASE (29) ; SYMBOL='Cu'
CASE (30) ; SYMBOL='Zn'
CASE (31) ; SYMBOL='Ga'
CASE (32) ; SYMBOL='Ge'
CASE (33) ; SYMBOL='As'
CASE (34) ; SYMBOL='Se'
CASE (35) ; SYMBOL='Br'
CASE (36) ; SYMBOL='Kr'
CASE (37) ; SYMBOL='Rb'
CASE (38) ; SYMBOL='Sr'
CASE (39) ; SYMBOL='Y'
CASE (40) ; SYMBOL='Zr'
CASE (41) ; SYMBOL='Nb'
CASE (42) ; SYMBOL='Mo'
CASE (43) ; SYMBOL='Tc'
CASE (44) ; SYMBOL='Ru'
CASE (45) ; SYMBOL='Rh'
CASE (46) ; SYMBOL='Pd'
CASE (47) ; SYMBOL='Ag'
CASE (48) ; SYMBOL='Cd'
CASE (49) ; SYMBOL='In'
CASE (50) ; SYMBOL='Sn'
CASE (51) ; SYMBOL='Sb'
CASE (52) ; SYMBOL='Te'
CASE (53) ; SYMBOL='I'
CASE (54) ; SYMBOL='Xe'
CASE (55) ; SYMBOL='Cs'
CASE (56) ; SYMBOL='Ba'
CASE (57) ; SYMBOL='La'
! Lanthanide elements (lanthanoids)
CASE (58) ; SYMBOL='Ce'
CASE (59) ; SYMBOL='Pr'
CASE (60) ; SYMBOL='Nd'
CASE (61) ; SYMBOL='Pm'
CASE (62) ; SYMBOL='Sm'
CASE (63) ; SYMBOL='Eu'
CASE (64) ; SYMBOL='Gd'
CASE (65) ; SYMBOL='Tb'
CASE (66) ; SYMBOL='Dy'
CASE (67) ; SYMBOL='Ho'
CASE (68) ; SYMBOL='Er'
CASE (69) ; SYMBOL='Tm'
CASE (70) ; SYMBOL='Yb'
CASE (71) ; SYMBOL='Lu'
CASE (72) ; SYMBOL='Hf'
CASE (73) ; SYMBOL='Ta'
CASE (74) ; SYMBOL='W'
CASE (75) ; SYMBOL='Re'
CASE (76) ; SYMBOL='Os'
CASE (77) ; SYMBOL='Ir'
CASE (78) ; SYMBOL='Pt'
CASE (79) ; SYMBOL='Au'
CASE (80) ; SYMBOL='Hg'
CASE (81) ; SYMBOL='Tl'
CASE (82) ; SYMBOL='Pb'
CASE (83) ; SYMBOL='Bi'
CASE (84) ; SYMBOL='Po'
CASE (85) ; SYMBOL='As'
CASE (86) ; SYMBOL='Rn'
CASE (87) ; SYMBOL='Fr'
CASE (88) ; SYMBOL='Ra'
CASE (89) ; SYMBOL='Ac'
! Actinide elements (actinoids)
CASE (90) ; SYMBOL='Th'
CASE (91) ; SYMBOL='Pa'
CASE (92) ; SYMBOL='U'
CASE (93) ; SYMBOL='Np'
CASE (94) ; SYMBOL='Pu'
CASE (95) ; SYMBOL='Am'
CASE (96) ; SYMBOL='Cm'
CASE (97) ; SYMBOL='Bk'
CASE (98) ; SYMBOL='Cf'
CASE (99) ; SYMBOL='Es'
CASE (100); SYMBOL='Fm'
CASE (101); SYMBOL='Md'
CASE (102); SYMBOL='No'
CASE (103); SYMBOL='Lr'
CASE (104); SYMBOL='Rf'
END SELECT
END FUNCTION IDENTIFYZ
SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system.
INTEGER :: I,J
DOUBLE PRECISION,DIMENSION(3) :: DIFF
INTERNUCLEAR_ENERGY=0.D0
DO I=1,NBN
DO J=I+1,NBN
DIFF=CENTER(:,I)-CENTER(:,J)
INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF))
END DO
END DO
END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Various functions for the Hartree model with temperature
FUNCTION POSITIVE_PART(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
FUNC=0.D0
ELSE
FUNC=X
END IF
END FUNCTION POSITIVE_PART
FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC)
! beta test function for the entropy
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
FUNC=POSITIVE_PART(X)**MB/MB
END FUNCTION ENTROPY_FUNCTION
FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE
FUNC=X**(1.D0/(MB-1.D0))
END IF
END FUNCTION RECIP_DENTFUNC
FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE IF (X==0.D0) THEN
STOP'No derivative at origin'
ELSE
FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0)
END IF
END FUNCTION
FUNCTION FUNCFORMU(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
INTEGER :: I
DOUBLE PRECISION :: Y
FUNC=-MASS
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
IF (Y>=0.D0) THEN
FUNC=FUNC+RECIP_DENTFUNC(Y)
END IF
END DO
END FUNCTION FUNCFORMU
SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV
INTEGER :: I
DOUBLE PRECISION :: Y
FVAL=-MASS ; FDERIV=0.D0
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
FVAL=FVAL+RECIP_DENTFUNC(Y)
FDERIV=FDERIV+DRECIP_DENTFUNC(Y)
END DO
END SUBROUTINE RDENTFUNCD
END MODULE
MODULE basis_parameters
USE iso_c_binding
! flag for the choice of the basis set type (either existing in the library or even-tempered)
LOGICAL :: LIBRARY
! PARAMETERS FOR A GIVEN BASIS SET
CHARACTER(26) :: BASISFILE
INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4
! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme.
! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET
INTEGER :: NUMBER_OF_TERMS
DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO
! Various flags for the contraction of the primitives and the Kinetic Balance scheme
LOGICAL :: UNCONT
LOGICAL :: KINBAL,UKB
TYPE gaussianbasisfunction
! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function.
! nbrofexponents: the number of different gaussian primitives present in the contraction
! center: coordinates (x,y,z) of the center of the basis function
! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center)
! exponents: array containing the exponent of each of the gaussian primitives present in the contraction
! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction
! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives
! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance).
INTEGER(KIND=C_INT) :: nbrofexponents
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center
INTEGER :: center_id
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree
END TYPE gaussianbasisfunction
TYPE twospinor
! Definition of a Pauli 2-spinor type basis function using gaussian basis functions.
! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor
! contractions: array containing the contractions present in each of the components of the 2-spinor
! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes)
! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor
! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0
INTEGER,DIMENSION(2) :: nbrofcontractions
TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions
INTEGER,DIMENSION(2,MNOGBF) :: contidx
DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients
END TYPE twospinor
CONTAINS
SUBROUTINE SETUP_BASIS
USE case_parameters ; USE setup_tools
CHARACTER(LEN=4) :: CHAR
CHARACTER(LEN=26) :: BASISNAME
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## BASIS DEFINITION',INFO)
IF (INFO/=0) STOP
READ(100,'(3/,a)') BASISNAME
IF (BASISNAME(1:6)=='BASIS ') THEN
! The basis set is an existing one in the basis library
LIBRARY=.TRUE.
BASISFILE='basis/'//BASISNAME(7:)
READ(100,'(a4)') CHAR
IF (CHAR=='UNCO') THEN
UNCONT=.TRUE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)'
ELSE
UNCONT=.FALSE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)'
END IF
ELSE IF (BASISNAME(1:4)=='EVEN') THEN
! The basis set is an even-tempered one
LIBRARY=.FALSE.
IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)'
WRITE(*,'(a)')' Even-tempered basis set (preliminary support)'
READ(100,'(i4)') NUMBER_OF_TERMS
WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS
READ(100,*) FIRST_TERM
WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM
READ(100,*) COMMON_RATIO
WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO
ELSE
STOP' Unknown basis set type'
END IF
IF (RELATIVISTIC) THEN
READ(100,'(a2)') CHAR
IF (CHAR=='KI') THEN
KINBAL=.TRUE.
READ(100,'(a4)') CHAR
IF (CHAR=='REST') THEN
UKB=.FALSE.
WRITE(*,'(a)')' Restricted kinetic balance'
ELSE
UKB=.TRUE.
WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance'
END IF
ELSE
KINBAL=.FALSE.
WRITE(*,'(a)')' No kinetic balance'
END IF
END IF
CLOSE(100)
END SUBROUTINE SETUP_BASIS
FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE)
! Function that computes the value of a gaussian basis function at a given point of space.
USE iso_c_binding
TYPE(gaussianbasisfunction),INTENT(IN) :: GBF
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) &
& *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), &
& EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2)))
END FUNCTION GBF_POINTWISE_VALUE
SUBROUTINE PRINTGBF(PHI,NUNIT)
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NUNIT
INTEGER :: I
WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents
WRITE(NUNIT,*)' center:',PHI%center
WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree
DO I=1,PHI%nbrofexponents
WRITE(NUNIT,*)' gaussian primitive #',I
WRITE(NUNIT,*)' exponent:',PHI%exponents(I)
WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I)
END DO
END SUBROUTINE PRINTGBF
FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE)
! Function that computes the value of a Pauli 2-spinor basis function at a given point of space.
USE iso_c_binding
TYPE(twospinor),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE COMPLEX,DIMENSION(2) :: VALUE
INTEGER :: I,J
DO I=1,2
VALUE(I)=(0.D0,0.D0)
DO J=1,PHI%nbrofcontractions(I)
VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT)
END DO
END DO
END FUNCTION TWOSPINOR_POINTWISE_VALUE
SUBROUTINE PRINT2SPINOR(PHI,NUNIT)
TYPE(twospinor),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NUNIT
INTEGER :: I,J,K
DO K=1,2
WRITE(NUNIT,*)'component #',K
IF (PHI%nbrofcontractions(K)==0) THEN
WRITE(NUNIT,*)' no contraction'
ELSE
WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K)
DO I=1,PHI%nbrofcontractions(K)
WRITE(NUNIT,*)' contraction #',I
WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I)
WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents
WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree
WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center
DO J=1,PHI%contractions(K,I)%nbrofexponents
WRITE(NUNIT,*)' gaussian primitive #',J
WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J)
WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J)
END DO
END DO
END IF
END DO
END SUBROUTINE PRINT2SPINOR
END MODULE
MODULE scf_parameters
! number of different SCF algorithms to be used
INTEGER :: NBALG
! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only))
INTEGER,DIMENSION(5) :: ALG
! threshold for numerical convergence
DOUBLE PRECISION :: TRSHLD
! maximum number of iterations allowed
INTEGER :: MAXITR
! direct computation of the bielectronic integrals or not
LOGICAL :: DIRECT
! "semi-direct" computation of the bielectronic integrals (relativistic case only)
! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards.
LOGICAL :: SEMIDIRECT
! storage of the computed bielectronic integrals (and/or their list) on disk or in memory
LOGICAL :: USEDISK
! use of the SS-bielectronic integrals
LOGICAL :: SSINTEGRALS
+! resume EIG and EIGVEC from last computation
+ LOGICAL :: RESUME
! use of the SL-bielectronic integrals. Should not be set by the user directly
LOGICAL :: SLINTEGRALS = .TRUE.
CONTAINS
SUBROUTINE SETUP_SCF
!$ USE omp_lib
USE case_parameters ; USE setup_tools
CHARACTER :: METHOD
CHARACTER(4) :: CHAR
INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS
DOUBLE PRECISION :: SHIFT
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## SCF PARAMETERS',INFO)
IF (INFO/=0) STOP
READ(100,'(7/,i1)') NBALG
DO I=1,NBALG
READ(100,'(i1)') ALG(I)
IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN
STOP'The Optimal Damping Algorithm is intended for the non-relativistic case only.'
ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN
STOP'ES''s algorithm is intended for the relativistic case only.'
END IF
END DO
READ(100,*) TRSHLD
WRITE(*,*)'Threshold =',TRSHLD
READ(100,'(i5)') MAXITR
WRITE(*,*)'Maximum number of iterations =',MAXITR
READ(100,'(a3)') CHAR
IF (RELATIVISTIC) THEN
IF (CHAR=='DIR') THEN
DIRECT=.TRUE.
WRITE(*,'(a)')' Direct computation of the bielectronic integrals'
! check if the list of the bielectronic integrals is stored on disk or in memory
READ(100,'(a4)') CHAR
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
ELSE
USEDISK=.FALSE.
END IF
ELSE IF (CHAR=='NOT') THEN
DIRECT=.FALSE. ; SEMIDIRECT=.FALSE.
READ(100,'(a4)') CHAR
! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory)
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
WRITE(*,'(a)')' Computed bielectronic integrals stored on disk'
ELSE
USEDISK=.FALSE.
WRITE(*,'(a)')' Computed bielectronic integrals stored in memory'
END IF
ELSE IF (CHAR=='SEM') THEN
DIRECT=.FALSE. ; SEMIDIRECT=.TRUE.
WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals'
! check if the list of the bielectronic integrals is stored on disk or in memory
READ(100,'(a4)') CHAR
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
ELSE
USEDISK=.FALSE.
END IF
ELSE
WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.'
STOP
END IF
READ(100,'(a4)') CHAR
IF (CHAR=='NOSS') THEN
SSINTEGRALS=.FALSE.
WRITE(*,'(a)')' (SS-integrals are not used in the computation)'
ELSE
SSINTEGRALS=.TRUE.
END IF
ELSE
IF (CHAR=='DIR') THEN
DIRECT=.TRUE.
WRITE(*,'(a)')' Direct computation of the bielectronic integrals'
! the list of the bielectronic integrals is stored in memory
ELSE IF (CHAR=='NOT') THEN
DIRECT=.FALSE.
! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory)
READ(100,'(a4)') CHAR
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
WRITE(*,'(a)')' Computed bielectronic integrals stored on disk'
ELSE
USEDISK=.FALSE.
WRITE(*,'(a)')' Computed bielectronic integrals stored in memory'
END IF
ELSE
WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.'
STOP
END IF
END IF
! additional verifications on the parameters of the algorithms
DO I=1,NBALG
IF (ALG(I)==2) THEN
REWIND(100)
CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO)
IF (INFO/=0) GO TO 1
READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT
ELSE IF (ALG(I)==3) THEN
REWIND(100)
CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO)
IF (INFO/=0) GO TO 2
READ(100,'(/,i2)',ERR=2,END=2)MXSET
IF (MXSET<2) GO TO 3
ELSE IF (ALG(I)==5) THEN
REWIND(100)
CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO)
IF (INFO/=0) GO TO 4
READ(100,'(/,a)',ERR=4,END=4)METHOD
IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4
END IF
END DO
+
+ RESUME = .FALSE.
+ CALL LOOKFOR(100,'RESUME',INFO)
+ IF(INFO == 0) THEN
+ READ(100,'(a)')CHAR
+ IF(CHAR == 'YES') THEN
+ RESUME = .TRUE.
+ END IF
+ END IF
!$ ! determination of the number of threads to be used by OpenMP
!$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO)
!$ IF (INFO==0) THEN
!$ READ(100,'(/,i3)')NUMBER_OF_THREADS
!$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS)
!$ END IF
!$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.'
CLOSE(100)
RETURN
! MESSAGES
1 STOP'No shift parameter given for the level-shifting algorithm.'
2 STOP'No simplex dimension given for the DIIS algorithm.'
3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.'
4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.'
END SUBROUTINE SETUP_SCF
END MODULE
diff --git a/src/tools.f90 b/src/tools.f90
index d20e968..930e8ea 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -1,1018 +1,1045 @@
MODULE constants
DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0
END MODULE
MODULE random
CONTAINS
! call this once
SUBROUTINE INIT_RANDOM()
! initialises random generator
! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED
INTEGER :: i, n, clock
INTEGER, DIMENSION(:), ALLOCATABLE :: seed
CALL RANDOM_SEED(size = n)
ALLOCATE(seed(n))
CALL SYSTEM_CLOCK(COUNT=clock)
seed = clock + 37 * (/ (i - 1, i = 1, n) /)
CALL RANDOM_SEED(PUT = seed)
DEALLOCATE(seed)
END SUBROUTINE INIT_RANDOM
! returns an array of random numbers of size N in (0, 1)
FUNCTION GET_RANDOM(N) RESULT(r)
REAL, DIMENSION(N) :: r
INTEGER :: N
CALL RANDOM_NUMBER(r)
END FUNCTION get_random
END MODULE random
MODULE matrix_tools
INTERFACE PACK
MODULE PROCEDURE PACK_symmetric,PACK_hermitian
END INTERFACE
INTERFACE UNPACK
MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian
END INTERFACE
INTERFACE ABA
MODULE PROCEDURE ABA_symmetric,ABA_hermitian
END INTERFACE
INTERFACE ABCBA
MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian
END INTERFACE
INTERFACE ABC_CBA
MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian
END INTERFACE
INTERFACE FINNERPRODUCT
MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex
END INTERFACE
INTERFACE NORM
MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian
END INTERFACE
INTERFACE INVERSE
MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian
END INTERFACE
INTERFACE SQUARE_ROOT
MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian
END INTERFACE
INTERFACE EXPONENTIAL
MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex
END INTERFACE EXPONENTIAL
INTERFACE TRACE
MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian
END INTERFACE
INTERFACE TRACEOFPRODUCT
MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian
END INTERFACE
INTERFACE EIGENSOLVER
MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized
END INTERFACE
INTERFACE COMMUTATOR
MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian
END INTERFACE
INTERFACE PRINTMATRIX
MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian,PRINTMATRIX_complex,PRINTMATRIX_real
END INTERFACE
+INTERFACE READMATRIX
+ MODULE PROCEDURE READMATRIX_complex,READMATRIX_real
+END INTERFACE READMATRIX
+
INTERFACE BUILD_BLOCK_DIAGONAL
MODULE PROCEDURE BUILD_BLOCK_DIAGONAL_symmetric
END INTERFACE BUILD_BLOCK_DIAGONAL
CONTAINS
! handling of symmetric and hermitian matrices stored in packed form.
FUNCTION PACK_symmetric(A,N) RESULT (PA)
! Function that stores the upper triangular part of a symmetric matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=(A(I,J)+A(J,I))/2.D0
END DO
END DO
END FUNCTION PACK_symmetric
FUNCTION PACK_hermitian(A,N) RESULT (PA)
! Function that stores the upper triangular part of a hermitian matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=A(I,J)
PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0
END DO
END DO
END FUNCTION PACK_hermitian
FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
PD=ABA(PA,ABA(PB,PC,N),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_real
FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_complex
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
SUBROUTINE NORM_check_norm(CHAR)
CHARACTER(1),INTENT(IN) :: CHAR
IF((CHAR /= 'F') .AND. &
&(CHAR /= 'I') .AND. &
&(CHAR /= '1') .AND. &
&(CHAR /= 'M')) THEN
WRITE(*,*) 'Invalid norm'
STOP
END IF
END SUBROUTINE NORM_check_norm
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
CALL NORM_check_norm(CHAR)
NORM = DLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
CALL NORM_check_norm(CHAR)
NORM = ZLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
CALL NORM_check_norm(CHAR)
NORM = DLANSP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
CALL NORM_check_norm(CHAR)
NORM = ZLANHP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
+SUBROUTINE READMATRIX_real(MAT,N,LOGUNIT)
+ INTEGER,INTENT(IN) :: N,LOGUNIT
+ INTEGER :: I
+ DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: MAT
+ DOUBLE PRECISION,DIMENSION(N) :: LINE
+
+ DO I=1,N
+ READ(LOGUNIT,*) LINE
+ MAT(I,:) = LINE
+ END DO
+END SUBROUTINE READMATRIX_REAL
+
+SUBROUTINE READMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
+ INTEGER :: N,LOGUNIT_REAL,LOGUNIT_IMAG
+ DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: MAT
+ DOUBLE PRECISION,DIMENSION(N,N) :: R,I
+
+ CALL READMATRIX_real(R,N,LOGUNIT_REAL)
+ CALL READMATRIX_real(I,N,LOGUNIT_IMAG)
+
+ MAT = DCMPLX(R,I)
+END SUBROUTINE READMATRIX_complex
+
SUBROUTINE PRINTMATRIX_real(MAT,N,LOGUNIT)
INTEGER,INTENT(IN) :: N,LOGUNIT
INTEGER :: I
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: MAT
DO I=1,N
WRITE(LOGUNIT,*) MAT(I,:)
END DO
END SUBROUTINE PRINTMATRIX_real
SUBROUTINE PRINTMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG
INTEGER :: I
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: MAT
DO I=1,N
IF(LOGUNIT_REAL == LOGUNIT_IMAG) THEN
WRITE(LOGUNIT_REAL,*) MAT(I,:)
ELSE
WRITE(LOGUNIT_REAL,*) REAL(MAT(I,:))
WRITE(LOGUNIT_IMAG,*) AIMAG(MAT(I,:))
END IF
END DO
END SUBROUTINE PRINTMATRIX_complex
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
CALL PRINTMATRIX_real(UNPACK(PMAT,N),N,LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
CALL PRINTMATRIX_complex(UNPACK(PMAT,N),N,LOGUNIT_REAL,LOGUNIT_IMAG)
END SUBROUTINE PRINTMATRIX_hermitian
SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric(PB,PA,N)
! Builds B as [A 0;0 A], A is of size N
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION, DIMENSION(N*2*(N*2+1)/2),INTENT(OUT) :: PB
DOUBLE PRECISION, DIMENSION(2*N,2*N) :: B
B = 0
B(1:N,1:N) = UNPACK(PA,N)
B(N+1:2*N,N+1:2*N) = B(1:N,1:N)
PB = PACK(B,2*N)
END SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric
END MODULE matrix_tools
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
IMPLICIT NONE
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
59ca37bfbd28500dfeda67b21f69489711e01ed8
|
Complex General Hartree-Fock
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index b5d5da7..031151c 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,573 +1,581 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! POUR L'INSTANT
RESUME=.FALSE.
+ ! complex GHF
+ IF(MODEL == 3) THEN
+ SSINTEGRALS = .FALSE.
+ SLINTEGRALS = .FALSE.
+ END IF
+
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
+ CASE (3)
+ CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! Computation of the discretization basis
IF(MODEL == 4) THEN
CALL FORMBASIS_GHF(PHI,NBAS)
ELSE
CALL FORMBASIS(PHI,NBAS)
END IF
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOM_GHF(POM,PHI,NBAST)
ELSE
CALL BUILDOM(POM,PHI,NBAST)
END IF
PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
IF(MODEL == 4) THEN
CALL BUILDOEFM_GHF(POEFM,PHI,NBAST)
ELSE
CALL BUILDOEFM(POEFM,PHI,NBAST)
END IF
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
CASE (4)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
diff --git a/src/matrices.f90 b/src/matrices.f90
index 24d0064..a13d01a 100644
--- a/src/matrices.f90
+++ b/src/matrices.f90
@@ -1,719 +1,740 @@
SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON)
! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PDM=(0.D0,0.D0)
DO I=LOON,HOON
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
END DO
END SUBROUTINE FORMDM_relativistic
SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON)
! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PDM=0.D0
DO I=LOON,HOON
CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
END DO
END SUBROUTINE FORMDM_nonrelativistic
SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON)
! Assembly of the matrix of the projector on the "positive" space (i.e., the electronic states) associated to a Dirac-Fock Hamiltonian (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PPROJM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PPROJM=(0.D0,0.D0)
DO I=0,NBAST-LOON
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM)
END DO
END SUBROUTINE FORMPROJ
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POM=(0.D0,0.D0)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOM_relativistic
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J
DO J=1,NBAST
DO I=1,J
POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J))
END DO
END DO
END SUBROUTINE BUILDOM_nonrelativistic
SUBROUTINE BUILDOM_GHF(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! matrix is block-diagonal
CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOM_GHF
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
DO J=1,NBAST
DO I=1,J
PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0
END DO
END DO
END SUBROUTINE BUILDKPFM_nonrelativistic
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M,N
DOUBLE COMPLEX :: TMP,VALUE
POEFM=(0.D0,0.D0)
+ ! potential energy for L spinors
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
DO N=1,NBN
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
+ IF(MODEL == 3) THEN
+ ! schrodinger kinetic energy
+ DO J=1,NBAS(1)
+ DO I=1,J
+ VALUE=(0.D0,0.D0)
+ DO K=1,2
+ DO L=1,PHI(I)%nbrofcontractions(K)
+ DO M=1,PHI(J)%nbrofcontractions(K)
+ VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L)*&
+ &KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2
+ END DO
+ END DO
+ END DO
+ POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2) + VALUE
+ END DO
+ END DO
+ ELSE
+ ! kinetic energy alpha.p
DO J=NBAS(1)+1,SUM(NBAS)
DO I=1,NBAS(1)
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), &
& DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), &
& DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3))
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
+ !potential energy for S spinors
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
DO N=1,NBN
TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
+ END IF
END SUBROUTINE BUILDOEFM_relativistic
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
POEFM=0.D0
DO J=1,NBAST
DO I=1,J
VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0
DO N=1,NBN
VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N))
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOEFM_nonrelativistic
SUBROUTINE BUILDOEFM_GHF(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
! the one-electron Fock operator does not couple spins, matrix is block-diagonal
CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2)
CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2)
END SUBROUTINE BUILDOEFM_GHF
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM
TEFM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
! IF ((I==J).AND.(I==K).AND.(I==L)) THEN
! NO CONTRIBUTION
! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K))
! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN
! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I))
! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K))
! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I))
ELSE
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_relativistic
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
TEFM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I)
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J)
TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J))
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I))
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I))
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I)
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_RHF
SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
PTEFM=PCM-PEM
END SUBROUTINE BUILDTEFM_GHF
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM
CM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(I,J)
ELSE
CM(I,J)=CM(I,J)+INTGRL*DM(K,L)
CM(K,L)=CM(K,L)+INTGRL*DM(I,J)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_relativistic
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
CM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
CM(I,I)=CM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(J,J)
CM(J,I)=CM(J,I)+INTGRL*DM(J,J)
CM(J,J)=CM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
CM(L,I)=CM(L,I)+INTGRL*DM(I,I)
CM(I,L)=CM(I,L)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
CM(I,I)=CM(I,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*DM(I,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(I,J)+DM(J,I))
CM(J,I)=CM(J,I)+INTGRL*(DM(J,I)+DM(I,J))
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(I,L)+DM(L,I))
CM(J,I)=CM(J,I)+INTGRL*(DM(I,L)+DM(L,I))
CM(I,L)=CM(I,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,I)=CM(L,I)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,L)+DM(L,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,L)+DM(L,J))
CM(J,L)=CM(J,L)+INTGRL*(DM(J,I)+DM(I,J))
CM(L,J)=CM(L,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,K)+DM(K,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,K)+DM(K,J))
CM(J,K)=CM(J,K)+INTGRL*(DM(J,I)+DM(I,J))
CM(K,J)=CM(K,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(K,K)
CM(J,I)=CM(J,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
CM(K,L)=CM(K,L)+INTGRL*DM(I,I)
CM(L,K)=CM(L,K)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(K,L)+DM(L,K))
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(K,L)+DM(L,K))
CM(J,I)=CM(J,I)+INTGRL*(DM(K,L)+DM(L,K))
CM(K,L)=CM(K,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,K)=CM(L,K)+INTGRL*(DM(I,J)+DM(J,I))
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_nonrelativistic
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM
EM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
ELSE
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_relativistic
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
EM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,J)
EM(J,I)=EM(J,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
EM(L,I)=EM(L,I)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(I,I)
EM(I,I)=EM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
EM(I,K)=EM(I,K)+INTGRL*DM(I,K)
EM(K,I)=EM(K,I)+INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*DM(I,I)
diff --git a/src/setup.f90 b/src/setup.f90
index f925901..52adb32 100644
--- a/src/setup.f90
+++ b/src/setup.f90
@@ -1,595 +1,598 @@
MODULE case_parameters
! relativistic or non-relativistic case flag
LOGICAL :: RELATIVISTIC
! speed of light. Might be defined by the user via a scale factor
DOUBLE PRECISION :: C
! approximation index (1 is Hartree, 2 is Hartree-Fock)
INTEGER :: APPROXIMATION
! model/formalism index (see below)
INTEGER :: MODEL
CONTAINS
SUBROUTINE SETUP_CASE
USE setup_tools
! speed of light in the vacuum in atomic units (for the relativistic case)
! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006.
DOUBLE PRECISION,PARAMETER :: SPEED_OF_LIGHT=137.035999967994D0
DOUBLE PRECISION :: SCALING_FACTOR=1.D0
CHARACTER(2) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## CASE',INFO)
IF (INFO/=0) STOP
READ(100,'(a2)') CHAR
IF (CHAR=='RE') THEN
RELATIVISTIC=.TRUE.
WRITE(*,'(a)')' Relativistic case'
CALL LOOKFOR(100,'## SPEED OF LIGHT SCALE FACTOR',INFO)
IF (INFO==0) THEN
READ(100,*) SCALING_FACTOR
END IF
C = SCALING_FACTOR*SPEED_OF_LIGHT
WRITE(*,'(a,f16.8)')' Speed of light c = ',C
ELSE IF (CHAR=='NO') THEN
RELATIVISTIC=.FALSE.
WRITE(*,'(a)')' Non-relativistic case'
ELSE
WRITE(*,*)'Subroutine SETUP_CASE: error!'
STOP
END IF
CLOSE(100)
END SUBROUTINE SETUP_CASE
SUBROUTINE SETUP_APPROXIMATION
USE setup_tools
CHARACTER(12) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## APPROXIMATION',INFO)
IF (INFO/=0) STOP
READ(100,'(a12)') CHAR
IF (LEN_TRIM(CHAR)==7) THEN
APPROXIMATION=1
WRITE(*,'(a)')' Hartree approximation (Hartree product wave function)'
IF (RELATIVISTIC) STOP' This option is incompatible with the previous one (for the time being)'
ELSE IF (LEN_TRIM(CHAR)>7) THEN
APPROXIMATION=2
WRITE(*,'(a)')' Hartree-Fock approximation (Slater determinant wave function)'
ELSE
WRITE(*,*)'Subroutine SETUP_APPROXIMATION: error!'
STOP
END IF
CLOSE(100)
END SUBROUTINE SETUP_APPROXIMATION
SUBROUTINE SETUP_FORMALISM
USE setup_tools
CHARACTER(3) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## MODEL',INFO)
IF (INFO/=0) STOP
READ(100,'(a3)') CHAR
IF (RELATIVISTIC) THEN
IF (APPROXIMATION==2) THEN
IF (CHAR=='CSD') THEN
MODEL=1
WRITE(*,'(a)')' Closed-shell formalism'
ELSE IF (CHAR=='OSD') THEN
MODEL=2
WRITE(*,'(a)')' Average-of-configuration open-shell formalism'
+ ELSE IF (CHAR=='CGH') THEN
+ MODEL=3
+ WRITE(*,'(a)')' Complex general hartree-fock'
ELSE
GO TO 1
END IF
END IF
ELSE
IF (APPROXIMATION==1) THEN
IF (CHAR=='BOS') THEN
! MODEL=1
WRITE(*,'(a)')' Boson star model (preliminary)'
ELSE
GO TO 1
END IF
ELSE IF (APPROXIMATION==2) THEN
IF (CHAR=='RHF') THEN
! Restricted (closed-shell) Hartree-Fock (RHF) formalism (doubly occupied orbitals)
MODEL=1
WRITE(*,'(a)')' Restricted (closed-shell) Hartree-Fock (RHF) formalism'
ELSE IF (CHAR=='UHF') THEN
! Unrestricted (open-shell) Hartree-Fock (UHF) formalism (different orbitals for different spins (DODS method))
! Reference: J. A. Pople and R. K. Nesbet, Self-consistent orbitals for radicals, J. Chem. Phys., 22(3), 571-572, 1954.
MODEL=2
WRITE(*,'(a)')' Unrestricted (open-shell) Hartree-Fock (UHF) formalism'
ELSE IF (CHAR=='ROH') THEN
! Restricted Open-shell Hartree-Fock (ROHF) formalism
! Reference: C. C. J. Roothaan, Self-consistent field theory for open shells of electronic systems, Rev. Modern Phys., 32(2), 179-185, 1960.
MODEL=3
WRITE(*,'(a)')' Restricted Open-shell Hartree-Fock (ROHF) formalism'
WRITE(*,*)'Option not implemented yet!'
STOP
ELSE IF (CHAR=='GHF') THEN
! General Hartree-Fock (ROHF) formalism
MODEL=4
WRITE(*,'(a)')' General Hartree-Fock formalism'
ELSE
GO TO 1
END IF
END IF
END IF
CLOSE(100)
RETURN
1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!'
STOP
END SUBROUTINE SETUP_FORMALISM
END MODULE
MODULE data_parameters
USE iso_c_binding
! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS **
! number of nuclei in the molecular system (at most 10)
INTEGER :: NBN
! atomic numbers of the nuclei
INTEGER,DIMENSION(10) :: Z
! positions of the nucleii
DOUBLE PRECISION,DIMENSION(3,10) :: CENTER
! total number of electrons in the molecular system
INTEGER :: NBE
! total number of electrons in the closed shells (open-shell DHF formalism)
INTEGER :: NBECS
! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism)
INTEGER :: NBEOS,NBOOS
! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms)
INTEGER :: NBEA,NBEB
! internuclear repulsion energy
DOUBLE PRECISION :: INTERNUCLEAR_ENERGY
! ** DATA FOR BOSON STAR MODEL **
DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0
! mass
DOUBLE PRECISION :: MASS
! temperature
DOUBLE PRECISION :: TEMPERATURE
! exponent for the function defining the Tsallis-related entropy term
DOUBLE PRECISION :: MB
!
INTEGER,POINTER :: RANK_P
DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I
CONTAINS
SUBROUTINE SETUP_DATA
USE case_parameters ; USE setup_tools
IMPLICIT NONE
CHARACTER(30) :: NAME
INTEGER :: INFO,N
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN
CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- **** ---'
READ(100,*) NAME
READ(100,*) MASS
WRITE(*,'(a,f5.3)')' * Mass = ',MASS
READ(100,*) TEMPERATURE
WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE
READ(100,*) MB
WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB
WRITE(*,'(a)')' --- **** ---'
ELSE
CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- Molecular system ---'
READ(100,'(3/,a)')NAME
WRITE(*,'(a,a)')' ** NAME: ',NAME
READ(100,'(i2)') NBN
DO N=1,NBN
WRITE(*,'(a,i2)')' * Nucleus #',N
READ(100,*) Z(N),CENTER(:,N)
WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')'
WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N)
END DO
CALL INTERNUCLEAR_REPULSION_ENERGY
WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY
READ(100,'(i3)') NBE
WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE
IF (RELATIVISTIC) THEN
IF (MODEL==2) THEN
READ(100,'(3(i3))')NBECS,NBEOS,NBOOS
WRITE(*,'(a,i3)')' - number of closed shell electrons = ',NBECS
WRITE(*,'(a,i3)')' - number of open shell electrons = ',NBEOS
WRITE(*,'(a,i3)')' - number of open shell orbitals = ',NBOOS
IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons'
IF (NBOOS<=NBEOS) STOP' Problem with the number of open shell orbitals!'
END IF
ELSE
IF (MODEL==1) THEN
IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!'
ELSE IF (MODEL==2) THEN
READ(100,'(2(i3))')NBEA,NBEB
WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA
WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB
IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!'
! ELSE IF (MODEL==3) THEN
END IF
END IF
WRITE(*,'(a)')' --------- **** ---------'
END IF
CLOSE(100)
END SUBROUTINE SETUP_DATA
FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL)
! Function returning the symbol of a chemical element given its atomic number Z.
INTEGER,INTENT(IN) :: Z
CHARACTER(2) :: SYMBOL
IF (Z>104) THEN
WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!'
STOP
END IF
! List of symbols from Hydrogen up to Rutherfordium.
SELECT CASE (Z)
CASE (1) ; SYMBOL='H'
CASE (2) ; SYMBOL='He'
CASE (3) ; SYMBOL='Li'
CASE (4) ; SYMBOL='Be'
CASE (5) ; SYMBOL='B'
CASE (6) ; SYMBOL='C'
CASE (7) ; SYMBOL='N'
CASE (8) ; SYMBOL='O'
CASE (9) ; SYMBOL='F'
CASE (10) ; SYMBOL='Ne'
CASE (11) ; SYMBOL='Na'
CASE (12) ; SYMBOL='Mg'
CASE (13) ; SYMBOL='Al'
CASE (14) ; SYMBOL='Si'
CASE (15) ; SYMBOL='P'
CASE (16) ; SYMBOL='S'
CASE (17) ; SYMBOL='Cl'
CASE (18) ; SYMBOL='Ar'
CASE (19) ; SYMBOL='K'
CASE (20) ; SYMBOL='Ca'
CASE (21) ; SYMBOL='Sc'
CASE (22) ; SYMBOL='Ti'
CASE (23) ; SYMBOL='V'
CASE (24) ; SYMBOL='Cr'
CASE (25) ; SYMBOL='Mn'
CASE (26) ; SYMBOL='Fe'
CASE (27) ; SYMBOL='Co'
CASE (28) ; SYMBOL='Ni'
CASE (29) ; SYMBOL='Cu'
CASE (30) ; SYMBOL='Zn'
CASE (31) ; SYMBOL='Ga'
CASE (32) ; SYMBOL='Ge'
CASE (33) ; SYMBOL='As'
CASE (34) ; SYMBOL='Se'
CASE (35) ; SYMBOL='Br'
CASE (36) ; SYMBOL='Kr'
CASE (37) ; SYMBOL='Rb'
CASE (38) ; SYMBOL='Sr'
CASE (39) ; SYMBOL='Y'
CASE (40) ; SYMBOL='Zr'
CASE (41) ; SYMBOL='Nb'
CASE (42) ; SYMBOL='Mo'
CASE (43) ; SYMBOL='Tc'
CASE (44) ; SYMBOL='Ru'
CASE (45) ; SYMBOL='Rh'
CASE (46) ; SYMBOL='Pd'
CASE (47) ; SYMBOL='Ag'
CASE (48) ; SYMBOL='Cd'
CASE (49) ; SYMBOL='In'
CASE (50) ; SYMBOL='Sn'
CASE (51) ; SYMBOL='Sb'
CASE (52) ; SYMBOL='Te'
CASE (53) ; SYMBOL='I'
CASE (54) ; SYMBOL='Xe'
CASE (55) ; SYMBOL='Cs'
CASE (56) ; SYMBOL='Ba'
CASE (57) ; SYMBOL='La'
! Lanthanide elements (lanthanoids)
CASE (58) ; SYMBOL='Ce'
CASE (59) ; SYMBOL='Pr'
CASE (60) ; SYMBOL='Nd'
CASE (61) ; SYMBOL='Pm'
CASE (62) ; SYMBOL='Sm'
CASE (63) ; SYMBOL='Eu'
CASE (64) ; SYMBOL='Gd'
CASE (65) ; SYMBOL='Tb'
CASE (66) ; SYMBOL='Dy'
CASE (67) ; SYMBOL='Ho'
CASE (68) ; SYMBOL='Er'
CASE (69) ; SYMBOL='Tm'
CASE (70) ; SYMBOL='Yb'
CASE (71) ; SYMBOL='Lu'
CASE (72) ; SYMBOL='Hf'
CASE (73) ; SYMBOL='Ta'
CASE (74) ; SYMBOL='W'
CASE (75) ; SYMBOL='Re'
CASE (76) ; SYMBOL='Os'
CASE (77) ; SYMBOL='Ir'
CASE (78) ; SYMBOL='Pt'
CASE (79) ; SYMBOL='Au'
CASE (80) ; SYMBOL='Hg'
CASE (81) ; SYMBOL='Tl'
CASE (82) ; SYMBOL='Pb'
CASE (83) ; SYMBOL='Bi'
CASE (84) ; SYMBOL='Po'
CASE (85) ; SYMBOL='As'
CASE (86) ; SYMBOL='Rn'
CASE (87) ; SYMBOL='Fr'
CASE (88) ; SYMBOL='Ra'
CASE (89) ; SYMBOL='Ac'
! Actinide elements (actinoids)
CASE (90) ; SYMBOL='Th'
CASE (91) ; SYMBOL='Pa'
CASE (92) ; SYMBOL='U'
CASE (93) ; SYMBOL='Np'
CASE (94) ; SYMBOL='Pu'
CASE (95) ; SYMBOL='Am'
CASE (96) ; SYMBOL='Cm'
CASE (97) ; SYMBOL='Bk'
CASE (98) ; SYMBOL='Cf'
CASE (99) ; SYMBOL='Es'
CASE (100); SYMBOL='Fm'
CASE (101); SYMBOL='Md'
CASE (102); SYMBOL='No'
CASE (103); SYMBOL='Lr'
CASE (104); SYMBOL='Rf'
END SELECT
END FUNCTION IDENTIFYZ
SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system.
INTEGER :: I,J
DOUBLE PRECISION,DIMENSION(3) :: DIFF
INTERNUCLEAR_ENERGY=0.D0
DO I=1,NBN
DO J=I+1,NBN
DIFF=CENTER(:,I)-CENTER(:,J)
INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF))
END DO
END DO
END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Various functions for the Hartree model with temperature
FUNCTION POSITIVE_PART(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
FUNC=0.D0
ELSE
FUNC=X
END IF
END FUNCTION POSITIVE_PART
FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC)
! beta test function for the entropy
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
FUNC=POSITIVE_PART(X)**MB/MB
END FUNCTION ENTROPY_FUNCTION
FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE
FUNC=X**(1.D0/(MB-1.D0))
END IF
END FUNCTION RECIP_DENTFUNC
FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE IF (X==0.D0) THEN
STOP'No derivative at origin'
ELSE
FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0)
END IF
END FUNCTION
FUNCTION FUNCFORMU(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
INTEGER :: I
DOUBLE PRECISION :: Y
FUNC=-MASS
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
IF (Y>=0.D0) THEN
FUNC=FUNC+RECIP_DENTFUNC(Y)
END IF
END DO
END FUNCTION FUNCFORMU
SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV
INTEGER :: I
DOUBLE PRECISION :: Y
FVAL=-MASS ; FDERIV=0.D0
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
FVAL=FVAL+RECIP_DENTFUNC(Y)
FDERIV=FDERIV+DRECIP_DENTFUNC(Y)
END DO
END SUBROUTINE RDENTFUNCD
END MODULE
MODULE basis_parameters
USE iso_c_binding
! flag for the choice of the basis set type (either existing in the library or even-tempered)
LOGICAL :: LIBRARY
! PARAMETERS FOR A GIVEN BASIS SET
CHARACTER(26) :: BASISFILE
INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4
! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme.
! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET
INTEGER :: NUMBER_OF_TERMS
DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO
! Various flags for the contraction of the primitives and the Kinetic Balance scheme
LOGICAL :: UNCONT
LOGICAL :: KINBAL,UKB
TYPE gaussianbasisfunction
! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function.
! nbrofexponents: the number of different gaussian primitives present in the contraction
! center: coordinates (x,y,z) of the center of the basis function
! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center)
! exponents: array containing the exponent of each of the gaussian primitives present in the contraction
! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction
! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives
! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance).
INTEGER(KIND=C_INT) :: nbrofexponents
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center
INTEGER :: center_id
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree
END TYPE gaussianbasisfunction
TYPE twospinor
! Definition of a Pauli 2-spinor type basis function using gaussian basis functions.
! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor
! contractions: array containing the contractions present in each of the components of the 2-spinor
! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes)
! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor
! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0
INTEGER,DIMENSION(2) :: nbrofcontractions
TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions
INTEGER,DIMENSION(2,MNOGBF) :: contidx
DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients
END TYPE twospinor
CONTAINS
SUBROUTINE SETUP_BASIS
USE case_parameters ; USE setup_tools
CHARACTER(LEN=4) :: CHAR
CHARACTER(LEN=26) :: BASISNAME
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## BASIS DEFINITION',INFO)
IF (INFO/=0) STOP
READ(100,'(3/,a)') BASISNAME
IF (BASISNAME(1:6)=='BASIS ') THEN
! The basis set is an existing one in the basis library
LIBRARY=.TRUE.
BASISFILE='basis/'//BASISNAME(7:)
READ(100,'(a4)') CHAR
IF (CHAR=='UNCO') THEN
UNCONT=.TRUE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)'
ELSE
UNCONT=.FALSE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)'
END IF
ELSE IF (BASISNAME(1:4)=='EVEN') THEN
! The basis set is an even-tempered one
LIBRARY=.FALSE.
IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)'
WRITE(*,'(a)')' Even-tempered basis set (preliminary support)'
READ(100,'(i4)') NUMBER_OF_TERMS
WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS
READ(100,*) FIRST_TERM
WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM
READ(100,*) COMMON_RATIO
WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO
ELSE
STOP' Unknown basis set type'
END IF
IF (RELATIVISTIC) THEN
READ(100,'(a2)') CHAR
IF (CHAR=='KI') THEN
KINBAL=.TRUE.
READ(100,'(a4)') CHAR
IF (CHAR=='REST') THEN
UKB=.FALSE.
WRITE(*,'(a)')' Restricted kinetic balance'
ELSE
UKB=.TRUE.
WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance'
END IF
ELSE
KINBAL=.FALSE.
WRITE(*,'(a)')' No kinetic balance'
END IF
END IF
CLOSE(100)
END SUBROUTINE SETUP_BASIS
FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE)
! Function that computes the value of a gaussian basis function at a given point of space.
USE iso_c_binding
TYPE(gaussianbasisfunction),INTENT(IN) :: GBF
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) &
& *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), &
& EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2)))
END FUNCTION GBF_POINTWISE_VALUE
SUBROUTINE PRINTGBF(PHI,NUNIT)
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NUNIT
INTEGER :: I
WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents
WRITE(NUNIT,*)' center:',PHI%center
WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree
DO I=1,PHI%nbrofexponents
WRITE(NUNIT,*)' gaussian primitive #',I
WRITE(NUNIT,*)' exponent:',PHI%exponents(I)
WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I)
END DO
END SUBROUTINE PRINTGBF
FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE)
! Function that computes the value of a Pauli 2-spinor basis function at a given point of space.
USE iso_c_binding
TYPE(twospinor),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE COMPLEX,DIMENSION(2) :: VALUE
INTEGER :: I,J
DO I=1,2
VALUE(I)=(0.D0,0.D0)
DO J=1,PHI%nbrofcontractions(I)
VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT)
END DO
END DO
END FUNCTION TWOSPINOR_POINTWISE_VALUE
SUBROUTINE PRINT2SPINOR(PHI,NUNIT)
TYPE(twospinor),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NUNIT
INTEGER :: I,J,K
DO K=1,2
WRITE(NUNIT,*)'component #',K
IF (PHI%nbrofcontractions(K)==0) THEN
WRITE(NUNIT,*)' no contraction'
ELSE
WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K)
|
antoine-levitt/ACCQUAREL
|
d621ca0e1b69a228f61c4fe370539d6df5f5b255
|
New LSINTEGRALS variable
|
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90
index 4a838ac..9c57dfa 100644
--- a/src/integrals_f.f90
+++ b/src/integrals_f.f90
@@ -1,558 +1,564 @@
MODULE integrals
! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/).
! number of a priori nonzero bielectronic integrals
INTEGER :: BINMBR
! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory)
INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES
CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE
! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK
INTEGER,DIMENSION(2) :: NBF
! unit number for the list of nonzero bielectronic integrals (when stored on disk)
INTEGER,PARAMETER :: LUNIT=10
! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk)
INTEGER,PARAMETER :: BIUNIT=11
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) &
& BIND(C,NAME="unrolloverlap")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) &
& BIND(C,NAME="unrollkinetic")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& dimension) &
& BIND(C,NAME="unrollderiv")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
INTEGER(KIND=C_INT),VALUE :: dimension
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& center) &
& BIND(C,NAME="unrollpotential")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& dimension1,dimension2) &
& BIND(C,NAME="unrollxderiv")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, &
& nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) &
& BIND(C,NAME="unrollcoulomb")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d
END FUNCTION
END INTERFACE
INTERFACE COULOMBVALUE
MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed
END INTERFACE
INTERFACE BUILDBILIST
MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic
END INTERFACE
CONTAINS
FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree)
END FUNCTION OVERLAPVALUE
FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree)
END FUNCTION KINETICVALUE
FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator).
! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z).
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& DIMENSION-1)
END FUNCTION DERIVVALUE
FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& CENTER)
END FUNCTION POTENTIALVALUE
FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator).
! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z).
! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z).
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& DIMENSION1-1,DIMENSION2-1)
END FUNCTION XDERIVVALUE
FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE)
! Function that computes the value of the bielectronic integral between four gaussian basis functions.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, &
& PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree)
END FUNCTION COULOMBVALUE_nonrelativistic
SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE)
! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value.
! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974.
USE case_parameters ; USE basis_parameters
TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
INTEGER,INTENT(OUT) :: LISTSIZE
INTEGER :: I,J,K,L
INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE
LOGICAL :: SC,SS
! same spin check. Not used outside GHF
SS = .TRUE.
OPEN(LUNIT,form='UNFORMATTED')
! determination of the number of elements (i.e., integer quadruples) that compose the list
LISTSIZE=0
DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K
! same center?
SC=((PHI(I)%center_id==PHI(J)%center_id).AND.(PHI(J)%center_id==PHI(K)%center_id).AND.(PHI(K)%center_id==PHI(L)%center_id))
GLOBALMONOMIALDEGREE=PHI(I)%monomialdegree+PHI(J)%monomialdegree+PHI(K)%monomialdegree+PHI(L)%monomialdegree
! same spin? i must have same spin as j, same for k and l
IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.&
&(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2)))
! parity check on the product of the monomials if the four functions share the same center
IF (((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)).AND.SS) THEN
LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L
IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.&
&(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2)))
IF ((K<J).AND.SS) THEN
LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L
END IF
IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.&
&(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2)))
IF ((J<I).AND.(L<K).AND.SS) THEN
LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K
END IF
END IF
END DO ; END DO ; END DO ; END DO
CLOSE(LUNIT)
WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE
END SUBROUTINE BUILDBILIST_nonrelativistic
FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE)
! Function that computes the value of the bielectronic integral between four 2-spinor basis functions.
USE basis_parameters
TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D
DOUBLE COMPLEX :: VALUE
INTEGER :: I,IA,IB,J,JC,JD
VALUE=(0.D0,0.D0)
DO I=1,2
DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I)
DO J=1,2
DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J)
VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) &
& *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) &
& *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), &
& PHI_D%contractions(J,JD))
END DO ; END DO
END DO
END DO ; END DO
END DO
END FUNCTION COULOMBVALUE_relativistic
FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE)
! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions.
USE basis_parameters
TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D
CHARACTER(2),INTENT(IN) :: CLASS
DOUBLE COMPLEX :: VALUE
INTEGER :: I,IA,IB,J,JC,JD
VALUE=(0.D0,0.D0)
DO I=1,2
DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I)
DO J=1,2
DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J)
VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) &
& *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) &
& *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), &
& PHI_D%contidx(J,JD),CLASS)
END DO ; END DO
END DO
END DO ; END DO
END DO
END FUNCTION COULOMBVALUE_precomputed
SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE)
! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value.
USE case_parameters ; USE basis_parameters ; USE scf_parameters
TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3)
INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6
INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE
LOGICAL :: SC
OPEN(LUNIT,form='UNFORMATTED')
! determination of the number of elements (i.e., integer quadruples) that compose the list
SUBSIZE=0
! LLLL-type integrals
DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1)
IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN
DO I1=1,2
DO I2=1,PHI(I)%nbrofcontractions(I1)
DO I3=1,PHI(J)%nbrofcontractions(I1)
DO I4=1,2
DO I5=1,PHI(K)%nbrofcontractions(I4)
DO I6=1,PHI(L)%nbrofcontractions(I4)
SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) &
& .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) &
& .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id))
GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree &
& +PHI(J)%contractions(I1,I3)%monomialdegree &
& +PHI(K)%contractions(I4,I5)%monomialdegree &
& +PHI(L)%contractions(I4,I6)%monomialdegree
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
SUBSIZE(1)=SUBSIZE(1)+1
WRITE(LUNIT)I,J,K,L,'LL'
GO TO 1
END IF
END DO
END DO
END DO
END DO
END DO
END DO
1 CONTINUE
END IF
END DO ; END DO ; END DO ; END DO
! SSLL-type integrals
+ IF(SLINTEGRALS) THEN
DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1)
DO I1=1,2
DO I2=1,PHI(I)%nbrofcontractions(I1)
DO I3=1,PHI(J)%nbrofcontractions(I1)
DO I4=1,2
DO I5=1,PHI(K)%nbrofcontractions(I4)
DO I6=1,PHI(L)%nbrofcontractions(I4)
SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) &
& .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) &
& .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id))
GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree &
& +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
WRITE(LUNIT)I,J,K,L,'SL'
SUBSIZE(2)=SUBSIZE(2)+1
GO TO 2
END IF
END DO
END DO
END DO
END DO
END DO
END DO
2 CONTINUE
- END DO ; END DO ; END DO ; END DO
+ END DO; END DO ; END DO ; END DO
+ END IF
IF (SSINTEGRALS) THEN
! SSSS-type integrals
DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS)
IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN
DO I1=1,2
DO I2=1,PHI(I)%nbrofcontractions(I1)
DO I3=1,PHI(J)%nbrofcontractions(I1)
DO I4=1,2
DO I5=1,PHI(K)%nbrofcontractions(I4)
DO I6=1,PHI(L)%nbrofcontractions(I4)
SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) &
& .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) &
& .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id))
GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree &
& +PHI(J)%contractions(I1,I3)%monomialdegree &
& +PHI(K)%contractions(I4,I5)%monomialdegree &
& +PHI(L)%contractions(I4,I6)%monomialdegree
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
WRITE(LUNIT)I,J,K,L,'SS'
SUBSIZE(3)=SUBSIZE(3)+1
GO TO 3
END IF
END DO
END DO
END DO
END DO
END DO
END DO
3 CONTINUE
END IF
END DO ; END DO ; END DO ; END DO
END IF
LISTSIZE=SUM(SUBSIZE)
CLOSE(LUNIT)
WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE
END SUBROUTINE BUILDBILIST_relativistic
SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function).
USE basis_parameters ; USE scf_parameters
INTEGER,DIMENSION(2),INTENT(IN) :: NGBF
TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF
INTEGER :: I,J,K,L,M,N,O
INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE
LOGICAL :: SC
NBF=NGBF
! (LL|LL) integrals
WRITE(*,*)'- Computing LL integrals'
ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), &
& LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), &
& LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24))
M=0 ; N=0 ; O=0
DO I=1,NGBF(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K
SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id))
GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
! parity check (one center case)
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
IF (K<J) THEN
N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L))
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K))
END IF
ELSE
M=M+1 ; LLIJKL(M)=(0.D0,0.D0)
IF (K<J) THEN
N=N+1 ; LLIKJL(N)=(0.D0,0.D0)
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; LLILJK(O)=(0.D0,0.D0)
END IF
END IF
END DO ; END DO ; END DO ; END DO
-! (SS|LL) integrals
- WRITE(*,*)'- Computing SL integrals'
- ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4))
- N=0
-! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly.
- !$OMP PARALLEL DO PRIVATE(N,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1)
- DO I=NGBF(1)+1,SUM(NGBF)
-! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential).
- N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2
- ! this takes N(N+1)/2*(I-N) iters
- DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K
- SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id))
- GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
-! parity check (one center case)
- IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
- N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
- ELSE
- N=N+1 ; SLIJKL(N)=(0.D0,0.D0)
- END IF
- END DO ; END DO ; END DO ; END DO
- !$OMP END PARALLEL DO
+ IF(SLINTEGRALS) THEN
+ ! (SS|LL) integrals
+ WRITE(*,*)'- Computing SL integrals'
+ ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4))
+ N=0
+ ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly.
+ !$OMP PARALLEL DO PRIVATE(N,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1)
+ DO I=NGBF(1)+1,SUM(NGBF)
+ ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential).
+ N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2
+ ! this takes N(N+1)/2*(I-N) iters
+ DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K
+ SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.&
+ &(GBF(K)%center_id==GBF(L)%center_id))
+ GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
+ ! parity check (one center case)
+ IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
+ N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
+ ELSE
+ N=N+1 ; SLIJKL(N)=(0.D0,0.D0)
+ END IF
+ END DO; END DO ; END DO ; END DO
+ !$OMP END PARALLEL DO
+ END IF
IF (SSINTEGRALS) THEN
! (SS|SS) integrals
WRITE(*,*)'- Computing SS integrals'
ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), &
& SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), &
& SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24))
M=0 ; N=0 ; O=0
!$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1)
DO I=NGBF(1)+1,SUM(NGBF)
! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential).
M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24
N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24
O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24
DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K
SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id))
GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
! parity check (one center case)
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
IF (K<J) THEN
N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L))
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K))
END IF
ELSE
M=M+1 ; SSIJKL(M)=(0.D0,0.D0)
IF (K<J) THEN
N=N+1 ; SSIKJL(N)=(0.D0,0.D0)
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; SSILJK(O)=(0.D0,0.D0)
END IF
END IF
END DO ; END DO ; END DO ; END DO
!$OMP END PARALLEL DO
END IF
END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES
FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE)
! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974).
! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis.
USE basis_parameters
INTEGER,INTENT(IN) :: I,J,K,L
CHARACTER(2),INTENT(IN) :: CLASS
DOUBLE COMPLEX :: VALUE
INTEGER :: IDX
INTEGER,DIMENSION(4) :: N,TMP
! Preliminaries
N=(/I,J,K,L/)
TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/)
TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/)
TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/)
IF (CLASS.EQ.'LL') THEN
! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions
IF (N(3)<=N(2)) THEN
! integral of type (IJ|KL)
IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=LLIJKL(IDX)
ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN
! integral of type (IJ|KL)
IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=LLIJKL(IDX)
ELSE IF (N(4)<=N(2)) THEN
! integral of type (IK|JL)
IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=LLIKJL(IDX)
ELSE IF (N(1)==N(3)) THEN
! integral of type (IK|JL)
IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=LLIKJL(IDX)
ELSE
! integral of type (IL|JK)
IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24
VALUE=LLILJK(IDX)
END IF
ELSE IF (CLASS=='SL') THEN
! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions
N(1:2)=N(1:2)-(/NBF(1),NBF(1)/)
IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2
VALUE=SLIJKL(IDX)
ELSE IF (CLASS=='SS') THEN
N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/)
! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions
IF (N(3)<=N(2)) THEN
! integral of type (IJ|KL)
IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=SSIJKL(IDX)
ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN
! integral of type (IJ|KL)
IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=SSIJKL(IDX)
ELSE IF (N(4)<=N(2)) THEN
! integral of type (IK|JL)
IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=SSIKJL(IDX)
ELSE IF (N(1)==N(3)) THEN
! integral of type (IK|JL)
IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=SSIKJL(IDX)
ELSE
! integral of type (IL|JK)
IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24
VALUE=SSILJK(IDX)
END IF
END IF
END FUNCTION PRECOMPUTEDCOULOMBVALUE
SUBROUTINE DEALLOCATE_INTEGRALS
USE scf_parameters
! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis.
- DEALLOCATE(LLIJKL,LLIKJL,LLILJK,SLIJKL)
+ DEALLOCATE(LLIJKL,LLIKJL,LLILJK)
IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK)
+ IF (SLINTEGRALS) DEALLOCATE(SLIJKL)
END SUBROUTINE DEALLOCATE_INTEGRALS
END MODULE
diff --git a/src/setup.f90 b/src/setup.f90
index bf6248a..f925901 100644
--- a/src/setup.f90
+++ b/src/setup.f90
@@ -119,640 +119,642 @@ SUBROUTINE SETUP_FORMALISM
END IF
END IF
END IF
CLOSE(100)
RETURN
1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!'
STOP
END SUBROUTINE SETUP_FORMALISM
END MODULE
MODULE data_parameters
USE iso_c_binding
! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS **
! number of nuclei in the molecular system (at most 10)
INTEGER :: NBN
! atomic numbers of the nuclei
INTEGER,DIMENSION(10) :: Z
! positions of the nucleii
DOUBLE PRECISION,DIMENSION(3,10) :: CENTER
! total number of electrons in the molecular system
INTEGER :: NBE
! total number of electrons in the closed shells (open-shell DHF formalism)
INTEGER :: NBECS
! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism)
INTEGER :: NBEOS,NBOOS
! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms)
INTEGER :: NBEA,NBEB
! internuclear repulsion energy
DOUBLE PRECISION :: INTERNUCLEAR_ENERGY
! ** DATA FOR BOSON STAR MODEL **
DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0
! mass
DOUBLE PRECISION :: MASS
! temperature
DOUBLE PRECISION :: TEMPERATURE
! exponent for the function defining the Tsallis-related entropy term
DOUBLE PRECISION :: MB
!
INTEGER,POINTER :: RANK_P
DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I
CONTAINS
SUBROUTINE SETUP_DATA
USE case_parameters ; USE setup_tools
IMPLICIT NONE
CHARACTER(30) :: NAME
INTEGER :: INFO,N
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN
CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- **** ---'
READ(100,*) NAME
READ(100,*) MASS
WRITE(*,'(a,f5.3)')' * Mass = ',MASS
READ(100,*) TEMPERATURE
WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE
READ(100,*) MB
WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB
WRITE(*,'(a)')' --- **** ---'
ELSE
CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- Molecular system ---'
READ(100,'(3/,a)')NAME
WRITE(*,'(a,a)')' ** NAME: ',NAME
READ(100,'(i2)') NBN
DO N=1,NBN
WRITE(*,'(a,i2)')' * Nucleus #',N
READ(100,*) Z(N),CENTER(:,N)
WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')'
WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N)
END DO
CALL INTERNUCLEAR_REPULSION_ENERGY
WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY
READ(100,'(i3)') NBE
WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE
IF (RELATIVISTIC) THEN
IF (MODEL==2) THEN
READ(100,'(3(i3))')NBECS,NBEOS,NBOOS
WRITE(*,'(a,i3)')' - number of closed shell electrons = ',NBECS
WRITE(*,'(a,i3)')' - number of open shell electrons = ',NBEOS
WRITE(*,'(a,i3)')' - number of open shell orbitals = ',NBOOS
IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons'
IF (NBOOS<=NBEOS) STOP' Problem with the number of open shell orbitals!'
END IF
ELSE
IF (MODEL==1) THEN
IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!'
ELSE IF (MODEL==2) THEN
READ(100,'(2(i3))')NBEA,NBEB
WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA
WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB
IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!'
! ELSE IF (MODEL==3) THEN
END IF
END IF
WRITE(*,'(a)')' --------- **** ---------'
END IF
CLOSE(100)
END SUBROUTINE SETUP_DATA
FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL)
! Function returning the symbol of a chemical element given its atomic number Z.
INTEGER,INTENT(IN) :: Z
CHARACTER(2) :: SYMBOL
IF (Z>104) THEN
WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!'
STOP
END IF
! List of symbols from Hydrogen up to Rutherfordium.
SELECT CASE (Z)
CASE (1) ; SYMBOL='H'
CASE (2) ; SYMBOL='He'
CASE (3) ; SYMBOL='Li'
CASE (4) ; SYMBOL='Be'
CASE (5) ; SYMBOL='B'
CASE (6) ; SYMBOL='C'
CASE (7) ; SYMBOL='N'
CASE (8) ; SYMBOL='O'
CASE (9) ; SYMBOL='F'
CASE (10) ; SYMBOL='Ne'
CASE (11) ; SYMBOL='Na'
CASE (12) ; SYMBOL='Mg'
CASE (13) ; SYMBOL='Al'
CASE (14) ; SYMBOL='Si'
CASE (15) ; SYMBOL='P'
CASE (16) ; SYMBOL='S'
CASE (17) ; SYMBOL='Cl'
CASE (18) ; SYMBOL='Ar'
CASE (19) ; SYMBOL='K'
CASE (20) ; SYMBOL='Ca'
CASE (21) ; SYMBOL='Sc'
CASE (22) ; SYMBOL='Ti'
CASE (23) ; SYMBOL='V'
CASE (24) ; SYMBOL='Cr'
CASE (25) ; SYMBOL='Mn'
CASE (26) ; SYMBOL='Fe'
CASE (27) ; SYMBOL='Co'
CASE (28) ; SYMBOL='Ni'
CASE (29) ; SYMBOL='Cu'
CASE (30) ; SYMBOL='Zn'
CASE (31) ; SYMBOL='Ga'
CASE (32) ; SYMBOL='Ge'
CASE (33) ; SYMBOL='As'
CASE (34) ; SYMBOL='Se'
CASE (35) ; SYMBOL='Br'
CASE (36) ; SYMBOL='Kr'
CASE (37) ; SYMBOL='Rb'
CASE (38) ; SYMBOL='Sr'
CASE (39) ; SYMBOL='Y'
CASE (40) ; SYMBOL='Zr'
CASE (41) ; SYMBOL='Nb'
CASE (42) ; SYMBOL='Mo'
CASE (43) ; SYMBOL='Tc'
CASE (44) ; SYMBOL='Ru'
CASE (45) ; SYMBOL='Rh'
CASE (46) ; SYMBOL='Pd'
CASE (47) ; SYMBOL='Ag'
CASE (48) ; SYMBOL='Cd'
CASE (49) ; SYMBOL='In'
CASE (50) ; SYMBOL='Sn'
CASE (51) ; SYMBOL='Sb'
CASE (52) ; SYMBOL='Te'
CASE (53) ; SYMBOL='I'
CASE (54) ; SYMBOL='Xe'
CASE (55) ; SYMBOL='Cs'
CASE (56) ; SYMBOL='Ba'
CASE (57) ; SYMBOL='La'
! Lanthanide elements (lanthanoids)
CASE (58) ; SYMBOL='Ce'
CASE (59) ; SYMBOL='Pr'
CASE (60) ; SYMBOL='Nd'
CASE (61) ; SYMBOL='Pm'
CASE (62) ; SYMBOL='Sm'
CASE (63) ; SYMBOL='Eu'
CASE (64) ; SYMBOL='Gd'
CASE (65) ; SYMBOL='Tb'
CASE (66) ; SYMBOL='Dy'
CASE (67) ; SYMBOL='Ho'
CASE (68) ; SYMBOL='Er'
CASE (69) ; SYMBOL='Tm'
CASE (70) ; SYMBOL='Yb'
CASE (71) ; SYMBOL='Lu'
CASE (72) ; SYMBOL='Hf'
CASE (73) ; SYMBOL='Ta'
CASE (74) ; SYMBOL='W'
CASE (75) ; SYMBOL='Re'
CASE (76) ; SYMBOL='Os'
CASE (77) ; SYMBOL='Ir'
CASE (78) ; SYMBOL='Pt'
CASE (79) ; SYMBOL='Au'
CASE (80) ; SYMBOL='Hg'
CASE (81) ; SYMBOL='Tl'
CASE (82) ; SYMBOL='Pb'
CASE (83) ; SYMBOL='Bi'
CASE (84) ; SYMBOL='Po'
CASE (85) ; SYMBOL='As'
CASE (86) ; SYMBOL='Rn'
CASE (87) ; SYMBOL='Fr'
CASE (88) ; SYMBOL='Ra'
CASE (89) ; SYMBOL='Ac'
! Actinide elements (actinoids)
CASE (90) ; SYMBOL='Th'
CASE (91) ; SYMBOL='Pa'
CASE (92) ; SYMBOL='U'
CASE (93) ; SYMBOL='Np'
CASE (94) ; SYMBOL='Pu'
CASE (95) ; SYMBOL='Am'
CASE (96) ; SYMBOL='Cm'
CASE (97) ; SYMBOL='Bk'
CASE (98) ; SYMBOL='Cf'
CASE (99) ; SYMBOL='Es'
CASE (100); SYMBOL='Fm'
CASE (101); SYMBOL='Md'
CASE (102); SYMBOL='No'
CASE (103); SYMBOL='Lr'
CASE (104); SYMBOL='Rf'
END SELECT
END FUNCTION IDENTIFYZ
SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system.
INTEGER :: I,J
DOUBLE PRECISION,DIMENSION(3) :: DIFF
INTERNUCLEAR_ENERGY=0.D0
DO I=1,NBN
DO J=I+1,NBN
DIFF=CENTER(:,I)-CENTER(:,J)
INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF))
END DO
END DO
END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Various functions for the Hartree model with temperature
FUNCTION POSITIVE_PART(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
FUNC=0.D0
ELSE
FUNC=X
END IF
END FUNCTION POSITIVE_PART
FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC)
! beta test function for the entropy
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
FUNC=POSITIVE_PART(X)**MB/MB
END FUNCTION ENTROPY_FUNCTION
FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE
FUNC=X**(1.D0/(MB-1.D0))
END IF
END FUNCTION RECIP_DENTFUNC
FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE IF (X==0.D0) THEN
STOP'No derivative at origin'
ELSE
FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0)
END IF
END FUNCTION
FUNCTION FUNCFORMU(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
INTEGER :: I
DOUBLE PRECISION :: Y
FUNC=-MASS
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
IF (Y>=0.D0) THEN
FUNC=FUNC+RECIP_DENTFUNC(Y)
END IF
END DO
END FUNCTION FUNCFORMU
SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV
INTEGER :: I
DOUBLE PRECISION :: Y
FVAL=-MASS ; FDERIV=0.D0
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
FVAL=FVAL+RECIP_DENTFUNC(Y)
FDERIV=FDERIV+DRECIP_DENTFUNC(Y)
END DO
END SUBROUTINE RDENTFUNCD
END MODULE
MODULE basis_parameters
USE iso_c_binding
! flag for the choice of the basis set type (either existing in the library or even-tempered)
LOGICAL :: LIBRARY
! PARAMETERS FOR A GIVEN BASIS SET
CHARACTER(26) :: BASISFILE
INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4
! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme.
! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET
INTEGER :: NUMBER_OF_TERMS
DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO
! Various flags for the contraction of the primitives and the Kinetic Balance scheme
LOGICAL :: UNCONT
LOGICAL :: KINBAL,UKB
TYPE gaussianbasisfunction
! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function.
! nbrofexponents: the number of different gaussian primitives present in the contraction
! center: coordinates (x,y,z) of the center of the basis function
! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center)
! exponents: array containing the exponent of each of the gaussian primitives present in the contraction
! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction
! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives
! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance).
INTEGER(KIND=C_INT) :: nbrofexponents
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center
INTEGER :: center_id
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree
END TYPE gaussianbasisfunction
TYPE twospinor
! Definition of a Pauli 2-spinor type basis function using gaussian basis functions.
! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor
! contractions: array containing the contractions present in each of the components of the 2-spinor
! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes)
! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor
! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0
INTEGER,DIMENSION(2) :: nbrofcontractions
TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions
INTEGER,DIMENSION(2,MNOGBF) :: contidx
DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients
END TYPE twospinor
CONTAINS
SUBROUTINE SETUP_BASIS
USE case_parameters ; USE setup_tools
CHARACTER(LEN=4) :: CHAR
CHARACTER(LEN=26) :: BASISNAME
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## BASIS DEFINITION',INFO)
IF (INFO/=0) STOP
READ(100,'(3/,a)') BASISNAME
IF (BASISNAME(1:6)=='BASIS ') THEN
! The basis set is an existing one in the basis library
LIBRARY=.TRUE.
BASISFILE='basis/'//BASISNAME(7:)
READ(100,'(a4)') CHAR
IF (CHAR=='UNCO') THEN
UNCONT=.TRUE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)'
ELSE
UNCONT=.FALSE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)'
END IF
ELSE IF (BASISNAME(1:4)=='EVEN') THEN
! The basis set is an even-tempered one
LIBRARY=.FALSE.
IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)'
WRITE(*,'(a)')' Even-tempered basis set (preliminary support)'
READ(100,'(i4)') NUMBER_OF_TERMS
WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS
READ(100,*) FIRST_TERM
WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM
READ(100,*) COMMON_RATIO
WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO
ELSE
STOP' Unknown basis set type'
END IF
IF (RELATIVISTIC) THEN
READ(100,'(a2)') CHAR
IF (CHAR=='KI') THEN
KINBAL=.TRUE.
READ(100,'(a4)') CHAR
IF (CHAR=='REST') THEN
UKB=.FALSE.
WRITE(*,'(a)')' Restricted kinetic balance'
ELSE
UKB=.TRUE.
WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance'
END IF
ELSE
KINBAL=.FALSE.
WRITE(*,'(a)')' No kinetic balance'
END IF
END IF
CLOSE(100)
END SUBROUTINE SETUP_BASIS
FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE)
! Function that computes the value of a gaussian basis function at a given point of space.
USE iso_c_binding
TYPE(gaussianbasisfunction),INTENT(IN) :: GBF
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) &
& *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), &
& EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2)))
END FUNCTION GBF_POINTWISE_VALUE
SUBROUTINE PRINTGBF(PHI,NUNIT)
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NUNIT
INTEGER :: I
WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents
WRITE(NUNIT,*)' center:',PHI%center
WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree
DO I=1,PHI%nbrofexponents
WRITE(NUNIT,*)' gaussian primitive #',I
WRITE(NUNIT,*)' exponent:',PHI%exponents(I)
WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I)
END DO
END SUBROUTINE PRINTGBF
FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE)
! Function that computes the value of a Pauli 2-spinor basis function at a given point of space.
USE iso_c_binding
TYPE(twospinor),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE COMPLEX,DIMENSION(2) :: VALUE
INTEGER :: I,J
DO I=1,2
VALUE(I)=(0.D0,0.D0)
DO J=1,PHI%nbrofcontractions(I)
VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT)
END DO
END DO
END FUNCTION TWOSPINOR_POINTWISE_VALUE
SUBROUTINE PRINT2SPINOR(PHI,NUNIT)
TYPE(twospinor),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NUNIT
INTEGER :: I,J,K
DO K=1,2
WRITE(NUNIT,*)'component #',K
IF (PHI%nbrofcontractions(K)==0) THEN
WRITE(NUNIT,*)' no contraction'
ELSE
WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K)
DO I=1,PHI%nbrofcontractions(K)
WRITE(NUNIT,*)' contraction #',I
WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I)
WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents
WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree
WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center
DO J=1,PHI%contractions(K,I)%nbrofexponents
WRITE(NUNIT,*)' gaussian primitive #',J
WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J)
WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J)
END DO
END DO
END IF
END DO
END SUBROUTINE PRINT2SPINOR
END MODULE
MODULE scf_parameters
! number of different SCF algorithms to be used
INTEGER :: NBALG
! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only))
INTEGER,DIMENSION(5) :: ALG
! threshold for numerical convergence
DOUBLE PRECISION :: TRSHLD
! maximum number of iterations allowed
INTEGER :: MAXITR
! direct computation of the bielectronic integrals or not
LOGICAL :: DIRECT
! "semi-direct" computation of the bielectronic integrals (relativistic case only)
! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards.
LOGICAL :: SEMIDIRECT
! storage of the computed bielectronic integrals (and/or their list) on disk or in memory
LOGICAL :: USEDISK
! use of the SS-bielectronic integrals
LOGICAL :: SSINTEGRALS
+ ! use of the SL-bielectronic integrals. Should not be set by the user directly
+ LOGICAL :: SLINTEGRALS = .TRUE.
CONTAINS
SUBROUTINE SETUP_SCF
!$ USE omp_lib
USE case_parameters ; USE setup_tools
CHARACTER :: METHOD
CHARACTER(4) :: CHAR
INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS
DOUBLE PRECISION :: SHIFT
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## SCF PARAMETERS',INFO)
IF (INFO/=0) STOP
READ(100,'(7/,i1)') NBALG
DO I=1,NBALG
READ(100,'(i1)') ALG(I)
IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN
STOP'The Optimal Damping Algorithm is intended for the non-relativistic case only.'
ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN
STOP'ES''s algorithm is intended for the relativistic case only.'
END IF
END DO
READ(100,*) TRSHLD
WRITE(*,*)'Threshold =',TRSHLD
READ(100,'(i5)') MAXITR
WRITE(*,*)'Maximum number of iterations =',MAXITR
READ(100,'(a3)') CHAR
IF (RELATIVISTIC) THEN
IF (CHAR=='DIR') THEN
DIRECT=.TRUE.
WRITE(*,'(a)')' Direct computation of the bielectronic integrals'
! check if the list of the bielectronic integrals is stored on disk or in memory
READ(100,'(a4)') CHAR
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
ELSE
USEDISK=.FALSE.
END IF
ELSE IF (CHAR=='NOT') THEN
DIRECT=.FALSE. ; SEMIDIRECT=.FALSE.
READ(100,'(a4)') CHAR
! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory)
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
WRITE(*,'(a)')' Computed bielectronic integrals stored on disk'
ELSE
USEDISK=.FALSE.
WRITE(*,'(a)')' Computed bielectronic integrals stored in memory'
END IF
ELSE IF (CHAR=='SEM') THEN
DIRECT=.FALSE. ; SEMIDIRECT=.TRUE.
WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals'
! check if the list of the bielectronic integrals is stored on disk or in memory
READ(100,'(a4)') CHAR
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
ELSE
USEDISK=.FALSE.
END IF
ELSE
WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.'
STOP
END IF
READ(100,'(a4)') CHAR
IF (CHAR=='NOSS') THEN
SSINTEGRALS=.FALSE.
WRITE(*,'(a)')' (SS-integrals are not used in the computation)'
ELSE
SSINTEGRALS=.TRUE.
END IF
ELSE
IF (CHAR=='DIR') THEN
DIRECT=.TRUE.
WRITE(*,'(a)')' Direct computation of the bielectronic integrals'
! the list of the bielectronic integrals is stored in memory
ELSE IF (CHAR=='NOT') THEN
DIRECT=.FALSE.
! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory)
READ(100,'(a4)') CHAR
IF (CHAR=='DISK') THEN
USEDISK=.TRUE.
WRITE(*,'(a)')' Computed bielectronic integrals stored on disk'
ELSE
USEDISK=.FALSE.
WRITE(*,'(a)')' Computed bielectronic integrals stored in memory'
END IF
ELSE
WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.'
STOP
END IF
END IF
! additional verifications on the parameters of the algorithms
DO I=1,NBALG
IF (ALG(I)==2) THEN
REWIND(100)
CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO)
IF (INFO/=0) GO TO 1
READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT
ELSE IF (ALG(I)==3) THEN
REWIND(100)
CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO)
IF (INFO/=0) GO TO 2
READ(100,'(/,i2)',ERR=2,END=2)MXSET
IF (MXSET<2) GO TO 3
ELSE IF (ALG(I)==5) THEN
REWIND(100)
CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO)
IF (INFO/=0) GO TO 4
READ(100,'(/,a)',ERR=4,END=4)METHOD
IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4
END IF
END DO
!$ ! determination of the number of threads to be used by OpenMP
!$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO)
!$ IF (INFO==0) THEN
!$ READ(100,'(/,i3)')NUMBER_OF_THREADS
!$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS)
!$ END IF
!$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.'
CLOSE(100)
RETURN
! MESSAGES
1 STOP'No shift parameter given for the level-shifting algorithm.'
2 STOP'No simplex dimension given for the DIIS algorithm.'
3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.'
4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.'
END SUBROUTINE SETUP_SCF
END MODULE
|
antoine-levitt/ACCQUAREL
|
d2089d7bf16fb62e1061a712dd2c98aa762e0742
|
Plot functions: take non-symmetric matrices as input
|
diff --git a/src/scf.f90 b/src/scf.f90
index 40ab732..61f30e8 100644
--- a/src/scf.f90
+++ b/src/scf.f90
@@ -1,460 +1,460 @@
MODULE scf_tools
INTERFACE CHECKNUMCONV
MODULE PROCEDURE CHECKNUMCONV_relativistic,CHECKNUMCONV_AOCOSDHF,CHECKNUMCONV_RHF,CHECKNUMCONV_UHF
END INTERFACE
CONTAINS
SUBROUTINE CHECKORB(EIG,N,LOON)
! Subroutine that determines the number of the lowest and highest occupied electronic orbitals and checks if they are both in the spectral gap (in the relavistic case).
USE case_parameters ; USE data_parameters
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N),INTENT(IN) :: EIG
INTEGER,INTENT(IN) :: N
INTEGER,INTENT(OUT) :: LOON
INTEGER :: HGEN
! Determination of the number of the lowest occupied orbital (i.e., the one relative to the first eigenvalue associated to an electronic state in the gap)
LOON=MINLOC(EIG,DIM=1,MASK=EIG>-C*C)
IF (LOON.EQ.0) THEN
STOP'Subroutine CHECKORB: no eigenvalue associated to an electronic state.'
ELSE
WRITE(*,'(a,i3,a,i3,a)')' Number of the lowest occupied electronic orbital = ',LOON,'(/',N,')'
IF (N-LOON.LT.NBE) THEN
WRITE(*,'(a)')' Subroutine CHECKORB: there are not enough eigenvalues associated to electronic states (',N-LOON,').'
STOP
END IF
! Determination of the number of the highest orbital relative to an eigenvalue associated to an electronic state in the gap
HGEN=MAXLOC(EIG,DIM=1,MASK=EIG<0.D0)
WRITE(*,'(a,i3)')' Number of eigenvalues associated to electronic states in the gap = ',HGEN-LOON+1
IF (HGEN-LOON+1.LT.NBE) THEN
WRITE(*,'(a,i2,a)')' Warning: there are less than ',NBE,' eigenvalues associated to electronic states in the gap.'
END IF
END IF
END SUBROUTINE CHECKORB
SUBROUTINE CHECKNUMCONV_relativistic(PDMN,PDMO,PFM,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock equations (restricted closed-shell Hartree-Fock and closed-shell Dirac-Hartree-Fock formalisms).
USE matrix_tools ; USE metric_relativistic
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMN,PDMO,PFM
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE COMPLEX,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMT
DOUBLE PRECISION,DIMENSION(N) :: WORK
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMN-PDMO,N)
WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
WRITE(17,'(e22.14)')FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFM,PDMN,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n),D_n] =',NORM(CMT,N,'I')
FNCMT=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n),D_n] =',FNCMT
WRITE(18,'(e22.14)')FNCMT
IF (FNCMT<=TRSHLD) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
WRITE(16,'(e22.14)')ETOTN
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_relativistic
SUBROUTINE CHECKNUMCONV_RHF(PDMN,PDMO,PFM,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock equations (restricted closed-shell Hartree-Fock formalism).
USE matrix_tools ; USE metric_nonrelativistic
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMN,PDMO,PFM
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE PRECISION,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMT
DOUBLE PRECISION,DIMENSION(N) :: WORK
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMN-PDMO,N)
WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
WRITE(17,'(e22.14)')FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFM,PDMN,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n),D_n] =',NORM(CMT,N,'I')
FNCMT=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n),D_n] =',FNCMT
WRITE(18,'(e22.14)')FNCMT
IF (FNCMT<=TRSHLD) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
WRITE(16,'(e22.14)')ETOTN
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_RHF
SUBROUTINE CHECKNUMCONV_UHF(PDMA,PDMB,PTDMO,PFMA,PFMB,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock type equations (unrestricted open-shell Hartree-Fock formalism).
USE matrix_tools ; USE metric_nonrelativistic
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMA,PDMB,PTDMO,PFMA,PFMB
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE PRECISION,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMTA,FNCMTB
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMA+PDMB-PTDMO,N)
WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMA,PDMA,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n^a),D_n^a] =',NORM(CMT,N,'I')
FNCMTA=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^a),D_n^a] =',FNCMTA
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMB,PDMB,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n^b),D_n^b] =',NORM(CMT,N,'I')
FNCMTB=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^b),D_n^b] =',FNCMTB
IF ((FNCMTA<=TRSHLD).AND.(FNCMTB<=TRSHLD)) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_UHF
SUBROUTINE CHECKNUMCONV_AOCOSDHF(PDMCN,PDMON,PDMCO,PDMOO,PFMC,PFMO,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock type equations (average-of-configuration open-shell Dirac-Hartree-Fock formalism).
USE matrix_tools ; USE metric_relativistic
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMCN,PDMON,PDMCO,PDMOO,PFMC,PFMO
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE COMPLEX,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDNC,FNDFDNO,FNCMTC,FNCMTO
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=PDMCN-PDMCO
FNDFDNC=NORM(PDIFF,N,'F')
WRITE(*,*)'Infinity norm of the difference D_n^c-DC_{n-1}^c =',NORM(PDIFF,N,'I')
WRITE(*,*)'Frobenius norm of the difference D_n^c-DC_{n-1}^c =',FNDFDNC
PDIFF=PDMON-PDMOO
FNDFDNO=NORM(PDIFF,N,'F')
WRITE(*,*)'Infinity norm of the difference D_n^o-DC_{n-1}^o =',NORM(PDIFF,N,'I')
WRITE(*,*)'Frobenius norm of the difference D_n^o-DC_{n-1}^o =',FNDFDNO
IF ((FNDFDNC<=TRSHLD).AND.(FNDFDNO<=TRSHLD)) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMC,PDMCN,PS,N),ISRS))
FNCMTC=NORM(CMT,N,'F')
WRITE(*,*)'Infinity norm of the commutator [F(D_n^c),D_n^c] =',NORM(CMT,N,'I')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^c),D_n^c] =',FNCMTC
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMO,PDMON,PS,N),ISRS))
FNCMTO=NORM(CMT,N,'F')
WRITE(*,*)'Infinity norm of the commutator [F(D_n^o),D_n^o] =',NORM(CMT,N,'I')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^o),D_n^o] =',FNCMTO
IF ((FNCMTC<=TRSHLD).AND.(FNCMTO<=TRSHLD)) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_AOCOSDHF
END MODULE
MODULE graphics_tools
INTERFACE DENSITY_POINTWISE_VALUE
MODULE PROCEDURE DENSITY_POINTWISE_VALUE_relativistic,DENSITY_POINTWISE_VALUE_nonrelativistic
END INTERFACE
INTERFACE EXPORT_DENSITY
MODULE PROCEDURE EXPORT_DENSITY_relativistic,EXPORT_DENSITY_nonrelativistic
END INTERFACE
CONTAINS
-FUNCTION DENSITY_POINTWISE_VALUE_relativistic(PDM,PHI,NBAST,POINT) RESULT(VALUE)
+FUNCTION DENSITY_POINTWISE_VALUE_relativistic(DM,PHI,NBAST,POINT) RESULT(VALUE)
! Function that computes the value of the electronic density associated to a given density matrix (only the upper triangular part of this matrix is stored in packed format) at a given point of space.
USE basis_parameters ; USE matrix_tools
IMPLICIT NONE
- DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE PRECISION :: VALUE
INTEGER :: I
DOUBLE COMPLEX,DIMENSION(NBAST,2) :: POINTWISE_VALUES
DOUBLE COMPLEX,DIMENSION(2,2) :: MATRIX
DO I=1,NBAST
POINTWISE_VALUES(I,:)=TWOSPINOR_POINTWISE_VALUE(PHI(I),POINT)
END DO
- MATRIX=MATMUL(TRANSPOSE(CONJG(POINTWISE_VALUES)),MATMUL(UNPACK(PDM,NBAST),POINTWISE_VALUES))
+ MATRIX=MATMUL(TRANSPOSE(CONJG(POINTWISE_VALUES)),MATMUL(DM,POINTWISE_VALUES))
VALUE=REAL(MATRIX(1,1)+MATRIX(2,2))
END FUNCTION DENSITY_POINTWISE_VALUE_relativistic
-FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic(PDM,PHI,NBAST,POINT) RESULT(VALUE)
+FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic(DM,PHI,NBAST,POINT) RESULT(VALUE)
! Function that computes the value of the electronic density associated to a given density matrix (only the upper triangular part of this matrix is stored in packed format) at a given point of space.
USE basis_parameters ; USE matrix_tools
IMPLICIT NONE
- DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE PRECISION :: VALUE
INTEGER :: I
REAL(KIND=C_DOUBLE),DIMENSION(NBAST) :: POINTWISE_VALUES
DO I=1,NBAST
POINTWISE_VALUES(I)=GBF_POINTWISE_VALUE(PHI(I),POINT)
END DO
- VALUE=DOT_PRODUCT(POINTWISE_VALUES,MATMUL(UNPACK(PDM,NBAST),POINTWISE_VALUES))
+ VALUE=DOT_PRODUCT(POINTWISE_VALUES,MATMUL(DM,POINTWISE_VALUES))
END FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic
-SUBROUTINE EXPORT_DENSITY_relativistic(PDM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
+SUBROUTINE EXPORT_DENSITY_relativistic(DM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
USE basis_parameters ; USE data_parameters ; USE matrices
IMPLICIT NONE
- DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST,NPOINTS
DOUBLE PRECISION,INTENT(IN) :: RMIN,RMAX
CHARACTER(*),INTENT(IN) :: FILENAME
CHARACTER(*),INTENT(IN) :: FILEFORMAT
INTEGER :: I,J,K
DOUBLE PRECISION :: GRID_STEPSIZE
DOUBLE PRECISION,DIMENSION(3) :: X
IF (NPOINTS/=1) THEN
GRID_STEPSIZE=(RMAX-RMIN)/(NPOINTS-1)
ELSE
STOP
END IF
IF ((FILEFORMAT=='matlab').OR.(FILEFORMAT=='MATLAB')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME)
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
- WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
+ WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
ELSE IF ((FILEFORMAT=='cube').OR.(FILEFORMAT=='CUBE')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME//'.cube')
WRITE(42,*)'CUBE FILE.'
WRITE(42,*)'OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z'
WRITE(42,*)NBN,RMIN,RMIN,RMIN
WRITE(42,*)NPOINTS,(RMAX-RMIN)/NPOINTS,0.D0,0.D0
WRITE(42,*)NPOINTS,0.D0,(RMAX-RMIN)/NPOINTS,0.D0
WRITE(42,*)NPOINTS,0.D0,0.D0,(RMAX-RMIN)/NPOINTS
DO I=1,NBN
WRITE(42,*)Z(I),0.D0,CENTER(:,I)
END DO
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
- WRITE(42,*)DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
+ WRITE(42,*)DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
END IF
END SUBROUTINE EXPORT_DENSITY_relativistic
-SUBROUTINE EXPORT_DENSITY_nonrelativistic(PDM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
+SUBROUTINE EXPORT_DENSITY_nonrelativistic(DM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
USE basis_parameters ; USE data_parameters ; USE matrices
IMPLICIT NONE
- DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: DM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST,NPOINTS
DOUBLE PRECISION,INTENT(IN) :: RMIN,RMAX
CHARACTER(*),INTENT(IN) :: FILENAME
CHARACTER(*),INTENT(IN) :: FILEFORMAT
INTEGER :: I,J,K
DOUBLE PRECISION :: GRID_STEPSIZE
DOUBLE PRECISION,DIMENSION(3) :: X
IF (NPOINTS/=1) THEN
GRID_STEPSIZE=(RMAX-RMIN)/(NPOINTS-1)
ELSE
STOP
END IF
IF ((FILEFORMAT=='matlab').OR.(FILEFORMAT=='MATLAB')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME)
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
- WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
+ WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
ELSE IF ((FILEFORMAT=='cube').OR.(FILEFORMAT=='CUBE')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME//'.cube')
WRITE(42,*)'CUBE FILE.'
WRITE(42,*)'OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z'
WRITE(42,*)NBN,RMIN,RMIN,RMIN
WRITE(42,*)NPOINTS,(RMAX-RMIN)/NPOINTS,0.D0,0.D0
WRITE(42,*)NPOINTS,0.D0,(RMAX-RMIN)/NPOINTS,0.D0
WRITE(42,*)NPOINTS,0.D0,0.D0,(RMAX-RMIN)/NPOINTS
DO I=1,NBN
WRITE(42,*)Z(I),0.D0,CENTER(:,I)
END DO
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
- WRITE(42,*)DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
+ WRITE(42,*)DENSITY_POINTWISE_VALUE(DM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
END IF
END SUBROUTINE EXPORT_DENSITY_nonrelativistic
END MODULE
MODULE output
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ALL_EIG
INTERFACE OUTPUT_ITER
MODULE PROCEDURE OUTPUT_ITER_nonrelativistic,OUTPUT_ITER_relativistic
END INTERFACE OUTPUT_ITER
INTERFACE OUTPUT_FINALIZE
MODULE PROCEDURE OUTPUT_FINALIZE_nonrelativistic,OUTPUT_FINALIZE_relativistic
END INTERFACE OUTPUT_FINALIZE
CONTAINS
SUBROUTINE OUTPUT_ITER_relativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE scf_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
IF (ITER==1) ALLOCATE(ALL_EIG(NBAST,MAXITR))
ALL_EIG(:,ITER)=EIG
END SUBROUTINE OUTPUT_ITER_relativistic
SUBROUTINE OUTPUT_ITER_nonrelativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE scf_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
IF (ITER==1) ALLOCATE(ALL_EIG(NBAST,MAXITR))
ALL_EIG(:,ITER)=EIG
END SUBROUTINE OUTPUT_ITER_nonrelativistic
SUBROUTINE OUTPUT_FINALIZE_relativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
- USE basis_parameters ; USE graphics_tools
+ USE basis_parameters ; USE graphics_tools ; USE matrix_tools
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
OPEN(42,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,ITER
WRITE(42,*)ALL_EIG(:,I)
END DO
CLOSE(42)
DEALLOCATE(ALL_EIG)
- CALL EXPORT_DENSITY(PDM,PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
+ CALL EXPORT_DENSITY(UNPACK(PDM,NBAST),PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
END SUBROUTINE OUTPUT_FINALIZE_relativistic
SUBROUTINE OUTPUT_FINALIZE_nonrelativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
- USE basis_parameters ; USE graphics_tools
+ USE basis_parameters ; USE graphics_tools ; USE matrix_tools
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
OPEN(42,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,ITER
WRITE(42,*)ALL_EIG(:,I)
END DO
CLOSE(42)
DEALLOCATE(ALL_EIG)
- CALL EXPORT_DENSITY(PDM,PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
+ CALL EXPORT_DENSITY(UNPACK(PDM,NBAST),PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
END SUBROUTINE OUTPUT_FINALIZE_nonrelativistic
END MODULE output
|
antoine-levitt/ACCQUAREL
|
36a071f419b7e3b96f0c634398cba9c0c9dd5b70
|
Fix bug in BUILD_BLOCK_DIAGONAL
|
diff --git a/src/tools.f90 b/src/tools.f90
index c6d74a3..d20e968 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -423,595 +423,596 @@ FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_real
FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_complex
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
SUBROUTINE NORM_check_norm(CHAR)
CHARACTER(1),INTENT(IN) :: CHAR
IF((CHAR /= 'F') .AND. &
&(CHAR /= 'I') .AND. &
&(CHAR /= '1') .AND. &
&(CHAR /= 'M')) THEN
WRITE(*,*) 'Invalid norm'
STOP
END IF
END SUBROUTINE NORM_check_norm
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
CALL NORM_check_norm(CHAR)
NORM = DLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
CALL NORM_check_norm(CHAR)
NORM = ZLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
CALL NORM_check_norm(CHAR)
NORM = DLANSP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
CALL NORM_check_norm(CHAR)
NORM = ZLANHP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
SUBROUTINE PRINTMATRIX_real(MAT,N,LOGUNIT)
INTEGER,INTENT(IN) :: N,LOGUNIT
INTEGER :: I
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: MAT
DO I=1,N
WRITE(LOGUNIT,*) MAT(I,:)
END DO
END SUBROUTINE PRINTMATRIX_real
SUBROUTINE PRINTMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG
INTEGER :: I
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: MAT
DO I=1,N
IF(LOGUNIT_REAL == LOGUNIT_IMAG) THEN
WRITE(LOGUNIT_REAL,*) MAT(I,:)
ELSE
WRITE(LOGUNIT_REAL,*) REAL(MAT(I,:))
WRITE(LOGUNIT_IMAG,*) AIMAG(MAT(I,:))
END IF
END DO
END SUBROUTINE PRINTMATRIX_complex
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
CALL PRINTMATRIX_real(UNPACK(PMAT,N),N,LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
CALL PRINTMATRIX_complex(UNPACK(PMAT,N),N,LOGUNIT_REAL,LOGUNIT_IMAG)
END SUBROUTINE PRINTMATRIX_hermitian
SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric(PB,PA,N)
! Builds B as [A 0;0 A], A is of size N
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION, DIMENSION(N*2*(N*2+1)/2),INTENT(OUT) :: PB
DOUBLE PRECISION, DIMENSION(2*N,2*N) :: B
+ B = 0
B(1:N,1:N) = UNPACK(PA,N)
B(N+1:2*N,N+1:2*N) = B(1:N,1:N)
PB = PACK(B,2*N)
END SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric
END MODULE matrix_tools
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
IMPLICIT NONE
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
09d121ca18e3a61508462f54b2047b6265b8b7f2
|
Allow null matrix
|
diff --git a/src/expokit.f b/src/expokit.f
index b81fa45..7145d98 100644
--- a/src/expokit.f
+++ b/src/expokit.f
@@ -1,1532 +1,1528 @@
* EXPOKIT, used under a free license, http://www.maths.uq.edu.au/expokit/
*----------------------------------------------------------------------|
subroutine DMEXPV( n, m, t, v, w, tol, anorm,
. wsp,lwsp, iwsp,liwsp, matvec, itrace,iflag )
implicit none
integer n, m, lwsp, liwsp, itrace, iflag, iwsp(liwsp)
double precision t, tol, anorm, v(n), w(n), wsp(lwsp)
external matvec
*-----Purpose----------------------------------------------------------|
*
*--- DMEXPV computes w = exp(t*A)*v - Customised for MARKOV CHAINS.
*
* It does not compute the matrix exponential in isolation but
* instead, it computes directly the action of the exponential
* operator on the operand vector. This way of doing so allows
* for addressing large sparse problems.
*
* The method used is based on Krylov subspace projection
* techniques and the matrix under consideration interacts only
* via the external routine `matvec' performing the matrix-vector
* product (matrix-free method).
*
* This is a customised version for Markov Chains. This means that a
* check is done within this code to ensure that the resulting vector
* w is a probability vector, i.e., w must have all its components
* in [0,1], with sum equal to 1. This check is done at some expense
* and the user may try DGEXPV which is cheaper since it ignores
* probability constraints.
*
* IMPORTANT: The check assumes that the transition rate matrix Q
* satisfies Qe = 0, where e=(1,...,1)'. Don't use DMEXPV
* if this condition does not hold. Use DGEXPV instead.
* DMEXPV/DGEXPV require the matrix-vector product
* y = A*x = Q'*x, i.e, the TRANSPOSE of Q times a vector.
* Failure to remember this leads to wrong results.
*
*-----Arguments--------------------------------------------------------|
*
* n : (input) order of the principal matrix A.
*
* m : (input) maximum size for the Krylov basis.
*
* t : (input) time at wich the solution is needed (can be < 0).
*
* v(n) : (input) given operand vector.
*
* w(n) : (output) computed approximation of exp(t*A)*v.
*
* tol : (input/output) the requested acurracy tolerance on w.
* If on input tol=0.0d0 or tol is too small (tol.le.eps)
* the internal value sqrt(eps) is used, and tol is set to
* sqrt(eps) on output (`eps' denotes the machine epsilon).
* (`Happy breakdown' is assumed if h(j+1,j) .le. anorm*tol)
*
* anorm : (input) an approximation of some norm of A.
*
* wsp(lwsp): (workspace) lwsp .ge. n*(m+1)+n+(m+2)^2+4*(m+2)^2+ideg+1
* +---------+-------+---------------+
* (actually, ideg=6) V H wsp for PADE
*
* iwsp(liwsp): (workspace) liwsp .ge. m+2
*
* matvec : external subroutine for matrix-vector multiplication.
* synopsis: matvec( x, y )
* double precision x(*), y(*)
* computes: y(1:n) <- A*x(1:n)
* where A is the principal matrix.
*
* IMPORTANT: DMEXPV requires the product y = Ax = Q'x, i.e.
* the TRANSPOSE of the transition rate matrix.
*
* itrace : (input) running mode. 0=silent, 1=print step-by-step info
*
* iflag : (output) exit flag.
* <0 - bad input arguments
* 0 - no problem
* 1 - maximum number of steps reached without convergence
* 2 - requested tolerance was too high
*
*-----Accounts on the computation--------------------------------------|
* Upon exit, an interested user may retrieve accounts on the
* computations. They are located in the workspace arrays wsp and
* iwsp as indicated below:
*
* location mnemonic description
* -----------------------------------------------------------------|
* iwsp(1) = nmult, number of matrix-vector multiplications used
* iwsp(2) = nexph, number of Hessenberg matrix exponential evaluated
* iwsp(3) = nscale, number of repeated squaring involved in Pade
* iwsp(4) = nstep, number of integration steps used up to completion
* iwsp(5) = nreject, number of rejected step-sizes
* iwsp(6) = ibrkflag, set to 1 if `happy breakdown' and 0 otherwise
* iwsp(7) = mbrkdwn, if `happy brkdown', basis-size when it occured
* -----------------------------------------------------------------|
* wsp(1) = step_min, minimum step-size used during integration
* wsp(2) = step_max, maximum step-size used during integration
* wsp(3) = x_round, maximum among all roundoff errors (lower bound)
* wsp(4) = s_round, sum of roundoff errors (lower bound)
* wsp(5) = x_error, maximum among all local truncation errors
* wsp(6) = s_error, global sum of local truncation errors
* wsp(7) = tbrkdwn, if `happy breakdown', time when it occured
* wsp(8) = t_now, integration domain successfully covered
* wsp(9) = hump, i.e., max||exp(sA)||, s in [0,t] (or [t,0] if t<0)
* wsp(10) = ||w||/||v||, scaled norm of the solution w.
* -----------------------------------------------------------------|
* The `hump' is a measure of the conditioning of the problem. The
* matrix exponential is well-conditioned if hump = 1, whereas it is
* poorly-conditioned if hump >> 1. However the solution can still be
* relatively fairly accurate even when the hump is large (the hump
* is an upper bound), especially when the hump and the scaled norm
* of w [this is also computed and returned in wsp(10)] are of the
* same order of magnitude (further details in reference below).
* Markov chains are usually well-conditioned problems.
*
*----------------------------------------------------------------------|
*-----The following parameters may also be adjusted herein-------------|
*
integer mxstep, mxreject, ideg
double precision delta, gamma
parameter( mxstep = 500,
. mxreject = 0,
. ideg = 6,
. delta = 1.2d0,
. gamma = 0.9d0 )
* mxstep : maximum allowable number of integration steps.
* The value 0 means an infinite number of steps.
*
* mxreject: maximum allowable number of rejections at each step.
* The value 0 means an infinite number of rejections.
*
* ideg : the Pade approximation of type (ideg,ideg) is used as
* an approximation to exp(H). The value 0 switches to the
* uniform rational Chebyshev approximation of type (14,14)
*
* delta : local truncation error `safety factor'
*
* gamma : stepsize `shrinking factor'
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer i, j, k1, mh, mx, iv, ih, j1v, ns, ifree, lfree, iexph,
. ireject,ibrkflag,mbrkdwn, nmult, nreject, nexph, nscale,
. nstep
double precision sgn, t_out, tbrkdwn, step_min,step_max, err_loc,
. s_error, x_error, t_now, t_new, t_step, t_old,
. xm, beta, break_tol, p1, p2, p3, eps, rndoff,
. vnorm, avnorm, hj1j, hij, hump, SQR1,
. roundoff, s_round, x_round
intrinsic AINT,ABS,DBLE,LOG10,MAX,MIN,NINT,SIGN,SQRT
double precision DDOT, DNRM2, DASUM
*--- check restrictions on input parameters ...
iflag = 0
if ( lwsp.lt.n*(m+2)+5*(m+2)**2+ideg+1 ) iflag = -1
if ( liwsp.lt.m+2 ) iflag = -2
if ( m.ge.n .or. m.le.0 ) iflag = -3
if ( iflag.ne.0 ) stop 'bad sizes (in input of DMEXPV)'
*
*--- initialisations ...
*
k1 = 2
mh = m + 2
iv = 1
ih = iv + n*(m+1) + n
ifree = ih + mh*mh
lfree = lwsp - ifree + 1
ibrkflag = 0
mbrkdwn = m
nmult = 0
nreject = 0
nexph = 0
nscale = 0
sgn = SIGN( 1.0d0,t )
t_out = ABS( t )
tbrkdwn = 0.0d0
step_min = t_out
step_max = 0.0d0
nstep = 0
s_error = 0.0d0
s_round = 0.0d0
x_error = 0.0d0
x_round = 0.0d0
t_now = 0.0d0
t_new = 0.0d0
p1 = 4.0d0/3.0d0
1 p2 = p1 - 1.0d0
p3 = p2 + p2 + p2
eps = ABS( p3-1.0d0 )
if ( eps.eq.0.0d0 ) go to 1
if ( tol.le.eps ) tol = SQRT( eps )
rndoff = eps*anorm
break_tol = 1.0d-7
*>>> break_tol = tol
*>>> break_tol = anorm*tol
call DCOPY( n, v,1, w,1 )
beta = DNRM2( n, w,1 )
vnorm = beta
hump = beta
*
*--- obtain the very first stepsize ...
*
SQR1 = SQRT( 0.1d0 )
xm = 1.0d0/DBLE( m )
p1 = tol*(((m+1)/2.72D0)**(m+1))*SQRT(2.0D0*3.14D0*(m+1))
t_new = (1.0d0/anorm)*(p1/(4.0d0*beta*anorm))**xm
p1 = 10.0d0**(NINT( LOG10( t_new )-SQR1 )-1)
t_new = AINT( t_new/p1 + 0.55d0 ) * p1
*
*--- step-by-step integration ...
*
100 if ( t_now.ge.t_out ) goto 500
nstep = nstep + 1
t_step = MIN( t_out-t_now, t_new )
p1 = 1.0d0/beta
do i = 1,n
wsp(iv + i-1) = p1*w(i)
enddo
do i = 1,mh*mh
wsp(ih+i-1) = 0.0d0
enddo
*
*--- Arnoldi loop ...
*
j1v = iv + n
do 200 j = 1,m
nmult = nmult + 1
call matvec( wsp(j1v-n), wsp(j1v) )
do i = 1,j
hij = DDOT( n, wsp(iv+(i-1)*n),1, wsp(j1v),1 )
call DAXPY( n, -hij, wsp(iv+(i-1)*n),1, wsp(j1v),1 )
wsp(ih+(j-1)*mh+i-1) = hij
enddo
hj1j = DNRM2( n, wsp(j1v),1 )
*--- if `happy breakdown' go straightforward at the end ...
if ( hj1j.le.break_tol ) then
print*,'happy breakdown: mbrkdwn =',j,' h =',hj1j
k1 = 0
ibrkflag = 1
mbrkdwn = j
tbrkdwn = t_now
t_step = t_out-t_now
goto 300
endif
wsp(ih+(j-1)*mh+j) = hj1j
call DSCAL( n, 1.0d0/hj1j, wsp(j1v),1 )
j1v = j1v + n
200 continue
nmult = nmult + 1
call matvec( wsp(j1v-n), wsp(j1v) )
avnorm = DNRM2( n, wsp(j1v),1 )
*
*--- set 1 for the 2-corrected scheme ...
*
300 continue
wsp(ih+m*mh+m+1) = 1.0d0
*
*--- loop while ireject<mxreject until the tolerance is reached ...
*
ireject = 0
401 continue
*
*--- compute w = beta*V*exp(t_step*H)*e1 ..
*
nexph = nexph + 1
mx = mbrkdwn + k1
if ( ideg.ne.0 ) then
*--- irreducible rational Pade approximation ...
call DGPADM( ideg, mx, sgn*t_step, wsp(ih),mh,
. wsp(ifree),lfree, iwsp, iexph, ns, iflag )
iexph = ifree + iexph - 1
nscale = nscale + ns
else
*--- uniform rational Chebyshev approximation ...
iexph = ifree
do i = 1,mx
wsp(iexph+i-1) = 0.0d0
enddo
wsp(iexph) = 1.0d0
call DNCHBV(mx,sgn*t_step,wsp(ih),mh,wsp(iexph),wsp(ifree+mx))
endif
402 continue
*
*--- error estimate ...
*
if ( k1.eq.0 ) then
err_loc = tol
else
p1 = ABS( wsp(iexph+m) ) * beta
p2 = ABS( wsp(iexph+m+1) ) * beta * avnorm
if ( p1.gt.10.0d0*p2 ) then
err_loc = p2
xm = 1.0d0/DBLE( m )
elseif ( p1.gt.p2 ) then
err_loc = (p1*p2)/(p1-p2)
xm = 1.0d0/DBLE( m )
else
err_loc = p1
xm = 1.0d0/DBLE( m-1 )
endif
endif
*
*--- reject the step-size if the error is not acceptable ...
*
if ( (k1.ne.0) .and. (err_loc.gt.delta*t_step*tol) .and.
. (mxreject.eq.0 .or. ireject.lt.mxreject) ) then
t_old = t_step
t_step = gamma * t_step * (t_step*tol/err_loc)**xm
p1 = 10.0d0**(NINT( LOG10( t_step )-SQR1 )-1)
t_step = AINT( t_step/p1 + 0.55d0 ) * p1
if ( itrace.ne.0 ) then
print*,'t_step =',t_old
print*,'err_loc =',err_loc
print*,'err_required =',delta*t_old*tol
print*,'stepsize rejected, stepping down to:',t_step
endif
ireject = ireject + 1
nreject = nreject + 1
if ( mxreject.ne.0 .and. ireject.gt.mxreject ) then
print*,"Failure in DMEXPV: ---"
print*,"The requested tolerance is too high."
Print*,"Rerun with a smaller value."
iflag = 2
return
endif
goto 401
endif
*
*--- now update w = beta*V*exp(t_step*H)*e1 and the hump ...
*
mx = mbrkdwn + MAX( 0,k1-1 )
call DGEMV( 'n', n,mx,beta,wsp(iv),n,wsp(iexph),1,0.0d0,w,1 )
beta = DNRM2( n, w,1 )
hump = MAX( hump, beta )
*
*--- Markov model constraints ...
*
j = 0
do i = 1,n
if ( w(i).lt.0.0d0 ) then
w(i) = 0.0d0
j = j + 1
endif
enddo
p1 = DASUM( n, w,1 )
if ( j.gt.0 ) call DSCAL( n, 1.0d0/p1, w,1 )
roundoff = DABS( 1.0d0-p1 ) / DBLE( n )
*
*--- suggested value for the next stepsize ...
*
t_new = gamma * t_step * (t_step*tol/err_loc)**xm
p1 = 10.0d0**(NINT( LOG10( t_new )-SQR1 )-1)
t_new = AINT( t_new/p1 + 0.55d0 ) * p1
err_loc = MAX( err_loc, roundoff )
err_loc = MAX( err_loc, rndoff )
*
*--- update the time covered ...
*
t_now = t_now + t_step
*
*--- display and keep some information ...
*
if ( itrace.ne.0 ) then
print*,'integration',nstep,'---------------------------------'
print*,'scale-square =',ns
print*,'wnorm =',beta
print*,'step_size =',t_step
print*,'err_loc =',err_loc
print*,'roundoff =',roundoff
print*,'next_step =',t_new
endif
step_min = MIN( step_min, t_step )
step_max = MAX( step_max, t_step )
s_error = s_error + err_loc
s_round = s_round + roundoff
x_error = MAX( x_error, err_loc )
x_round = MAX( x_round, roundoff )
if ( mxstep.eq.0 .or. nstep.lt.mxstep ) goto 100
iflag = 1
500 continue
iwsp(1) = nmult
iwsp(2) = nexph
iwsp(3) = nscale
iwsp(4) = nstep
iwsp(5) = nreject
iwsp(6) = ibrkflag
iwsp(7) = mbrkdwn
wsp(1) = step_min
wsp(2) = step_max
wsp(3) = x_round
wsp(4) = s_round
wsp(5) = x_error
wsp(6) = s_error
wsp(7) = tbrkdwn
wsp(8) = sgn*t_now
wsp(9) = hump/vnorm
wsp(10) = beta/vnorm
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine DGPADM( ideg,m,t,H,ldh,wsp,lwsp,ipiv,iexph,ns,iflag )
implicit none
integer ideg, m, ldh, lwsp, iexph, ns, iflag, ipiv(m)
double precision t, H(ldh,m), wsp(lwsp)
*-----Purpose----------------------------------------------------------|
*
* Computes exp(t*H), the matrix exponential of a general matrix in
* full, using the irreducible rational Pade approximation to the
* exponential function exp(x) = r(x) = (+/-)( I + 2*(q(x)/p(x)) ),
* combined with scaling-and-squaring.
*
*-----Arguments--------------------------------------------------------|
*
* ideg : (input) the degre of the diagonal Pade to be used.
* a value of 6 is generally satisfactory.
*
* m : (input) order of H.
*
* H(ldh,m) : (input) argument matrix.
*
* t : (input) time-scale (can be < 0).
*
* wsp(lwsp) : (workspace/output) lwsp .ge. 4*m*m+ideg+1.
*
* ipiv(m) : (workspace)
*
*>>>> iexph : (output) number such that wsp(iexph) points to exp(tH)
* i.e., exp(tH) is located at wsp(iexph ... iexph+m*m-1)
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* NOTE: if the routine was called with wsp(iptr),
* then exp(tH) will start at wsp(iptr+iexph-1).
*
* ns : (output) number of scaling-squaring used.
*
* iflag : (output) exit flag.
* 0 - no problem
* <0 - problem
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer mm,i,j,k,ih2,ip,iq,iused,ifree,iodd,icoef,iput,iget
double precision hnorm,scale,scale2,cp,cq
intrinsic INT,ABS,DBLE,LOG,MAX
*--- check restrictions on input parameters ...
mm = m*m
iflag = 0
if ( ldh.lt.m ) iflag = -1
if ( lwsp.lt.4*mm+ideg+1 ) iflag = -2
if ( iflag.ne.0 ) stop 'bad sizes (in input of DGPADM)'
*
*--- initialise pointers ...
*
icoef = 1
ih2 = icoef + (ideg+1)
ip = ih2 + mm
iq = ip + mm
ifree = iq + mm
*
*--- scaling: seek ns such that ||t*H/2^ns|| < 1/2;
* and set scale = t/2^ns ...
*
do i = 1,m
wsp(i) = 0.0d0
enddo
do j = 1,m
do i = 1,m
wsp(i) = wsp(i) + ABS( H(i,j) )
enddo
enddo
hnorm = 0.0d0
do i = 1,m
hnorm = MAX( hnorm,wsp(i) )
enddo
hnorm = ABS( t*hnorm )
- if ( hnorm.eq.0.0d0 ) stop 'Error - null H in input of DGPADM.'
ns = MAX( 0,INT(LOG(hnorm)/LOG(2.0d0))+2 )
scale = t / DBLE(2**ns)
scale2 = scale*scale
*
*--- compute Pade coefficients ...
*
i = ideg+1
j = 2*ideg+1
wsp(icoef) = 1.0d0
do k = 1,ideg
wsp(icoef+k) = (wsp(icoef+k-1)*DBLE( i-k ))/DBLE( k*(j-k) )
enddo
*
*--- H2 = scale2*H*H ...
*
call DGEMM( 'n','n',m,m,m,scale2,H,ldh,H,ldh,0.0d0,wsp(ih2),m )
*
*--- initialize p (numerator) and q (denominator) ...
*
cp = wsp(icoef+ideg-1)
cq = wsp(icoef+ideg)
do j = 1,m
do i = 1,m
wsp(ip + (j-1)*m + i-1) = 0.0d0
wsp(iq + (j-1)*m + i-1) = 0.0d0
enddo
wsp(ip + (j-1)*(m+1)) = cp
wsp(iq + (j-1)*(m+1)) = cq
enddo
*
*--- Apply Horner rule ...
*
iodd = 1
k = ideg - 1
100 continue
iused = iodd*iq + (1-iodd)*ip
call DGEMM( 'n','n',m,m,m, 1.0d0,wsp(iused),m,
. wsp(ih2),m, 0.0d0,wsp(ifree),m )
do j = 1,m
wsp(ifree+(j-1)*(m+1)) = wsp(ifree+(j-1)*(m+1))+wsp(icoef+k-1)
enddo
ip = (1-iodd)*ifree + iodd*ip
iq = iodd*ifree + (1-iodd)*iq
ifree = iused
iodd = 1-iodd
k = k-1
if ( k.gt.0 ) goto 100
*
*--- Obtain (+/-)(I + 2*(p\q)) ...
*
if ( iodd .eq. 1 ) then
call DGEMM( 'n','n',m,m,m, scale,wsp(iq),m,
. H,ldh, 0.0d0,wsp(ifree),m )
iq = ifree
else
call DGEMM( 'n','n',m,m,m, scale,wsp(ip),m,
. H,ldh, 0.0d0,wsp(ifree),m )
ip = ifree
endif
call DAXPY( mm, -1.0d0,wsp(ip),1, wsp(iq),1 )
call DGESV( m,m, wsp(iq),m, ipiv, wsp(ip),m, iflag )
if ( iflag.ne.0 ) stop 'Problem in DGESV (within DGPADM)'
call DSCAL( mm, 2.0d0, wsp(ip), 1 )
do j = 1,m
wsp(ip+(j-1)*(m+1)) = wsp(ip+(j-1)*(m+1)) + 1.0d0
enddo
iput = ip
if ( ns.eq.0 .and. iodd.eq.1 ) then
call DSCAL( mm, -1.0d0, wsp(ip), 1 )
goto 200
endif
*
*-- squaring : exp(t*H) = (exp(t*H))^(2^ns) ...
*
iodd = 1
do k = 1,ns
iget = iodd*ip + (1-iodd)*iq
iput = (1-iodd)*ip + iodd*iq
call DGEMM( 'n','n',m,m,m, 1.0d0,wsp(iget),m, wsp(iget),m,
. 0.0d0,wsp(iput),m )
iodd = 1-iodd
enddo
200 continue
iexph = iput
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine DSPADM( ideg,m,t,H,ldh,wsp,lwsp,ipiv,iexph,ns,iflag )
implicit none
integer ideg, m, ldh, lwsp, iexph, ns, iflag, ipiv(m)
double precision t, H(ldh,m), wsp(lwsp)
*-----Purpose----------------------------------------------------------|
*
* Computes exp(t*H), the matrix exponential of a symmetric matrix
* in full, using the irreducible rational Pade approximation to the
* exponential function exp(x) = r(x) = (+/-)( I + 2*(q(x)/p(x)) ),
* combined with scaling-and-squaring.
*
*-----Arguments--------------------------------------------------------|
*
* ideg : (input) the degre of the diagonal Pade to be used.
* a value of 6 is generally satisfactory.
*
* m : (input) order of H.
*
* H(ldh,m) : (input) argument matrix (both lower and upper parts).
*
* t : (input) time-scale (can be < 0).
*
* wsp(lwsp) : (workspace/output) lwsp .ge. 4*m*m+ideg+1.
*
* ipiv(m) : (workspace)
*
*>>>> iexph : (output) number such that wsp(iexph) points to exp(tH)
* i.e., exp(tH) is located at wsp(iexph ... iexph+m*m-1)
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* NOTE: if the routine was called with wsp(iptr),
* then exp(tH) will start at wsp(iptr+iexph-1).
*
* ns : (output) number of scaling-squaring used.
*
* iflag : (output) exit flag.
* 0 - no problem
* <0 - problem
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer mm,i,j,k,ih2,ip,iq,iused,ifree,iodd,icoef,iput,iget
double precision hnorm,scale,scale2,cp,cq
intrinsic INT,ABS,DBLE,LOG,MAX
*--- check restrictions on input parameters ...
mm = m*m
iflag = 0
if ( ldh.lt.m ) iflag = -1
if ( lwsp.lt.4*mm+ideg+1 ) iflag = -2
if ( iflag.ne.0 ) stop 'bad sizes (in input of DSPADM)'
*
*--- initialise pointers ...
*
icoef = 1
ih2 = icoef + (ideg+1)
ip = ih2 + mm
iq = ip + mm
ifree = iq + mm
*
*--- scaling: seek ns such that ||t*H/2^ns|| < 1/2;
* and set scale = t/2^ns ...
*
do i = 1,m
wsp(i) = 0.0d0
enddo
do j = 1,m
do i = 1,m
wsp(i) = wsp(i) + ABS( H(i,j) )
enddo
enddo
hnorm = 0.0d0
do i = 1,m
hnorm = MAX( hnorm,wsp(i) )
enddo
hnorm = ABS( t*hnorm )
- if ( hnorm.eq.0.0d0 ) stop 'Error - null H in input of DSPADM.'
ns = MAX( 0,INT(LOG(hnorm)/LOG(2.0d0))+2 )
scale = t / DBLE(2**ns)
scale2 = scale*scale
*
*--- compute Pade coefficients ...
*
i = ideg+1
j = 2*ideg+1
wsp(icoef) = 1.0d0
do k = 1,ideg
wsp(icoef+k) = (wsp(icoef+k-1)*DBLE( i-k ))/DBLE( k*(j-k) )
enddo
*
*--- H2 = scale2*H*H ...
*
call DGEMM( 'n','n',m,m,m,scale2,H,ldh,H,ldh,0.0d0,wsp(ih2),m )
*
*--- initialize p (numerator) and q (denominator) ...
*
cp = wsp(icoef+ideg-1)
cq = wsp(icoef+ideg)
do j = 1,m
do i = 1,m
wsp(ip + (j-1)*m + i-1) = 0.0d0
wsp(iq + (j-1)*m + i-1) = 0.0d0
enddo
wsp(ip + (j-1)*(m+1)) = cp
wsp(iq + (j-1)*(m+1)) = cq
enddo
*
*--- Apply Horner rule ...
*
iodd = 1
k = ideg - 1
100 continue
iused = iodd*iq + (1-iodd)*ip
call DGEMM( 'n','n',m,m,m, 1.0d0,wsp(iused),m,
. wsp(ih2),m, 0.0d0,wsp(ifree),m )
do j = 1,m
wsp(ifree+(j-1)*(m+1)) = wsp(ifree+(j-1)*(m+1))+wsp(icoef+k-1)
enddo
ip = (1-iodd)*ifree + iodd*ip
iq = iodd*ifree + (1-iodd)*iq
ifree = iused
iodd = 1-iodd
k = k-1
if ( k.gt.0 ) goto 100
*
*--- Obtain (+/-)(I + 2*(p\q)) ...
*
if ( iodd .eq. 1 ) then
call DGEMM( 'n','n',m,m,m, scale,wsp(iq),m,
. H,ldh, 0.0d0,wsp(ifree),m )
iq = ifree
else
call DGEMM( 'n','n',m,m,m, scale,wsp(ip),m,
. H,ldh, 0.0d0,wsp(ifree),m )
ip = ifree
endif
call DAXPY( mm, -1.0d0,wsp(ip),1, wsp(iq),1 )
call DSYSV( 'U',m,m,wsp(iq),m,ipiv,wsp(ip),m,wsp(ih2),mm,iflag )
if ( iflag.ne.0 ) stop 'Problem in DSYSV (within DSPADM)'
call DSCAL( mm, 2.0d0, wsp(ip), 1 )
do j = 1,m
wsp(ip+(j-1)*(m+1)) = wsp(ip+(j-1)*(m+1)) + 1.0d0
enddo
iput = ip
if ( ns.eq.0 .and. iodd.eq.1 ) then
call DSCAL( mm, -1.0d0, wsp(ip), 1 )
goto 200
endif
*
*-- squaring : exp(t*H) = (exp(t*H))^(2^ns) ...
*
iodd = 1
do k = 1,ns
iget = iodd*ip + (1-iodd)*iq
iput = (1-iodd)*ip + iodd*iq
call DGEMM( 'n','n',m,m,m, 1.0d0,wsp(iget),m, wsp(iget),m,
. 0.0d0,wsp(iput),m )
iodd = 1-iodd
enddo
200 continue
iexph = iput
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine ZGPADM(ideg,m,t,H,ldh,wsp,lwsp,ipiv,iexph,ns,iflag)
implicit none
double precision t
integer ideg, m, ldh, lwsp, iexph, ns, iflag, ipiv(m)
complex*16 H(ldh,m), wsp(lwsp)
*-----Purpose----------------------------------------------------------|
*
* Computes exp(t*H), the matrix exponential of a general complex
* matrix in full, using the irreducible rational Pade approximation
* to the exponential exp(z) = r(z) = (+/-)( I + 2*(q(z)/p(z)) ),
* combined with scaling-and-squaring.
*
*-----Arguments--------------------------------------------------------|
*
* ideg : (input) the degre of the diagonal Pade to be used.
* a value of 6 is generally satisfactory.
*
* m : (input) order of H.
*
* H(ldh,m) : (input) argument matrix.
*
* t : (input) time-scale (can be < 0).
*
* wsp(lwsp) : (workspace/output) lwsp .ge. 4*m*m+ideg+1.
*
* ipiv(m) : (workspace)
*
*>>>> iexph : (output) number such that wsp(iexph) points to exp(tH)
* i.e., exp(tH) is located at wsp(iexph ... iexph+m*m-1)
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* NOTE: if the routine was called with wsp(iptr),
* then exp(tH) will start at wsp(iptr+iexph-1).
*
* ns : (output) number of scaling-squaring used.
*
* iflag : (output) exit flag.
* 0 - no problem
* <0 - problem
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer i,j,k,icoef,mm,ih2,iodd,iused,ifree,iq,ip,iput,iget
double precision hnorm
complex*16 cp, cq, scale, scale2, ZERO, ONE
parameter( ZERO=(0.0d0,0.0d0), ONE=(1.0d0,0.0d0) )
intrinsic ABS, CMPLX, DBLE, INT, LOG, MAX
*--- check restrictions on input parameters ...
mm = m*m
iflag = 0
if ( ldh.lt.m ) iflag = -1
if ( lwsp.lt.4*mm+ideg+1 ) iflag = -2
if ( iflag.ne.0 ) stop 'bad sizes (in input of ZGPADM)'
*
*--- initialise pointers ...
*
icoef = 1
ih2 = icoef + (ideg+1)
ip = ih2 + mm
iq = ip + mm
ifree = iq + mm
*
*--- scaling: seek ns such that ||t*H/2^ns|| < 1/2;
* and set scale = t/2^ns ...
*
do i = 1,m
wsp(i) = ZERO
enddo
do j = 1,m
do i = 1,m
wsp(i) = wsp(i) + ABS( H(i,j) )
enddo
enddo
hnorm = 0.0d0
do i = 1,m
hnorm = MAX( hnorm,DBLE(wsp(i)) )
enddo
hnorm = ABS( t*hnorm )
- if ( hnorm.eq.0.0d0 ) stop 'Error - null H in input of ZGPADM.'
ns = MAX( 0,INT(LOG(hnorm)/LOG(2.0d0))+2 )
scale = CMPLX( t/DBLE(2**ns),0.0d0 )
scale2 = scale*scale
*
*--- compute Pade coefficients ...
*
i = ideg+1
j = 2*ideg+1
wsp(icoef) = ONE
do k = 1,ideg
wsp(icoef+k) = (wsp(icoef+k-1)*DBLE( i-k ))/DBLE( k*(j-k) )
enddo
*
*--- H2 = scale2*H*H ...
*
call ZGEMM( 'n','n',m,m,m,scale2,H,ldh,H,ldh,ZERO,wsp(ih2),m )
*
*--- initialise p (numerator) and q (denominator) ...
*
cp = wsp(icoef+ideg-1)
cq = wsp(icoef+ideg)
do j = 1,m
do i = 1,m
wsp(ip + (j-1)*m + i-1) = ZERO
wsp(iq + (j-1)*m + i-1) = ZERO
enddo
wsp(ip + (j-1)*(m+1)) = cp
wsp(iq + (j-1)*(m+1)) = cq
enddo
*
*--- Apply Horner rule ...
*
iodd = 1
k = ideg - 1
100 continue
iused = iodd*iq + (1-iodd)*ip
call ZGEMM( 'n','n',m,m,m, ONE,wsp(iused),m,
. wsp(ih2),m, ZERO,wsp(ifree),m )
do j = 1,m
wsp(ifree+(j-1)*(m+1)) = wsp(ifree+(j-1)*(m+1))+wsp(icoef+k-1)
enddo
ip = (1-iodd)*ifree + iodd*ip
iq = iodd*ifree + (1-iodd)*iq
ifree = iused
iodd = 1-iodd
k = k-1
if ( k.gt.0 ) goto 100
*
*--- Obtain (+/-)(I + 2*(p\q)) ...
*
if ( iodd.ne.0 ) then
call ZGEMM( 'n','n',m,m,m, scale,wsp(iq),m,
. H,ldh, ZERO,wsp(ifree),m )
iq = ifree
else
call ZGEMM( 'n','n',m,m,m, scale,wsp(ip),m,
. H,ldh, ZERO,wsp(ifree),m )
ip = ifree
endif
call ZAXPY( mm, -ONE,wsp(ip),1, wsp(iq),1 )
call ZGESV( m,m, wsp(iq),m, ipiv, wsp(ip),m, iflag )
if ( iflag.ne.0 ) stop 'Problem in ZGESV (within ZGPADM)'
call ZDSCAL( mm, 2.0d0, wsp(ip), 1 )
do j = 1,m
wsp(ip+(j-1)*(m+1)) = wsp(ip+(j-1)*(m+1)) + ONE
enddo
iput = ip
if ( ns.eq.0 .and. iodd.ne.0 ) then
call ZDSCAL( mm, -1.0d0, wsp(ip), 1 )
goto 200
endif
*
*-- squaring : exp(t*H) = (exp(t*H))^(2^ns) ...
*
iodd = 1
do k = 1,ns
iget = iodd*ip + (1-iodd)*iq
iput = (1-iodd)*ip + iodd*iq
call ZGEMM( 'n','n',m,m,m, ONE,wsp(iget),m, wsp(iget),m,
. ZERO,wsp(iput),m )
iodd = 1-iodd
enddo
200 continue
iexph = iput
END
*----------------------------------------------------------------------|
subroutine ZHPADM(ideg,m,t,H,ldh,wsp,lwsp,ipiv,iexph,ns,iflag)
implicit none
double precision t
integer ideg, m, ldh, lwsp, iexph, ns, iflag, ipiv(m)
complex*16 H(ldh,m), wsp(lwsp)
*-----Purpose----------------------------------------------------------|
*
* Computes exp(t*H), the matrix exponential of an Hermitian matrix
* in full, using the irreducible rational Pade approximation to the
* exponential function exp(z) = r(z) = (+/-)( I + 2*(q(z)/p(z)) ),
* combined with scaling-and-squaring.
*
*-----Arguments--------------------------------------------------------|
*
* ideg : (input) the degre of the diagonal Pade to be used.
* a value of 6 is generally satisfactory.
*
* m : (input) order of H.
*
* H(ldh,m) : (input) argument matrix (both lower and upper parts).
*
* t : (input) time-scale (can be < 0).
*
* wsp(lwsp) : (workspace/output) lwsp .ge. 4*m*m+ideg+1.
*
* ipiv(m) : (workspace)
*
*>>>> iexph : (output) number such that wsp(iexph) points to exp(tH)
* i.e., exp(tH) is located at wsp(iexph ... iexph+m*m-1)
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* NOTE: if the routine was called with wsp(iptr),
* then exp(tH) will start at wsp(iptr+iexph-1).
*
* ns : (output) number of scaling-squaring used.
*
* iflag : (output) exit flag.
* 0 - no problem
* <0 - problem
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer i,j,k,icoef,mm,ih2,iodd,iused,ifree,iq,ip,iput,iget
double precision hnorm
complex*16 cp, cq, scale, scale2, ZERO, ONE
parameter( ZERO=(0.0d0,0.0d0), ONE=(1.0d0,0.0d0) )
intrinsic ABS, CMPLX, DBLE, INT, LOG, MAX
*--- check restrictions on input parameters ...
mm = m*m
iflag = 0
if ( ldh.lt.m ) iflag = -1
if ( lwsp.lt.4*mm+ideg+1 ) iflag = -2
if ( iflag.ne.0 ) stop 'bad sizes (in input of ZHPADM)'
*
*--- initialise pointers ...
*
icoef = 1
ih2 = icoef + (ideg+1)
ip = ih2 + mm
iq = ip + mm
ifree = iq + mm
*
*--- scaling: seek ns such that ||t*H/2^ns|| < 1/2;
* and set scale = t/2^ns ...
*
do i = 1,m
wsp(i) = ZERO
enddo
do j = 1,m
do i = 1,m
wsp(i) = wsp(i) + ABS( H(i,j) )
enddo
enddo
hnorm = 0.0d0
do i = 1,m
hnorm = MAX( hnorm,DBLE(wsp(i)) )
enddo
hnorm = ABS( t*hnorm )
- if ( hnorm.eq.0.0d0 ) stop 'Error - null H in input of ZHPADM.'
ns = MAX( 0,INT(LOG(hnorm)/LOG(2.0d0))+2 )
scale = CMPLX( t/DBLE(2**ns),0.0d0 )
scale2 = scale*scale
*
*--- compute Pade coefficients ...
*
i = ideg+1
j = 2*ideg+1
wsp(icoef) = ONE
do k = 1,ideg
wsp(icoef+k) = (wsp(icoef+k-1)*DBLE( i-k ))/DBLE( k*(j-k) )
enddo
*
*--- H2 = scale2*H*H ...
*
call ZGEMM( 'n','n',m,m,m,scale2,H,ldh,H,ldh,ZERO,wsp(ih2),m )
*
*--- initialise p (numerator) and q (denominator) ...
*
cp = wsp(icoef+ideg-1)
cq = wsp(icoef+ideg)
do j = 1,m
do i = 1,m
wsp(ip + (j-1)*m + i-1) = ZERO
wsp(iq + (j-1)*m + i-1) = ZERO
enddo
wsp(ip + (j-1)*(m+1)) = cp
wsp(iq + (j-1)*(m+1)) = cq
enddo
*
*--- Apply Horner rule ...
*
iodd = 1
k = ideg - 1
100 continue
iused = iodd*iq + (1-iodd)*ip
call ZGEMM( 'n','n',m,m,m, ONE,wsp(iused),m,
. wsp(ih2),m, ZERO,wsp(ifree),m )
do j = 1,m
wsp(ifree+(j-1)*(m+1)) = wsp(ifree+(j-1)*(m+1))+wsp(icoef+k-1)
enddo
ip = (1-iodd)*ifree + iodd*ip
iq = iodd*ifree + (1-iodd)*iq
ifree = iused
iodd = 1-iodd
k = k-1
if ( k.gt.0 ) goto 100
*
*--- Obtain (+/-)(I + 2*(p\q)) ...
*
if ( iodd.ne.0 ) then
call ZGEMM( 'n','n',m,m,m, scale,wsp(iq),m,
. H,ldh, ZERO,wsp(ifree),m )
iq = ifree
else
call ZGEMM( 'n','n',m,m,m, scale,wsp(ip),m,
. H,ldh, ZERO,wsp(ifree),m )
ip = ifree
endif
call ZAXPY( mm, -ONE,wsp(ip),1, wsp(iq),1 )
call ZHESV( 'U',m,m,wsp(iq),m,ipiv,wsp(ip),m,wsp(ih2),mm,iflag )
if ( iflag.ne.0 ) stop 'Problem in ZHESV (within ZHPADM)'
call ZDSCAL( mm, 2.0d0, wsp(ip), 1 )
do j = 1,m
wsp(ip+(j-1)*(m+1)) = wsp(ip+(j-1)*(m+1)) + ONE
enddo
iput = ip
if ( ns.eq.0 .and. iodd.ne.0 ) then
call ZDSCAL( mm, -1.0d0, wsp(ip), 1 )
goto 200
endif
*
*-- squaring : exp(t*H) = (exp(t*H))^(2^ns) ...
*
iodd = 1
do k = 1,ns
iget = iodd*ip + (1-iodd)*iq
iput = (1-iodd)*ip + iodd*iq
call ZGEMM( 'n','n',m,m,m, ONE,wsp(iget),m, wsp(iget),m,
. ZERO,wsp(iput),m )
iodd = 1-iodd
enddo
200 continue
iexph = iput
END
*----------------------------------------------------------------------|
subroutine DGCHBV( m, t, H,ldh, y, wsp, iwsp, iflag )
implicit none
integer m, ldh, iflag, iwsp(m)
double precision t, H(ldh,m), y(m)
complex*16 wsp(m*(m+2))
*-----Purpose----------------------------------------------------------|
*
*--- DGCHBV computes y = exp(t*H)*y using the partial fraction
* expansion of the uniform rational Chebyshev approximation
* to exp(-x) of type (14,14). H is a General matrix.
* About 14-digit accuracy is expected if the matrix H is negative
* definite. The algorithm may behave poorly otherwise.
*
*-----Arguments--------------------------------------------------------|
*
* m : (input) order of the matrix H
*
* t : (input) time-scaling factor (can be < 0).
*
* H(ldh,m): (input) argument matrix.
*
* y(m) : (input/output) on input the operand vector,
* on output the resulting vector exp(t*H)*y.
*
* iwsp(m) : (workspace)
*
* wsp : (workspace). Observe that a double precision vector of
* length 2*m*(m+2) can be used as well when calling this
* routine (thus avoiding an idle complex array elsewhere)
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer ndeg, i, j, ip, ih, iy, iz
parameter ( ndeg=7 )
double precision alpha0
complex*16 alpha(ndeg), theta(ndeg)
intrinsic DBLE
*--- Pointers ...
ih = 1
iy = ih + m*m
iz = iy + m
*--- Coefficients and poles of the partial fraction expansion ...
alpha0 = 0.183216998528140087D-11
alpha(1)=( 0.557503973136501826D+02,-0.204295038779771857D+03)
alpha(2)=(-0.938666838877006739D+02, 0.912874896775456363D+02)
alpha(3)=( 0.469965415550370835D+02,-0.116167609985818103D+02)
alpha(4)=(-0.961424200626061065D+01,-0.264195613880262669D+01)
alpha(5)=( 0.752722063978321642D+00, 0.670367365566377770D+00)
alpha(6)=(-0.188781253158648576D-01,-0.343696176445802414D-01)
alpha(7)=( 0.143086431411801849D-03, 0.287221133228814096D-03)
theta(1)=(-0.562314417475317895D+01, 0.119406921611247440D+01)
theta(2)=(-0.508934679728216110D+01, 0.358882439228376881D+01)
theta(3)=(-0.399337136365302569D+01, 0.600483209099604664D+01)
theta(4)=(-0.226978543095856366D+01, 0.846173881758693369D+01)
theta(5)=( 0.208756929753827868D+00, 0.109912615662209418D+02)
theta(6)=( 0.370327340957595652D+01, 0.136563731924991884D+02)
theta(7)=( 0.889777151877331107D+01, 0.166309842834712071D+02)
*
*--- Accumulation of the contribution of each pole ...
*
do j = 1,m
wsp(iz+j-1) = y(j)
y(j) = y(j)*alpha0
enddo
do ip = 1,ndeg
*--- Solve each fraction using Gaussian elimination with pivoting...
do j = 1,m
do i = 1,m
wsp(ih+(j-1)*m+i-1) = -t*H(i,j)
enddo
wsp(ih+(j-1)*m+j-1) = wsp(ih+(j-1)*m+j-1)-theta(ip)
wsp(iy+j-1) = wsp(iz+j-1)
enddo
call ZGESV( M, 1, WSP(iH),M, IWSP, WSP(iY),M, IFLAG )
if ( IFLAG.ne.0 ) stop 'Error in DGCHBV'
*--- Accumulate the partial result in y ...
do j = 1,m
y(j) = y(j) + DBLE( alpha(ip)*wsp(iy+j-1) )
enddo
enddo
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine DSCHBV( m, t, H,ldh, y, wsp, iwsp, iflag )
implicit none
integer m, ldh, iflag, iwsp(m)
double precision t, H(ldh,m), y(m)
complex*16 wsp(m*(m+2))
*-----Purpose----------------------------------------------------------|
*
*--- DSCHBV computes y = exp(t*H)*y using the partial fraction
* expansion of the uniform rational Chebyshev approximation
* to exp(-x) of type (14,14). H is assumed to be symmetric.
* About 14-digit accuracy is expected if the matrix H is negative
* definite. The algorithm may behave poorly otherwise.
*
*-----Arguments--------------------------------------------------------|
*
* m : (input) order of matrix H
*
* t : (input) time-scaling factor (can be < 0).
*
* H(ldh,m): (input) symmetric matrix.
*
* y(m) : (input/output) on input the operand vector,
* on output the resulting vector exp(t*H)*y.
*
* iwsp(m) : (workspace)
*
* wsp : (workspace). Observe that a double precision vector of
* length 2*m*(m+2) can be used as well when calling this
* routine (thus avoiding an idle complex array elsewhere)
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer ndeg, i, j, ip, ih, iy, iz
parameter ( ndeg=7 )
double precision alpha0
complex*16 alpha(ndeg), theta(ndeg), w
intrinsic ABS,CMPLX,DBLE,MIN
*--- Pointers ...
ih = 1
iy = ih + m*m
iz = iy + m
*--- Coefficients and poles of the partial fraction expansion ...
alpha0 = 0.183216998528140087D-11
alpha(1)=( 0.557503973136501826D+02,-0.204295038779771857D+03)
alpha(2)=(-0.938666838877006739D+02, 0.912874896775456363D+02)
alpha(3)=( 0.469965415550370835D+02,-0.116167609985818103D+02)
alpha(4)=(-0.961424200626061065D+01,-0.264195613880262669D+01)
alpha(5)=( 0.752722063978321642D+00, 0.670367365566377770D+00)
alpha(6)=(-0.188781253158648576D-01,-0.343696176445802414D-01)
alpha(7)=( 0.143086431411801849D-03, 0.287221133228814096D-03)
theta(1)=(-0.562314417475317895D+01, 0.119406921611247440D+01)
theta(2)=(-0.508934679728216110D+01, 0.358882439228376881D+01)
theta(3)=(-0.399337136365302569D+01, 0.600483209099604664D+01)
theta(4)=(-0.226978543095856366D+01, 0.846173881758693369D+01)
theta(5)=( 0.208756929753827868D+00, 0.109912615662209418D+02)
theta(6)=( 0.370327340957595652D+01, 0.136563731924991884D+02)
theta(7)=( 0.889777151877331107D+01, 0.166309842834712071D+02)
*
*--- Accumulation of the contribution of each pole ...
*
do j = 1,m
wsp(iz+j-1) = y(j)
y(j) = y(j)*alpha0
enddo
do ip = 1,ndeg
*--- Solve each fraction using Gaussian elimination with pivoting...
do j = 1,m
do i = 1,m
wsp(ih+(j-1)*m+i-1) = -t*H(i,j)
enddo
wsp(ih+(j-1)*m+j-1) = wsp(ih+(j-1)*m+j-1)-theta(ip)
wsp(iy+j-1) = wsp(iz+j-1)
enddo
call ZSYSV('U', M, 1, WSP(iH),M, IWSP, WSP(iY),M, W,1, IFLAG )
if ( IFLAG.ne.0 ) stop 'Error in DSCHBV'
*--- Accumulate the partial result in y ...
do i = 1,m
y(i) = y(i) + DBLE( alpha(ip)*wsp(iy+i-1) )
enddo
enddo
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine ZGCHBV( m, t, H,ldh, y, wsp, iwsp, iflag )
implicit none
integer m, ldh, iflag, iwsp(m)
double precision t
complex*16 H(ldh,m), y(m), wsp(m*(m+2))
*-----Purpose----------------------------------------------------------|
*
*--- ZGCHBV computes y = exp(t*H)*y using the partial fraction
* expansion of the uniform rational Chebyshev approximation
* to exp(-x) of type (14,14). H is a General matrix.
* About 14-digit accuracy is expected if the matrix H is negative
* definite. The algorithm may behave poorly otherwise.
*
*-----Arguments--------------------------------------------------------|
*
* m : (input) order of the matrix H.
*
* t : (input) time-scaling factor (can be < 0).
*
* H(ldh,m): (input) argument matrix.
*
* y(m) : (input/output) on input the operand vector,
* on output the resulting vector exp(t*H)*y.
*
* iwsp(m) : (workspace)
*
* wsp : (workspace). Observe that a double precision vector of
* length 2*m*(m+2) can be used as well when calling this
* routine.
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
integer ndeg, i, j, ip, ih, iy, iz
parameter ( ndeg=7 )
double precision alpha0
complex*16 alpha(2*ndeg), theta(2*ndeg)
*--- Pointers ...
ih = 1
iy = ih + m*m
iz = iy + m
*--- Coefficients and poles of the partial fraction expansion ...
alpha0 = 0.183216998528140087D-11
alpha(1)=( 0.557503973136501826D+02,-0.204295038779771857D+03)
alpha(2)=(-0.938666838877006739D+02, 0.912874896775456363D+02)
alpha(3)=( 0.469965415550370835D+02,-0.116167609985818103D+02)
alpha(4)=(-0.961424200626061065D+01,-0.264195613880262669D+01)
alpha(5)=( 0.752722063978321642D+00, 0.670367365566377770D+00)
alpha(6)=(-0.188781253158648576D-01,-0.343696176445802414D-01)
alpha(7)=( 0.143086431411801849D-03, 0.287221133228814096D-03)
theta(1)=(-0.562314417475317895D+01, 0.119406921611247440D+01)
theta(2)=(-0.508934679728216110D+01, 0.358882439228376881D+01)
theta(3)=(-0.399337136365302569D+01, 0.600483209099604664D+01)
theta(4)=(-0.226978543095856366D+01, 0.846173881758693369D+01)
theta(5)=( 0.208756929753827868D+00, 0.109912615662209418D+02)
theta(6)=( 0.370327340957595652D+01, 0.136563731924991884D+02)
theta(7)=( 0.889777151877331107D+01, 0.166309842834712071D+02)
*
do ip = 1,ndeg
theta(ndeg+ip) = CONJG( theta(ip) )
alpha(ndeg+ip) = CONJG( alpha(ip) )
enddo
*
*--- Accumulation of the contribution of each pole ...
*
do j = 1,m
wsp(iz+j-1) = y(j)
y(j) = y(j)*alpha0
enddo
do ip = 1,2*ndeg
alpha(ip) = 0.5d0*alpha(ip)
*--- Solve each fraction using Gaussian elimination with pivoting...
do j = 1,m
do i = 1,m
wsp(ih+(j-1)*m+i-1) = -t*H(i,j)
enddo
wsp(ih+(j-1)*m+j-1) = wsp(ih+(j-1)*m+j-1)-theta(ip)
wsp(iy+j-1) = wsp(iz+j-1)
enddo
call ZGESV( M, 1, WSP(iH),M, IWSP, WSP(iY),M, IFLAG )
if ( IFLAG.ne.0 ) stop 'Error in ZGCHBV'
*--- Accumulate the partial result in y ...
do i = 1,m
y(i) = y(i) + alpha(ip)*wsp(iy+i-1)
enddo
enddo
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine DNCHBV( m, t, H,ldh, y, wsp )
implicit none
integer m, ldh
double precision t, H(ldh,m), y(m)
complex*16 wsp(m*(m+2))
*-----Purpose----------------------------------------------------------|
*
*--- DNCHBV computes y = exp(t*H)*y using the partial fraction
* expansion of the uniform rational Chebyshev approximation
* to exp(-x) of type (14,14). H is assumed to be upper-Hessenberg.
* About 14-digit accuracy is expected if the matrix H is negative
* definite. The algorithm may behave poorly otherwise.
*
*-----Arguments--------------------------------------------------------|
*
* m : (input) order of the Hessenberg matrix H
*
* t : (input) time-scaling factor (can be < 0).
*
* H(ldh,m): (input) upper Hessenberg matrix.
*
* y(m) : (input/output) on input the operand vector,
* on output the resulting vector exp(t*H)*y.
*
* wsp : (workspace). Observe that a double precision vector of
* length 2*m*(m+2) can be used as well when calling this
* routine (thus avoiding an idle complex array elsewhere)
*
*----------------------------------------------------------------------|
* Roger B. Sidje ([email protected])
* EXPOKIT: Software Package for Computing Matrix Exponentials.
* ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
*----------------------------------------------------------------------|
*
complex*16 ZERO
integer ndeg, i, j, k, ip, ih, iy, iz
parameter ( ndeg=7, ZERO=(0.0d0,0.0d0) )
double precision alpha0
complex*16 alpha(ndeg), theta(ndeg), tmpc
intrinsic ABS,DBLE,MIN
*--- Pointers ...
ih = 1
iy = ih + m*m
iz = iy + m
*--- Coefficients and poles of the partial fraction expansion...
alpha0 = 0.183216998528140087D-11
alpha(1)=( 0.557503973136501826D+02,-0.204295038779771857D+03)
alpha(2)=(-0.938666838877006739D+02, 0.912874896775456363D+02)
alpha(3)=( 0.469965415550370835D+02,-0.116167609985818103D+02)
alpha(4)=(-0.961424200626061065D+01,-0.264195613880262669D+01)
alpha(5)=( 0.752722063978321642D+00, 0.670367365566377770D+00)
alpha(6)=(-0.188781253158648576D-01,-0.343696176445802414D-01)
alpha(7)=( 0.143086431411801849D-03, 0.287221133228814096D-03)
theta(1)=(-0.562314417475317895D+01, 0.119406921611247440D+01)
theta(2)=(-0.508934679728216110D+01, 0.358882439228376881D+01)
theta(3)=(-0.399337136365302569D+01, 0.600483209099604664D+01)
theta(4)=(-0.226978543095856366D+01, 0.846173881758693369D+01)
theta(5)=( 0.208756929753827868D+00, 0.109912615662209418D+02)
theta(6)=( 0.370327340957595652D+01, 0.136563731924991884D+02)
theta(7)=( 0.889777151877331107D+01, 0.166309842834712071D+02)
*
*--- Accumulation of the contribution of each pole ...
*
do j = 1,m
wsp(iz+j-1) = y(j)
y(j) = y(j)*alpha0
enddo
do ip = 1,ndeg
*--- Solve each fraction using Gaussian elimination with pivoting...
do j = 1,m
wsp(iy+j-1) = wsp(iz+j-1)
do i = 1,MIN( j+1,m )
wsp(ih+(j-1)*m+i-1) = -t*H(i,j)
enddo
wsp(ih+(j-1)*m+j-1) = wsp(ih+(j-1)*m+j-1)-theta(ip)
do k = i,m
wsp(ih+(j-1)*m+k-1) = ZERO
enddo
enddo
do i = 1,m-1
*--- Get pivot and exchange rows ...
if (ABS(wsp(ih+(i-1)*m+i-1)).lt.ABS(wsp(ih+(i-1)*m+i))) then
call ZSWAP( m-i+1, wsp(ih+(i-1)*m+i-1),m,
. wsp(ih+(i-1)*m+i),m )
call ZSWAP( 1, wsp(iy+i-1),1, wsp(iy+i),1 )
endif
*--- Forward eliminiation ...
tmpc = wsp(ih+(i-1)*m+i) / wsp(ih+(i-1)*m+i-1)
call ZAXPY( m-i, -tmpc, wsp(ih+i*m+i-1),m, wsp(ih+i*m+i),m )
wsp(iy+i) = wsp(iy+i) - tmpc*wsp(iy+i-1)
enddo
*--- Backward substitution ...
do i = m,1,-1
tmpc = wsp(iy+i-1)
do j = i+1,m
tmpc = tmpc - wsp(ih+(j-1)*m+i-1)*wsp(iy+j-1)
enddo
wsp(iy+i-1) = tmpc / wsp(ih+(i-1)*m+i-1)
enddo
*--- Accumulate the partial result in y ...
do j = 1,m
y(j) = y(j) + DBLE( alpha(ip)*wsp(iy+j-1) )
enddo
enddo
END
*----------------------------------------------------------------------|
*----------------------------------------------------------------------|
subroutine ZNCHBV( m, t, H,ldh, y, wsp )
implicit none
integer m, ldh
double precision t
complex*16 H(ldh,m), y(m), wsp(m*(m+2))
*-----Purpose----------------------------------------------------------|
*
*--- ZNCHBV computes y = exp(t*H)*y using the partial fraction
* expansion of the uniform rational Chebyshev approximation
* to exp(-x) of type (14,14). H is assumed to be upper-Hessenberg.
* About 14-digit accuracy is expected if the matrix H is negative
* definite. The algorithm may behave poorly otherwise.
*
*-----Arguments--------------------------------------------------------|
*
* m : (input) order of the Hessenberg matrix H
*
* t : (input) time-scaling factor (can be < 0).
*
* H(ldh,m): (input) upper Hessenberg matrix.
|
antoine-levitt/ACCQUAREL
|
b29e566af386061f0f78ceb29b40a846f20499b5
|
Do not parallelise disk access (it messes up things)
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index 6c56e7d..89d6505 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,554 +1,550 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! POUR L'INSTANT
RESUME=.FALSE.
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST)
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
- !$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
- !$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
- !$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
- !$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
|
antoine-levitt/ACCQUAREL
|
286c38ae9f27be5ce32f7f86a9f82c2c07a430aa
|
fix matrix prints once and for all, and add new BUILD_BLOCK_DIAGONAL function
|
diff --git a/src/tools.f90 b/src/tools.f90
index 4e7abe5..c6d74a3 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -1,1007 +1,1017 @@
MODULE constants
DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0
END MODULE
MODULE random
CONTAINS
! call this once
SUBROUTINE INIT_RANDOM()
! initialises random generator
! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED
INTEGER :: i, n, clock
INTEGER, DIMENSION(:), ALLOCATABLE :: seed
CALL RANDOM_SEED(size = n)
ALLOCATE(seed(n))
CALL SYSTEM_CLOCK(COUNT=clock)
seed = clock + 37 * (/ (i - 1, i = 1, n) /)
CALL RANDOM_SEED(PUT = seed)
DEALLOCATE(seed)
END SUBROUTINE INIT_RANDOM
! returns an array of random numbers of size N in (0, 1)
FUNCTION GET_RANDOM(N) RESULT(r)
REAL, DIMENSION(N) :: r
INTEGER :: N
CALL RANDOM_NUMBER(r)
END FUNCTION get_random
END MODULE random
MODULE matrix_tools
INTERFACE PACK
MODULE PROCEDURE PACK_symmetric,PACK_hermitian
END INTERFACE
INTERFACE UNPACK
MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian
END INTERFACE
INTERFACE ABA
MODULE PROCEDURE ABA_symmetric,ABA_hermitian
END INTERFACE
INTERFACE ABCBA
MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian
END INTERFACE
INTERFACE ABC_CBA
MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian
END INTERFACE
INTERFACE FINNERPRODUCT
MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex
END INTERFACE
INTERFACE NORM
MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian
END INTERFACE
INTERFACE INVERSE
MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian
END INTERFACE
INTERFACE SQUARE_ROOT
MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian
END INTERFACE
INTERFACE EXPONENTIAL
MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex
END INTERFACE EXPONENTIAL
INTERFACE TRACE
MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian
END INTERFACE
INTERFACE TRACEOFPRODUCT
MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian
END INTERFACE
INTERFACE EIGENSOLVER
MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized
END INTERFACE
INTERFACE COMMUTATOR
MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian
END INTERFACE
INTERFACE PRINTMATRIX
- MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian
+ MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian,PRINTMATRIX_complex,PRINTMATRIX_real
END INTERFACE
+INTERFACE BUILD_BLOCK_DIAGONAL
+ MODULE PROCEDURE BUILD_BLOCK_DIAGONAL_symmetric
+END INTERFACE BUILD_BLOCK_DIAGONAL
CONTAINS
! handling of symmetric and hermitian matrices stored in packed form.
FUNCTION PACK_symmetric(A,N) RESULT (PA)
! Function that stores the upper triangular part of a symmetric matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=(A(I,J)+A(J,I))/2.D0
END DO
END DO
END FUNCTION PACK_symmetric
FUNCTION PACK_hermitian(A,N) RESULT (PA)
! Function that stores the upper triangular part of a hermitian matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=A(I,J)
PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0
END DO
END DO
END FUNCTION PACK_hermitian
FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
PD=ABA(PA,ABA(PB,PC,N),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_real
FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_complex
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
SUBROUTINE NORM_check_norm(CHAR)
CHARACTER(1),INTENT(IN) :: CHAR
IF((CHAR /= 'F') .AND. &
&(CHAR /= 'I') .AND. &
&(CHAR /= '1') .AND. &
&(CHAR /= 'M')) THEN
WRITE(*,*) 'Invalid norm'
STOP
END IF
END SUBROUTINE NORM_check_norm
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
CALL NORM_check_norm(CHAR)
NORM = DLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
CALL NORM_check_norm(CHAR)
NORM = ZLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
CALL NORM_check_norm(CHAR)
NORM = DLANSP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
CALL NORM_check_norm(CHAR)
NORM = ZLANHP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
-SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
-! Subroutine that prints in the file LOGUNIT a symmetric matrix of size N*N stored in packed format.
- IMPLICIT NONE
+SUBROUTINE PRINTMATRIX_real(MAT,N,LOGUNIT)
INTEGER,INTENT(IN) :: N,LOGUNIT
- DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
+ INTEGER :: I
+ DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: MAT
+
+ DO I=1,N
+ WRITE(LOGUNIT,*) MAT(I,:)
+ END DO
+END SUBROUTINE PRINTMATRIX_real
- INTEGER :: I,J,IJ
+SUBROUTINE PRINTMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
+ INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG
+ INTEGER :: I
+ DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: MAT
- OPEN(UNIT=LOGUNIT)
- WRITE(LOGUNIT,*)N
DO I=1,N
- DO J=1,N
- IF (J<I) THEN
- WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
- ELSE
- WRITE(LOGUNIT,'(2I3,E20.12)')I,J,PMAT(I+(J-1)*J/2)
- END IF
- END DO
+ IF(LOGUNIT_REAL == LOGUNIT_IMAG) THEN
+ WRITE(LOGUNIT_REAL,*) MAT(I,:)
+ ELSE
+ WRITE(LOGUNIT_REAL,*) REAL(MAT(I,:))
+ WRITE(LOGUNIT_IMAG,*) AIMAG(MAT(I,:))
+ END IF
END DO
- CLOSE(LOGUNIT)
-END SUBROUTINE PRINTMATRIX_symmetric
+END SUBROUTINE PRINTMATRIX_complex
-SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT)
-! Subroutine that prints in the file LOGUNIT a hermitian matrix of size N*N stored in packed format.
- IMPLICIT NONE
+SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
INTEGER,INTENT(IN) :: N,LOGUNIT
- DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
+ DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
- INTEGER :: I,J,IJ
+ CALL PRINTMATRIX_real(UNPACK(PMAT,N),N,LOGUNIT)
+END SUBROUTINE PRINTMATRIX_symmetric
- OPEN(UNIT=LOGUNIT)
- WRITE(LOGUNIT,*)N
- DO I=1,N
- DO J=1,N
- IF (J<I) THEN
- WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
- ELSE
- WRITE(LOGUNIT,'(2I3,2E20.12)')I,J,PMAT(I+(J-1)*J/2)
- END IF
- END DO
- END DO
- CLOSE(LOGUNIT)
+SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT_REAL,LOGUNIT_IMAG)
+ INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG
+ DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
+
+ CALL PRINTMATRIX_complex(UNPACK(PMAT,N),N,LOGUNIT_REAL,LOGUNIT_IMAG)
END SUBROUTINE PRINTMATRIX_hermitian
-END MODULE
+
+SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric(PB,PA,N)
+ ! Builds B as [A 0;0 A], A is of size N
+ INTEGER,INTENT(IN) :: N
+ DOUBLE PRECISION, DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
+ DOUBLE PRECISION, DIMENSION(N*2*(N*2+1)/2),INTENT(OUT) :: PB
+ DOUBLE PRECISION, DIMENSION(2*N,2*N) :: B
+
+ B(1:N,1:N) = UNPACK(PA,N)
+ B(N+1:2*N,N+1:2*N) = B(1:N,1:N)
+ PB = PACK(B,2*N)
+END SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric
+END MODULE matrix_tools
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
IMPLICIT NONE
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
9e8cbb2d15e2f52ccb5f5bb78fc2b6960ba85bf9
|
Change prototype of BUILDBILIST in nonrelativistic case
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index 6d305c0..6c56e7d 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,554 +1,554 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! POUR L'INSTANT
RESUME=.FALSE.
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST)
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
- CALL BUILDBILIST(PHI,NBAS,BINMBR)
+ CALL BUILDBILIST(PHI,NBAST,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
- CALL BUILDBILIST(PHI,NBAS,BINMBR)
+ CALL BUILDBILIST(PHI,NBAST,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90
index b0c20fd..7649ddc 100644
--- a/src/integrals_f.f90
+++ b/src/integrals_f.f90
@@ -1,547 +1,547 @@
MODULE integrals
! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/).
! number of a priori nonzero bielectronic integrals
INTEGER :: BINMBR
! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory)
INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES
CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE
! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK
INTEGER,DIMENSION(2) :: NBF
! unit number for the list of nonzero bielectronic integrals (when stored on disk)
INTEGER,PARAMETER :: LUNIT=10
! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk)
INTEGER,PARAMETER :: BIUNIT=11
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) &
& BIND(C,NAME="unrolloverlap")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) &
& BIND(C,NAME="unrollkinetic")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& dimension) &
& BIND(C,NAME="unrollderiv")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
INTEGER(KIND=C_INT),VALUE :: dimension
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& center) &
& BIND(C,NAME="unrollpotential")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& dimension1,dimension2) &
& BIND(C,NAME="unrollxderiv")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b
INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2
END FUNCTION
END INTERFACE
INTERFACE
REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, &
& nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, &
& nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, &
& nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) &
& BIND(C,NAME="unrollcoulomb")
USE iso_c_binding
INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d
END FUNCTION
END INTERFACE
INTERFACE COULOMBVALUE
MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed
END INTERFACE
INTERFACE BUILDBILIST
MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic
END INTERFACE
CONTAINS
FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree)
END FUNCTION OVERLAPVALUE
FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree)
END FUNCTION KINETICVALUE
FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator).
! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z).
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& DIMENSION-1)
END FUNCTION DERIVVALUE
FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& CENTER)
END FUNCTION POTENTIALVALUE
FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE)
! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator).
! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z).
! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z).
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B
INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& DIMENSION1-1,DIMENSION2-1)
END FUNCTION XDERIVVALUE
FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE)
! Function that computes the value of the bielectronic integral between four gaussian basis functions.
USE iso_c_binding ; USE basis_parameters
TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, &
& PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, &
& PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, &
& PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree)
END FUNCTION COULOMBVALUE_nonrelativistic
-SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAS,LISTSIZE)
+SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE)
! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value.
! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974.
USE case_parameters ; USE basis_parameters
TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI
- INTEGER,DIMENSION(1),INTENT(IN) :: NBAS
+ INTEGER,INTENT(IN) :: NBAST
INTEGER,INTENT(OUT) :: LISTSIZE
INTEGER :: I,J,K,L
INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE
LOGICAL :: SC
OPEN(LUNIT,form='UNFORMATTED')
! determination of the number of elements (i.e., integer quadruples) that compose the list
LISTSIZE=0
- DO I=1,NBAS(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K
+ DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K
SC=((PHI(I)%center_id==PHI(J)%center_id).AND.(PHI(J)%center_id==PHI(K)%center_id).AND.(PHI(K)%center_id==PHI(L)%center_id))
GLOBALMONOMIALDEGREE=PHI(I)%monomialdegree+PHI(J)%monomialdegree+PHI(K)%monomialdegree+PHI(L)%monomialdegree
! parity check on the product of the monomials if the four functions share the same center
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L
IF (K<J) THEN
LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L
END IF
IF ((J<I).AND.(L<K)) THEN
LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K
END IF
END IF
END DO ; END DO ; END DO ; END DO
CLOSE(LUNIT)
WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE
END SUBROUTINE BUILDBILIST_nonrelativistic
FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE)
! Function that computes the value of the bielectronic integral between four 2-spinor basis functions.
USE basis_parameters
TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D
DOUBLE COMPLEX :: VALUE
INTEGER :: I,IA,IB,J,JC,JD
VALUE=(0.D0,0.D0)
DO I=1,2
DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I)
DO J=1,2
DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J)
VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) &
& *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) &
& *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), &
& PHI_D%contractions(J,JD))
END DO ; END DO
END DO
END DO ; END DO
END DO
END FUNCTION COULOMBVALUE_relativistic
FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE)
! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions.
USE basis_parameters
TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D
CHARACTER(2),INTENT(IN) :: CLASS
DOUBLE COMPLEX :: VALUE
INTEGER :: I,IA,IB,J,JC,JD
VALUE=(0.D0,0.D0)
DO I=1,2
DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I)
DO J=1,2
DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J)
VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) &
& *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) &
& *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), &
& PHI_D%contidx(J,JD),CLASS)
END DO ; END DO
END DO
END DO ; END DO
END DO
END FUNCTION COULOMBVALUE_precomputed
SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE)
! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value.
USE case_parameters ; USE basis_parameters ; USE scf_parameters
TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3)
INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6
INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE
LOGICAL :: SC
OPEN(LUNIT,form='UNFORMATTED')
! determination of the number of elements (i.e., integer quadruples) that compose the list
SUBSIZE=0
! LLLL-type integrals
DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1)
IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN
DO I1=1,2
DO I2=1,PHI(I)%nbrofcontractions(I1)
DO I3=1,PHI(J)%nbrofcontractions(I1)
DO I4=1,2
DO I5=1,PHI(K)%nbrofcontractions(I4)
DO I6=1,PHI(L)%nbrofcontractions(I4)
SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) &
& .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) &
& .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id))
GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree &
& +PHI(J)%contractions(I1,I3)%monomialdegree &
& +PHI(K)%contractions(I4,I5)%monomialdegree &
& +PHI(L)%contractions(I4,I6)%monomialdegree
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
SUBSIZE(1)=SUBSIZE(1)+1
WRITE(LUNIT)I,J,K,L,'LL'
GO TO 1
END IF
END DO
END DO
END DO
END DO
END DO
END DO
1 CONTINUE
END IF
END DO ; END DO ; END DO ; END DO
! SSLL-type integrals
DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1)
DO I1=1,2
DO I2=1,PHI(I)%nbrofcontractions(I1)
DO I3=1,PHI(J)%nbrofcontractions(I1)
DO I4=1,2
DO I5=1,PHI(K)%nbrofcontractions(I4)
DO I6=1,PHI(L)%nbrofcontractions(I4)
SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) &
& .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) &
& .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id))
GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree &
& +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
WRITE(LUNIT)I,J,K,L,'SL'
SUBSIZE(2)=SUBSIZE(2)+1
GO TO 2
END IF
END DO
END DO
END DO
END DO
END DO
END DO
2 CONTINUE
END DO ; END DO ; END DO ; END DO
IF (SSINTEGRALS) THEN
! SSSS-type integrals
DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS)
IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN
DO I1=1,2
DO I2=1,PHI(I)%nbrofcontractions(I1)
DO I3=1,PHI(J)%nbrofcontractions(I1)
DO I4=1,2
DO I5=1,PHI(K)%nbrofcontractions(I4)
DO I6=1,PHI(L)%nbrofcontractions(I4)
SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) &
& .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) &
& .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id))
GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree &
& +PHI(J)%contractions(I1,I3)%monomialdegree &
& +PHI(K)%contractions(I4,I5)%monomialdegree &
& +PHI(L)%contractions(I4,I6)%monomialdegree
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
WRITE(LUNIT)I,J,K,L,'SS'
SUBSIZE(3)=SUBSIZE(3)+1
GO TO 3
END IF
END DO
END DO
END DO
END DO
END DO
END DO
3 CONTINUE
END IF
END DO ; END DO ; END DO ; END DO
END IF
LISTSIZE=SUM(SUBSIZE)
CLOSE(LUNIT)
WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE
END SUBROUTINE BUILDBILIST_relativistic
SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function).
USE basis_parameters ; USE scf_parameters
INTEGER,DIMENSION(2),INTENT(IN) :: NGBF
TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF
INTEGER :: I,J,K,L,M,N,O
INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE
LOGICAL :: SC
NBF=NGBF
! (LL|LL) integrals
WRITE(*,*)'- Computing LL integrals'
ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), &
& LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), &
& LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24))
M=0 ; N=0 ; O=0
DO I=1,NGBF(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K
SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id))
GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
! parity check (one center case)
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
IF (K<J) THEN
N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L))
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K))
END IF
ELSE
M=M+1 ; LLIJKL(M)=(0.D0,0.D0)
IF (K<J) THEN
N=N+1 ; LLIKJL(N)=(0.D0,0.D0)
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; LLILJK(O)=(0.D0,0.D0)
END IF
END IF
END DO ; END DO ; END DO ; END DO
! (SS|LL) integrals
WRITE(*,*)'- Computing SL integrals'
ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4))
N=0
! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly.
!$OMP PARALLEL DO PRIVATE(N,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1)
DO I=NGBF(1)+1,SUM(NGBF)
! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential).
N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2
! this takes N(N+1)/2*(I-N) iters
DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K
SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id))
GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
! parity check (one center case)
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
ELSE
N=N+1 ; SLIJKL(N)=(0.D0,0.D0)
END IF
END DO ; END DO ; END DO ; END DO
!$OMP END PARALLEL DO
IF (SSINTEGRALS) THEN
! (SS|SS) integrals
WRITE(*,*)'- Computing SS integrals'
ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), &
& SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), &
& SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24))
M=0 ; N=0 ; O=0
!$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1)
DO I=NGBF(1)+1,SUM(NGBF)
! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential).
M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24
N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24
O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24
DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K
SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id))
GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree
! parity check (one center case)
IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN
M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L))
IF (K<J) THEN
N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L))
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K))
END IF
ELSE
M=M+1 ; SSIJKL(M)=(0.D0,0.D0)
IF (K<J) THEN
N=N+1 ; SSIKJL(N)=(0.D0,0.D0)
END IF
IF ((J<I).AND.(L<K)) THEN
O=O+1 ; SSILJK(O)=(0.D0,0.D0)
END IF
END IF
END DO ; END DO ; END DO ; END DO
!$OMP END PARALLEL DO
END IF
END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES
FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE)
! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974).
! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis.
USE basis_parameters
INTEGER,INTENT(IN) :: I,J,K,L
CHARACTER(2),INTENT(IN) :: CLASS
DOUBLE COMPLEX :: VALUE
INTEGER :: IDX
INTEGER,DIMENSION(4) :: N,TMP
! Preliminaries
N=(/I,J,K,L/)
TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/)
TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/)
TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/)
IF (CLASS.EQ.'LL') THEN
! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions
IF (N(3)<=N(2)) THEN
! integral of type (IJ|KL)
IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=LLIJKL(IDX)
ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN
! integral of type (IJ|KL)
IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=LLIJKL(IDX)
ELSE IF (N(4)<=N(2)) THEN
! integral of type (IK|JL)
IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=LLIKJL(IDX)
ELSE IF (N(1)==N(3)) THEN
! integral of type (IK|JL)
IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=LLIKJL(IDX)
ELSE
! integral of type (IL|JK)
IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24
VALUE=LLILJK(IDX)
END IF
ELSE IF (CLASS=='SL') THEN
! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions
N(1:2)=N(1:2)-(/NBF(1),NBF(1)/)
IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2
VALUE=SLIJKL(IDX)
ELSE IF (CLASS=='SS') THEN
N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/)
! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions
IF (N(3)<=N(2)) THEN
! integral of type (IJ|KL)
IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=SSIJKL(IDX)
ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN
! integral of type (IJ|KL)
IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24
VALUE=SSIJKL(IDX)
ELSE IF (N(4)<=N(2)) THEN
! integral of type (IK|JL)
IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=SSIKJL(IDX)
ELSE IF (N(1)==N(3)) THEN
! integral of type (IK|JL)
IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24
VALUE=SSIKJL(IDX)
ELSE
! integral of type (IL|JK)
IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24
VALUE=SSILJK(IDX)
END IF
END IF
END FUNCTION PRECOMPUTEDCOULOMBVALUE
SUBROUTINE DEALLOCATE_INTEGRALS
USE scf_parameters
! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis.
DEALLOCATE(LLIJKL,LLIKJL,LLILJK,SLIJKL)
IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK)
END SUBROUTINE DEALLOCATE_INTEGRALS
END MODULE
|
antoine-levitt/ACCQUAREL
|
1626a02aecacc1df6a1126825815bb911a2c1c71
|
Use new syntax for LINESEARCH
|
diff --git a/src/gradient.f90 b/src/gradient.f90
index bd53cec..6f74e50 100644
--- a/src/gradient.f90
+++ b/src/gradient.f90
@@ -1,380 +1,380 @@
MODULE gradient_mod
USE basis_parameters
DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG
DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG
TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG
INTEGER,POINTER :: NBAST_PG
CONTAINS
FUNCTION OBJECTIVE(EPS)
USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions
USE matrices
DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM
DOUBLE PRECISION :: OBJECTIVE,EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),&
&UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG)
PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D')
CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW)
OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG)
END FUNCTION OBJECTIVE
FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE optimization_tools
IMPLICIT NONE
INTEGER :: INFO,LOON
INTEGER,INTENT(IN),TARGET :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW
POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST
E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS)
write(*,*) EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH_golden
! performs a linesearch about PDM
FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,INFO,LOON
DOUBLE PRECISION :: E,EAFTER,EBEFORE,FIRST_DER,SECOND_DER,EPS,DER_AFTER
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW
INTEGER,PARAMETER :: N_POINTS = 20
DOUBLE PRECISION, DIMENSION(N_POINTS) :: ENERGIES
DOUBLE PRECISION, PARAMETER :: EPS_MIN = 0D0
DOUBLE PRECISION, PARAMETER :: EPS_MAX = 10D0
CHARACTER(1),PARAMETER :: ALGORITHM = 'E'
CHARACTER(1),PARAMETER :: SEARCH_SPACE = 'L'
! compute EPS
IF(ALGORITHM == 'F') THEN
! fixed
EPS = 0.1
ELSEIF(ALGORITHM == 'E') THEN
! exhaustive search
! energy at PDM
PDMNEW=PDM
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW)
E=ENERGY(POEFM,PTEFM,PDMNEW,NBAST)
do I=1,N_POINTS
if(SEARCH_SPACE == 'L') THEN
eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
ELSE
eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
eps = 10**eps
END if
! energy at PDM + eps
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW)
ENERGIES(I)=ENERGY(POEFM,PTEFM,PDMNEW,NBAST)
end do
I = MINLOC(ENERGIES,1)
if(SEARCH_SPACE == 'L') THEN
eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
ELSE
eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
eps = 10**eps
END if
write(*,*) eps
END IF
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
! uncomment for a roothaan step
! ! Assembly and diagonalization of the Fock matrix
! CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW)
! CALL EIGENSOLVER(POEFM+PTEFM,PCFS,NBAST,EIG,EIGVEC,INFO)
! ! Assembly of the density matrix according to the aufbau principle
! CALL CHECKORB(EIG,NBAST,LOON)
! CALL FORMDM(PDMNEW,EIGVEC,NBAST,LOON,LOON+NBE-1)
END FUNCTION LINESEARCH
END MODULE gradient_mod
SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE gradient_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
PDM = THETA(PDM,POEFM,NBAST,PHI,'D')
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM1 = PDM
! PDM by line search
- PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PHI)
+ PDM = LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==200*MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE GRADIENT_relativistic
SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,EPS
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1 = PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
EPS = .05
PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==1000*MAXITR+200) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
5ab0b691124c922e6cd2fa07345e104633902d19
|
Exhaustive search rather than finite differences
|
diff --git a/src/gradient.f90 b/src/gradient.f90
index 13c719e..bd53cec 100644
--- a/src/gradient.f90
+++ b/src/gradient.f90
@@ -1,338 +1,380 @@
MODULE gradient_mod
USE basis_parameters
DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG
DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG
TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG
INTEGER,POINTER :: NBAST_PG
CONTAINS
FUNCTION OBJECTIVE(EPS)
USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions
USE matrices
DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM
DOUBLE PRECISION :: OBJECTIVE,EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),&
&UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG)
PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D')
CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW)
OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG)
END FUNCTION OBJECTIVE
FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE optimization_tools
IMPLICIT NONE
INTEGER :: INFO,LOON
INTEGER,INTENT(IN),TARGET :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW
POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST
E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS)
write(*,*) EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH_golden
! performs a linesearch about PDM
-FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PHI) RESULT(PDMNEW)
+FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
- DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
- INTEGER :: I
- DOUBLE PRECISION :: ETOT,EPS
+ INTEGER :: I,INFO,LOON
+ DOUBLE PRECISION :: E,EAFTER,EBEFORE,FIRST_DER,SECOND_DER,EPS,DER_AFTER
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW
+ INTEGER,PARAMETER :: N_POINTS = 20
+ DOUBLE PRECISION, DIMENSION(N_POINTS) :: ENERGIES
- DOUBLE PRECISION,PARAMETER :: EPS_FINDIFF = 0.001
- CHARACTER(1),PARAMETER :: ALGORITHM = 'F'
-
+ DOUBLE PRECISION, PARAMETER :: EPS_MIN = 0D0
+ DOUBLE PRECISION, PARAMETER :: EPS_MAX = 10D0
+ CHARACTER(1),PARAMETER :: ALGORITHM = 'E'
+ CHARACTER(1),PARAMETER :: SEARCH_SPACE = 'L'
+
! compute EPS
IF(ALGORITHM == 'F') THEN
! fixed
EPS = 0.1
- ELSEIF(ALGORITHM == 'Q') THEN
- ! quadratic model
+ ELSEIF(ALGORITHM == 'E') THEN
+ ! exhaustive search
+ ! energy at PDM
+ PDMNEW=PDM
+ CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW)
+ E=ENERGY(POEFM,PTEFM,PDMNEW,NBAST)
+
+ do I=1,N_POINTS
+ if(SEARCH_SPACE == 'L') THEN
+ eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
+ ELSE
+ eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
+ eps = 10**eps
+ END if
+ ! energy at PDM + eps
+ PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
+ &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
+ PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
+ CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW)
+ ENERGIES(I)=ENERGY(POEFM,PTEFM,PDMNEW,NBAST)
+ end do
+
+ I = MINLOC(ENERGIES,1)
+ if(SEARCH_SPACE == 'L') THEN
+ eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
+ ELSE
+ eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1)
+ eps = 10**eps
+ END if
+ write(*,*) eps
END IF
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
+
+ ! uncomment for a roothaan step
+ ! ! Assembly and diagonalization of the Fock matrix
+ ! CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW)
+ ! CALL EIGENSOLVER(POEFM+PTEFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ ! ! Assembly of the density matrix according to the aufbau principle
+ ! CALL CHECKORB(EIG,NBAST,LOON)
+ ! CALL FORMDM(PDMNEW,EIGVEC,NBAST,LOON,LOON+NBE-1)
END FUNCTION LINESEARCH
END MODULE gradient_mod
SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE gradient_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
PDM = THETA(PDM,POEFM,NBAST,PHI,'D')
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM1 = PDM
! PDM by line search
PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PHI)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==200*MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE GRADIENT_relativistic
SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,EPS
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1 = PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
EPS = .05
PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==1000*MAXITR+200) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
061108d417485726ea57c2d050394eb3b4fc0d79
|
Do a theta before beginning gradient algorithm
|
diff --git a/src/gradient.f90 b/src/gradient.f90
index 3b76696..13c719e 100644
--- a/src/gradient.f90
+++ b/src/gradient.f90
@@ -1,338 +1,338 @@
MODULE gradient_mod
USE basis_parameters
DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG
DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG
TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG
INTEGER,POINTER :: NBAST_PG
CONTAINS
FUNCTION OBJECTIVE(EPS)
USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions
USE matrices
DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM
DOUBLE PRECISION :: OBJECTIVE,EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),&
&UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG)
PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D')
CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW)
OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG)
END FUNCTION OBJECTIVE
FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE optimization_tools
IMPLICIT NONE
INTEGER :: INFO,LOON
INTEGER,INTENT(IN),TARGET :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW
POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST
E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS)
write(*,*) EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH_golden
! performs a linesearch about PDM
FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
DOUBLE PRECISION :: ETOT,EPS
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW
DOUBLE PRECISION,PARAMETER :: EPS_FINDIFF = 0.001
CHARACTER(1),PARAMETER :: ALGORITHM = 'F'
! compute EPS
IF(ALGORITHM == 'F') THEN
! fixed
EPS = 0.1
ELSEIF(ALGORITHM == 'Q') THEN
! quadratic model
END IF
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH
END MODULE gradient_mod
SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE gradient_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
+ PDM = THETA(PDM,POEFM,NBAST,PHI,'D')
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM1 = PDM
! PDM by line search
PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PHI)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==200*MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE GRADIENT_relativistic
SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,EPS
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1 = PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
- PDM = THETA(PDM,POEFM,NBAST,PHI,'D')
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
EPS = .05
PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==1000*MAXITR+200) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
bfa72802652d74c105a6ae4d8a48e01dd9c32e05
|
do a theta before beginning gradient algorithm
|
diff --git a/src/gradient.f90 b/src/gradient.f90
index 5c35d92..3b76696 100644
--- a/src/gradient.f90
+++ b/src/gradient.f90
@@ -1,337 +1,338 @@
MODULE gradient_mod
USE basis_parameters
DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG
DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG
TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG
INTEGER,POINTER :: NBAST_PG
CONTAINS
FUNCTION OBJECTIVE(EPS)
USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions
USE matrices
DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM
DOUBLE PRECISION :: OBJECTIVE,EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),&
&UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG)
PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D')
CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW)
OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG)
END FUNCTION OBJECTIVE
FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE optimization_tools
IMPLICIT NONE
INTEGER :: INFO,LOON
INTEGER,INTENT(IN),TARGET :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW
POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST
E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS)
write(*,*) EPS
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH_golden
! performs a linesearch about PDM
FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
DOUBLE PRECISION :: ETOT,EPS
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW
DOUBLE PRECISION,PARAMETER :: EPS_FINDIFF = 0.001
CHARACTER(1),PARAMETER :: ALGORITHM = 'F'
! compute EPS
IF(ALGORITHM == 'F') THEN
! fixed
EPS = 0.1
ELSEIF(ALGORITHM == 'Q') THEN
! quadratic model
END IF
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH
END MODULE gradient_mod
SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE gradient_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM1 = PDM
! PDM by line search
PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PHI)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==200*MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE GRADIENT_relativistic
SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,EPS
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1 = PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
+ PDM = THETA(PDM,POEFM,NBAST,PHI,'D')
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
EPS = .05
PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==1000*MAXITR+200) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
ee1cfa48ce0ff4c9b029bb6332697bbc4aee4caa
|
golden linesearch
|
diff --git a/src/gradient.f90 b/src/gradient.f90
index 20daef1..5c35d92 100644
--- a/src/gradient.f90
+++ b/src/gradient.f90
@@ -1,290 +1,337 @@
MODULE gradient_mod
+ USE basis_parameters
+
+ DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG
+ DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG
+ TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG
+ INTEGER,POINTER :: NBAST_PG
CONTAINS
+ FUNCTION OBJECTIVE(EPS)
+ USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions
+ USE matrices
+
+ DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM
+ DOUBLE PRECISION :: OBJECTIVE,EPS
+
+ PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),&
+ &UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG)
+ PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D')
+ CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW)
+ OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG)
+ END FUNCTION OBJECTIVE
+
+
+ FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW)
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
+ USE esa_mod ; USE optimization_tools
+ IMPLICIT NONE
+ INTEGER :: INFO,LOON
+ INTEGER,INTENT(IN),TARGET :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST) :: EIG
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC
+ DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc
+ DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT
+ TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
+ DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW
+
+ POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST
+
+ E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS)
+ write(*,*) EPS
+
+ PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
+ &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
+
+ PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
+ END FUNCTION LINESEARCH_golden
+
! performs a linesearch about PDM
FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PHI) RESULT(PDMNEW)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
DOUBLE PRECISION :: ETOT,EPS
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW
DOUBLE PRECISION,PARAMETER :: EPS_FINDIFF = 0.001
CHARACTER(1),PARAMETER :: ALGORITHM = 'F'
! compute EPS
IF(ALGORITHM == 'F') THEN
! fixed
EPS = 0.1
ELSEIF(ALGORITHM == 'Q') THEN
! quadratic model
END IF
PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
&UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
END FUNCTION LINESEARCH
END MODULE gradient_mod
SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
USE esa_mod ; USE gradient_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM1 = PDM
! PDM by line search
PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PHI)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==200*MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE GRADIENT_relativistic
SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,EPS
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1 = PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
EPS = .05
PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==1000*MAXITR+200) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
f229bc4149d1ba66f50e92f5e74243c016d1acaf
|
Remove old USE random
|
diff --git a/src/tools.f90 b/src/tools.f90
index bab2689..4e7abe5 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -265,744 +265,743 @@ FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
PD=ABA(PA,ABA(PB,PC,N),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_real
FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_complex
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
SUBROUTINE NORM_check_norm(CHAR)
CHARACTER(1),INTENT(IN) :: CHAR
IF((CHAR /= 'F') .AND. &
&(CHAR /= 'I') .AND. &
&(CHAR /= '1') .AND. &
&(CHAR /= 'M')) THEN
WRITE(*,*) 'Invalid norm'
STOP
END IF
END SUBROUTINE NORM_check_norm
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
CALL NORM_check_norm(CHAR)
NORM = DLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
CALL NORM_check_norm(CHAR)
NORM = ZLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
CALL NORM_check_norm(CHAR)
NORM = DLANSP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
CALL NORM_check_norm(CHAR)
NORM = ZLANHP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
- USE random
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a symmetric matrix of size N*N stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a hermitian matrix of size N*N stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,2E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_hermitian
END MODULE
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
IMPLICIT NONE
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
22b23f94ee5334642418fbabafc83ed828338654
|
Better ABCBA
|
diff --git a/src/tools.f90 b/src/tools.f90
index 56d82b3..bab2689 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -1,804 +1,801 @@
MODULE constants
DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0
END MODULE
MODULE random
CONTAINS
! call this once
SUBROUTINE INIT_RANDOM()
! initialises random generator
! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED
INTEGER :: i, n, clock
INTEGER, DIMENSION(:), ALLOCATABLE :: seed
CALL RANDOM_SEED(size = n)
ALLOCATE(seed(n))
CALL SYSTEM_CLOCK(COUNT=clock)
seed = clock + 37 * (/ (i - 1, i = 1, n) /)
CALL RANDOM_SEED(PUT = seed)
DEALLOCATE(seed)
END SUBROUTINE INIT_RANDOM
! returns an array of random numbers of size N in (0, 1)
FUNCTION GET_RANDOM(N) RESULT(r)
REAL, DIMENSION(N) :: r
INTEGER :: N
CALL RANDOM_NUMBER(r)
END FUNCTION get_random
END MODULE random
MODULE matrix_tools
INTERFACE PACK
MODULE PROCEDURE PACK_symmetric,PACK_hermitian
END INTERFACE
INTERFACE UNPACK
MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian
END INTERFACE
INTERFACE ABA
MODULE PROCEDURE ABA_symmetric,ABA_hermitian
END INTERFACE
INTERFACE ABCBA
MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian
END INTERFACE
INTERFACE ABC_CBA
MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian
END INTERFACE
INTERFACE FINNERPRODUCT
MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex
END INTERFACE
INTERFACE NORM
MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian
END INTERFACE
INTERFACE INVERSE
MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian
END INTERFACE
INTERFACE SQUARE_ROOT
MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian
END INTERFACE
INTERFACE EXPONENTIAL
MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex
END INTERFACE EXPONENTIAL
INTERFACE TRACE
MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian
END INTERFACE
INTERFACE TRACEOFPRODUCT
MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian
END INTERFACE
INTERFACE EIGENSOLVER
MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized
END INTERFACE
INTERFACE COMMUTATOR
MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian
END INTERFACE
INTERFACE PRINTMATRIX
MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian
END INTERFACE
CONTAINS
! handling of symmetric and hermitian matrices stored in packed form.
FUNCTION PACK_symmetric(A,N) RESULT (PA)
! Function that stores the upper triangular part of a symmetric matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=(A(I,J)+A(J,I))/2.D0
END DO
END DO
END FUNCTION PACK_symmetric
FUNCTION PACK_hermitian(A,N) RESULT (PA)
! Function that stores the upper triangular part of a hermitian matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=A(I,J)
PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0
END DO
END DO
END FUNCTION PACK_hermitian
FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
- DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
-
- A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
- PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
+ PD=ABA(PA,ABA(PB,PC,N),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_real
FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_complex
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
SUBROUTINE NORM_check_norm(CHAR)
CHARACTER(1),INTENT(IN) :: CHAR
IF((CHAR /= 'F') .AND. &
&(CHAR /= 'I') .AND. &
&(CHAR /= '1') .AND. &
&(CHAR /= 'M')) THEN
WRITE(*,*) 'Invalid norm'
STOP
END IF
END SUBROUTINE NORM_check_norm
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
CALL NORM_check_norm(CHAR)
NORM = DLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
CALL NORM_check_norm(CHAR)
NORM = ZLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
CALL NORM_check_norm(CHAR)
NORM = DLANSP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
CALL NORM_check_norm(CHAR)
NORM = ZLANHP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
USE random
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
|
antoine-levitt/ACCQUAREL
|
7091b783bd89d8784293263213ec3c1d2ccbe7a8
|
Also output condition number in nonrelativistic case
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index 67794f1..6d305c0 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,552 +1,554 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! POUR L'INSTANT
RESUME=.FALSE.
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Condition number
WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
+! Condition number
+ WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST)
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
|
antoine-levitt/ACCQUAREL
|
8df70a54f10c8ffaedec682b198b9d45fdf3135e
|
Skeleton for new LINESEARCH function
|
diff --git a/src/gradient.f90 b/src/gradient.f90
index 7b08241..20daef1 100644
--- a/src/gradient.f90
+++ b/src/gradient.f90
@@ -1,261 +1,290 @@
+MODULE gradient_mod
+CONTAINS
+! performs a linesearch about PDM
+FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PHI) RESULT(PDMNEW)
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
+ USE esa_mod
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT
+ TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
+ INTEGER :: I
+ DOUBLE PRECISION :: ETOT,EPS
+ DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW
+
+ DOUBLE PRECISION,PARAMETER :: EPS_FINDIFF = 0.001
+ CHARACTER(1),PARAMETER :: ALGORITHM = 'F'
+
+ ! compute EPS
+ IF(ALGORITHM == 'F') THEN
+ ! fixed
+ EPS = 0.1
+ ELSEIF(ALGORITHM == 'Q') THEN
+ ! quadratic model
+ END IF
+
+ PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
+ &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
+
+ PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D')
+END FUNCTION LINESEARCH
+END MODULE gradient_mod
+
SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
- USE esa_mod
+ USE esa_mod ; USE gradient_mod
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
- DOUBLE PRECISION :: EPS
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,LOON,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
- EPS = .1
- PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
- PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
- UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
-
- PPM = THETA(PDM,POEFM,NBAST,PHI,'D')
- PDM = PPM
-
+ PDM1 = PDM
+ ! PDM by line search
+ PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PHI)
+
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==200*MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE GRADIENT_relativistic
SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
IMPLICIT NONE
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
INTEGER :: ITER,INFO,I
DOUBLE PRECISION :: ETOT,ETOT1,EPS
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
LOGICAL :: NUMCONV
! INITIALIZATION AND PRELIMINARIES
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
ITER=0
PDM=(0.D0,0.D0)
PTEFM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! Assembly of the density matrix according to the aufbau principle
PDM1 = PDM
CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 5
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
GO TO 6
4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18)
STOP
! Gradient algorithm
6 WRITE(*,*) ' '
WRITE(*,*) 'Switching to gradient algorithm'
WRITE(*,*) ' '
ITER = 0
7 ITER=ITER+1
WRITE(*,'(a)')' '
WRITE(*,'(a,i3)')'# ITER = ',ITER
! Assembly and diagonalization of the Fock matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 4
! computation of the commutator
EPS = .05
PDM1 = PDM
! CMT in ON basis = DF - Sm1 F D S
CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
GO TO 2
ELSE IF (ITER==1000*MAXITR+200) THEN
! Maximum number of iterations reached without convergence
GO TO 5
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 7
END IF
END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
6f3ec7fd20b466e77d1dccf058770ad44ee5a012
|
PACK_symmetric: also symmetrise matrices
|
diff --git a/src/tools.f90 b/src/tools.f90
index 7cfa0d2..56d82b3 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -1,641 +1,642 @@
MODULE constants
DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0
END MODULE
MODULE random
CONTAINS
! call this once
SUBROUTINE INIT_RANDOM()
! initialises random generator
! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED
INTEGER :: i, n, clock
INTEGER, DIMENSION(:), ALLOCATABLE :: seed
CALL RANDOM_SEED(size = n)
ALLOCATE(seed(n))
CALL SYSTEM_CLOCK(COUNT=clock)
seed = clock + 37 * (/ (i - 1, i = 1, n) /)
CALL RANDOM_SEED(PUT = seed)
DEALLOCATE(seed)
END SUBROUTINE INIT_RANDOM
! returns an array of random numbers of size N in (0, 1)
FUNCTION GET_RANDOM(N) RESULT(r)
REAL, DIMENSION(N) :: r
INTEGER :: N
CALL RANDOM_NUMBER(r)
END FUNCTION get_random
END MODULE random
MODULE matrix_tools
INTERFACE PACK
MODULE PROCEDURE PACK_symmetric,PACK_hermitian
END INTERFACE
INTERFACE UNPACK
MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian
END INTERFACE
INTERFACE ABA
MODULE PROCEDURE ABA_symmetric,ABA_hermitian
END INTERFACE
INTERFACE ABCBA
MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian
END INTERFACE
INTERFACE ABC_CBA
MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian
END INTERFACE
INTERFACE FINNERPRODUCT
MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex
END INTERFACE
INTERFACE NORM
MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian
END INTERFACE
INTERFACE INVERSE
MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian
END INTERFACE
INTERFACE SQUARE_ROOT
MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian
END INTERFACE
INTERFACE EXPONENTIAL
MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex
END INTERFACE EXPONENTIAL
INTERFACE TRACE
MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian
END INTERFACE
INTERFACE TRACEOFPRODUCT
MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian
END INTERFACE
INTERFACE EIGENSOLVER
MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized
END INTERFACE
INTERFACE COMMUTATOR
MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian
END INTERFACE
INTERFACE PRINTMATRIX
MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian
END INTERFACE
CONTAINS
! handling of symmetric and hermitian matrices stored in packed form.
FUNCTION PACK_symmetric(A,N) RESULT (PA)
! Function that stores the upper triangular part of a symmetric matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
- PA(IJ)=A(I,J)
+ PA(IJ)=(A(I,J)+A(J,I))/2.D0
END DO
END DO
END FUNCTION PACK_symmetric
FUNCTION PACK_hermitian(A,N) RESULT (PA)
! Function that stores the upper triangular part of a hermitian matrix in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=A(I,J)
+ PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0
END DO
END DO
END FUNCTION PACK_hermitian
FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_real
FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: T
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
INTEGER :: IEXP,NS,IFLAG
INTEGER,DIMENSION(N) :: IWSP
INTEGER,PARAMETER :: IDEG=6
DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
IF (IFLAG/=0) GO TO 1
EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
RETURN
1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
WRITE(*,*)'(called from function EXPONENTIAL)'
STOP
END FUNCTION EXPONENTIAL_complex
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
|
antoine-levitt/ACCQUAREL
|
92d95671b7126bfffa742684d959b4278ae708ef
|
Refactor norm computation
|
diff --git a/src/tools.f90 b/src/tools.f90
index 25c8a83..f5f03b8 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -127,857 +127,841 @@ FUNCTION PACK_hermitian(A,N) RESULT (PA)
PA(IJ)=A(I,J)
END DO
END DO
END FUNCTION PACK_hermitian
FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
+SUBROUTINE NORM_check_norm(CHAR)
+ CHARACTER(1),INTENT(IN) :: CHAR
+ IF((CHAR /= 'F') .AND. &
+ &(CHAR /= 'I') .AND. &
+ &(CHAR /= '1') .AND. &
+ &(CHAR /= 'M')) THEN
+ WRITE(*,*) 'Invalid norm'
+ STOP
+ END IF
+END SUBROUTINE NORM_check_norm
+
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the Frobenius or infinity norm of a square real matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
-IF (CHAR=='F') THEN
- NORM=DLANGE('F',N,N,M,N,WORK)
- ELSE IF (CHAR=='I') THEN
- NORM=DLANGE('I',N,N,M,N,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=DLANGE('1',N,N,M,N,WORK)
- ELSE
- STOP'undefined matrix norm'
- END IF
+ CALL NORM_check_norm(CHAR)
+ NORM = DLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the Frobenius or infinity norm of a square complex matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
-IF (CHAR=='F') THEN
- NORM=ZLANGE('F',N,N,M,N,WORK)
- ELSE IF (CHAR=='I') THEN
- NORM=ZLANGE('I',N,N,M,N,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=ZLANGE('1',N,N,M,N,WORK)
- ELSE
- STOP'undefined matrix norm'
- END IF
+ CALL NORM_check_norm(CHAR)
+ NORM = ZLANGE(CHAR,N,N,M,N,WORK)
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the Frobenius norm, the infinity norm or the one norm of a symmetric matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
- IF (CHAR=='F') THEN
- NORM=DLANSP('F','U',N,PM,WORK)
- ELSE IF (CHAR=='I') THEN
- NORM=DLANSP('I','U',N,PM,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=DLANSP('1','U',N,PM,WORK)
- ELSE
- STOP'Function NORM: undefined matrix norm.'
- END IF
+ CALL NORM_check_norm(CHAR)
+ NORM = DLANSP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the Frobenius norm, the infinity norm or the one norm of a hermitian matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
- IF (CHAR=='F') THEN
- NORM=ZLANHP('F','U',N,PM,WORK)
- ELSE IF (CHAR=='I') THEN
- NORM=ZLANHP('I','U',N,PM,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=ZLANHP('1','U',N,PM,WORK)
- ELSE
- STOP'Function NORM: undefined matrix norm.'
- END IF
+ CALL NORM_check_norm(CHAR)
+ NORM = ZLANHP(CHAR,'U',N,PM,WORK)
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
+ USE random
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
function EXPONENTIAL_real(t,H,N) result(expH)
! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
! from http://fortranwiki.org/fortran/show/Expokit
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, intent(in) :: t
DOUBLE PRECISION, dimension(N,N), intent(in) :: H
DOUBLE PRECISION, dimension(N,N) :: expH
! Expokit variables
integer, parameter :: ideg = 6
DOUBLE PRECISION, dimension(4*N*N + ideg + 1) :: wsp
integer, dimension(N) :: iwsp
integer :: iexp, ns, iflag
call DGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
end function
function EXPONENTIAL_complex(t,H,N) result(expH)
! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
! from http://fortranwiki.org/fortran/show/Expokit
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, intent(in) :: t
DOUBLE COMPLEX, dimension(N,N), intent(in) :: H
DOUBLE COMPLEX, dimension(N,N) :: expH
! Expokit variables
external :: ZGPADM
integer, parameter :: ideg = 6
DOUBLE COMPLEX, dimension(4*N*N + ideg + 1) :: wsp
integer, dimension(N) :: iwsp
integer :: iexp, ns, iflag
call ZGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
end function
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a symmetric matrix of size N*N stored in packed format.
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a hermitian matrix of size N*N stored in packed format.
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,2E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_hermitian
END MODULE
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
ef51996cf4248151440b83df27c142debe772b95
|
Changed the tolerance in the sign function, tidied up the matrix_tools module
|
diff --git a/src/esa.f90 b/src/esa.f90
index e082d13..87dc100 100644
--- a/src/esa.f90
+++ b/src/esa.f90
@@ -1,282 +1,281 @@
MODULE esa_mod
USE basis_parameters
INTEGER,POINTER :: NBAST_P
DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_P,PTDM_P,PDMDIF_P
TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_P
CHARACTER,POINTER :: METHOD_P
CONTAINS
FUNCTION THETA(PDM,POEFM,N,PHI,METHOD) RESULT (PDMNEW)
! Function that computes the value of $\Theta(D)$ (with $D$ a hermitian matrix of size N, which upper triangular part is stored in packed form in PDM) with precision TOL (if the (geometrical) convergence of the fixed-point iterative sequence is attained), \Theta being the function defined in: A new definition of the Dirac-Fock ground state, Eric Séré, preprint (2009).
USE case_parameters ; USE basis_parameters ; USE matrices
USE matrix_tools ; USE metric_relativistic
USE debug
CHARACTER,INTENT(IN) :: METHOD
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDM,POEFM
TYPE(twospinor),DIMENSION(N),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDMNEW
INTEGER,PARAMETER :: ITERMAX=50
DOUBLE PRECISION,PARAMETER :: TOL=1.D-8
INTEGER :: ITER,INFO,LOON
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PTEFM,PFM,PDMOLD,PPROJM
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF
ITER=0
PDMOLD=PDM
IF (THETA_CHECK) THEN
WRITE(13,*)'tr(SD)=',REAL(TRACEOFPRODUCT(PS,PDM,N))
! PTMP=PDM ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO)
! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG
END IF
! Fixed-point iterative sequence
DO
ITER=ITER+1
! Projection of the current density matrix
CALL BUILDTEFM(PTEFM,N,PHI,PDMOLD)
PFM=POEFM+PTEFM
IF (METHOD=='D') THEN
! computation of the "positive" spectral projector associated to the Fock matrix based on the current density matrix via diagonalization
CALL EIGENSOLVER(PFM,PCFS,N,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 1
CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-C*C))
PDMNEW=ABCBA(PPROJM,PS,PDMOLD,N)
ELSE
! OR
! computation of the "positive" spectral projector via the sign function obtained by polynomial recursion
DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+C*C*PS,N)
TSF=TRANSPOSE(CONJG(SF))
PDMNEW=PACK((DM+MATMUL(DM,TSF)+MATMUL(SF,DM+MATMUL(DM,TSF)))/4.D0,N)
END IF
IF (THETA_CHECK) THEN
WRITE(13,*)'Iter #',ITER
WRITE(13,*)'tr(SPSDSP)=',REAL(TRACEOFPRODUCT(PS,PDMNEW,N))
! PTMP=PDMNEW ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO)
! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG
END IF
IF (THETA_CHECK) WRITE(13,*)'Residual =',NORM(ABA(PSRS,PDMNEW-PDMOLD,N),N,'I')
IF (NORM(PDMNEW-PDMOLD,N,'I')<TOL) THEN
IF (THETA_CHECK) THEN
WRITE(13,'(a,i3,a)')' Function THETA: convergence after ',ITER,' iteration(s).'
WRITE(13,*)ITER,NORM(PDMNEW-PDMOLD,N,'I')
END IF
RETURN
ELSE IF (ITER>=ITERMAX) THEN
WRITE(*,*)'Function THETA: no convergence after ',ITER,' iteration(s).'
IF (THETA_CHECK) THEN
WRITE(13,*)'Function THETA: no convergence after ',ITER,' iteration(s).'
WRITE(13,*)'Residual =',NORM(PDMNEW-PDMOLD,N,'I')
END IF
STOP
END IF
PDMOLD=PDMNEW
END DO
1 WRITE(*,*)'(called from subroutine THETA)'
END FUNCTION THETA
FUNCTION SIGN(PA,N) RESULT (SA)
! Function that computes the sign function of the hermitian matrix of a selfadjoint operator, which upper triangular part is stored in packed form, using a polynomial recursion (PINVS contains the inverse of the overlap matrix, which upper triangular part is stored in packed form).
! Note: the result is an unpacked matrix due to subsequent use.
USE matrix_tools ; USE metric_relativistic
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: SA
DOUBLE COMPLEX,DIMENSION(N,N) :: A,ISRS
INTEGER,PARAMETER :: ITERMAX=50
- DOUBLE PRECISION,PARAMETER :: TOL=1.D-8
+ DOUBLE PRECISION,PARAMETER :: TOL=1.D-15
INTEGER :: I,ITER
A=UNPACK(PA,N) ; ISRS=UNPACK(PISRS,N)
SA=MATMUL(UNPACK(PIS,N),A)/NORM(MATMUL(ISRS,MATMUL(A,ISRS)),N,'F')
ITER=0
DO
ITER=ITER+1
A=SA
SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0
IF (NORM(SA-A,N,'F')<TOL) THEN
-! WRITE(*,*)' Function SIGN: convergence after ',ITER,' iteration(s).'
RETURN
ELSE IF (ITER==ITERMAX) THEN
WRITE(*,*)'Function SIGN: no convergence after ',ITER,' iteration(s).'
STOP
END IF
END DO
END FUNCTION SIGN
END MODULE
FUNCTION DFE(LAMBDA) RESULT (ETOT)
USE common_functions ; USE matrices ; USE matrix_tools ; USE esa_mod
DOUBLE PRECISION,INTENT(IN) :: LAMBDA
DOUBLE PRECISION :: ETOT
DOUBLE COMPLEX,DIMENSION(NBAST_P*(NBAST_P+1)/2) :: PDM,PTEFM,PTMP
PDM=THETA(PTDM_P+LAMBDA*PDMDIF_P,POEFM_P,NBAST_P,PHI_P,METHOD_P)
CALL BUILDTEFM(PTEFM,NBAST_P,PHI_P,PDM)
ETOT=ENERGY(POEFM_P,PTEFM,PDM,NBAST_P)
END FUNCTION DFE
SUBROUTINE ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Eric Séré's Algorithm
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools
USE optimization_tools ; USE esa_mod
USE debug
INTEGER,INTENT(IN),TARGET :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
CHARACTER,TARGET :: METHOD
INTEGER :: ITER,LOON,INFO,I,NUM
DOUBLE PRECISION :: ALPHA,BETA,LAMBDA
DOUBLE PRECISION :: DPDUMMY,TOL
DOUBLE PRECISION :: ETOT,ETOT1,ETTOT,PDMDIFNORM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: PTDM,PDMDIF
LOGICAL :: NUMCONV
INTERFACE
DOUBLE PRECISION FUNCTION DFE(LAMBDA)
DOUBLE PRECISION,INTENT(IN) :: LAMBDA
END FUNCTION
END INTERFACE
! INITIALIZATIONS AND PRELIMINARIES
OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO)
READ(100,'(/,a)')METHOD
CLOSE(100)
IF (METHOD=='D') THEN
WRITE(*,*)'Function $Theta$ computed using diagonalization'
ELSE
WRITE(*,*)'Function $Theta$ computed using polynomial recursion'
END IF
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
! Pointer assignments
NBAST_P=>NBAST ; POEFM_P=>POEFM ; PTDM_P=>PTDM ; PDMDIF_P=>PDMDIF ; PHI_P=>PHI ; METHOD_P=>METHOD
ITER=0
TOL=1.D-4
PDM=(0.D0,0.D0) ; PTDM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/esaenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/esacrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/esacrit2.txt',STATUS='unknown',ACTION='write')
OPEN(19,FILE='plots/esaenrgyt.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 5
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! test ERIC
! PFM=POEFM+PTEFM
! CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
! CALL CHECKORB(EIG,NBAST,LOON)
! computation of the positive spectral projector associated to PFM
! CALL FORMDM(PTMP,EIGVEC,NBAST,LOON,NBAST)
! infinity norm of the commutator between PFM and its positive spectral projector
! WRITE(44,*)ITER,NORM(COMMUTATOR(POEFM+PTEFM,PTMP,PS,NBAST),NBAST,'I')
! fin test ERIC
! Computation of the pseudo density matrix
IF (THETA_CHECK) WRITE(13,*)'theta(D-~D)'
PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD)
PDMDIFNORM=NORM(ABA(PSRS,PDMDIF,NBAST),NBAST,'I')
WRITE(*,*)'Infinity norm of the difference D_{n-1}-~D_{n-2}=',PDMDIFNORM
IF (PDMDIFNORM<=TRSHLD) GO TO 2
BETA=REAL(TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST))
write(*,*)'beta=',beta
IF (BETA>0.D0) THEN
WRITE(*,*)'Warning: internal computation error (beta>0).'
GO TO 4
ELSE
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF)
ALPHA=REAL(TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST))
write(*,*)'alpha=',alpha
IF (ALPHA>0.D0) THEN
LAMBDA=-BETA/ALPHA
IF (LAMBDA<1.D0) THEN
WRITE(*,*)'lambda=',LAMBDA
! on peut raffiner avec la methode de la section doree (la fonction n'etant a priori pas quadratique), voir comment optimiser un peu cela...
! WRITE(*,*)'refinement using golden section search (',0.D0,',',LAMBDA,',',1.D0,')'
! DPDUMMY=GOLDEN(0.D0,LAMBDA,1.D0,DFE,TOL,LAMBDA)
IF (THETA_CHECK) WRITE(13,*)'theta(~D+s(D-~D))'
PTDM=THETA(PTDM+LAMBDA*PDMDIF,POEFM,NBAST,PHI,METHOD)
ELSE
WRITE(*,*)'lambda=1.'
IF (THETA_CHECK) WRITE(13,*)'theta(D)'
PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD)
END IF
ELSE IF (ALPHA<0.D0) THEN
WRITE(*,*)'lambda=1.'
IF (THETA_CHECK) WRITE(13,*)'theta(D)'
PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD)
ELSE
WRITE(*,*)'Warning: internal computation error (alpha=0).'
GO TO 4
END IF
END IF
! Trace of the pseudo density matrix
WRITE(*,*)'tr(tilde{D}_n)=',REAL(TRACE(ABA(PSRS,PTDM,NBAST),NBAST))
! Energy associated to the pseudo density matrix
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST)
WRITE(19,*)ETTOT
WRITE(*,*)'E(tilde{D}_n)=',ETTOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: convergence after',ITER,'iteration(s).'
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: no convergence after',ITER,'iteration(s).'
GO TO 6
4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: computation stopped after',ITER,'iteration(s).'
GO TO 6
5 WRITE(*,*)'(called from subroutine ESA)'
GO TO 7
6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
7 NULLIFY(NBAST_P,POEFM_P,PTDM_P,PDMDIF_P,PHI_P)
DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18) ; CLOSE(19)
END SUBROUTINE ESA
diff --git a/src/tools.f90 b/src/tools.f90
index 25c8a83..2bc08ba 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -1,983 +1,1026 @@
MODULE constants
DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0
END MODULE
MODULE random
CONTAINS
! call this once
SUBROUTINE INIT_RANDOM()
! initialises random generator
! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED
INTEGER :: i, n, clock
INTEGER, DIMENSION(:), ALLOCATABLE :: seed
CALL RANDOM_SEED(size = n)
ALLOCATE(seed(n))
CALL SYSTEM_CLOCK(COUNT=clock)
seed = clock + 37 * (/ (i - 1, i = 1, n) /)
CALL RANDOM_SEED(PUT = seed)
DEALLOCATE(seed)
END SUBROUTINE INIT_RANDOM
! returns an array of random numbers of size N in (0, 1)
FUNCTION GET_RANDOM(N) RESULT(r)
REAL, DIMENSION(N) :: r
INTEGER :: N
CALL RANDOM_NUMBER(r)
END FUNCTION get_random
END MODULE random
MODULE matrix_tools
INTERFACE PACK
MODULE PROCEDURE PACK_symmetric,PACK_hermitian
END INTERFACE
INTERFACE UNPACK
MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian
END INTERFACE
INTERFACE ABA
MODULE PROCEDURE ABA_symmetric,ABA_hermitian
END INTERFACE
INTERFACE ABCBA
MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian
END INTERFACE
INTERFACE ABC_CBA
MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian
END INTERFACE
INTERFACE FINNERPRODUCT
MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex
END INTERFACE
INTERFACE NORM
MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian
END INTERFACE
INTERFACE INVERSE
MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian
END INTERFACE
INTERFACE SQUARE_ROOT
MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian
END INTERFACE
+INTERFACE EXPONENTIAL
+ MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex
+END INTERFACE EXPONENTIAL
+
INTERFACE TRACE
MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian
END INTERFACE
INTERFACE TRACEOFPRODUCT
MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian
END INTERFACE
INTERFACE EIGENSOLVER
MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized
END INTERFACE
INTERFACE COMMUTATOR
MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian
END INTERFACE
-INTERFACE EXPONENTIAL
- MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex
-END INTERFACE EXPONENTIAL
-
INTERFACE PRINTMATRIX
MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian
END INTERFACE
CONTAINS
! handling of symmetric and hermitian matrices stored in packed form.
FUNCTION PACK_symmetric(A,N) RESULT (PA)
! Function that stores the upper triangular part of a symmetric matrix in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=A(I,J)
END DO
END DO
END FUNCTION PACK_symmetric
FUNCTION PACK_hermitian(A,N) RESULT (PA)
! Function that stores the upper triangular part of a hermitian matrix in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA
INTEGER :: IJ,I,J
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
PA(IJ)=A(I,J)
END DO
END DO
END FUNCTION PACK_hermitian
FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
+FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA)
+! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: N
+ DOUBLE PRECISION,INTENT(IN) :: T
+ DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A
+ DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA
+
+ INTEGER :: IEXP,NS,IFLAG
+ INTEGER,DIMENSION(N) :: IWSP
+ INTEGER,PARAMETER :: IDEG=6
+ DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP
+
+ CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
+ IF (IFLAG/=0) GO TO 1
+ EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
+ RETURN
+1 WRITE(*,*)'Subroutine DGPADM: there is a problem'
+ WRITE(*,*)'(called from function EXPONENTIAL)'
+ STOP
+END FUNCTION EXPONENTIAL_real
+
+FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA)
+! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/).
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: N
+ DOUBLE PRECISION,INTENT(IN) :: T
+ DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A
+ DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA
+
+ INTEGER :: IEXP,NS,IFLAG
+ INTEGER,DIMENSION(N) :: IWSP
+ INTEGER,PARAMETER :: IDEG=6
+ DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP
+
+ CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG)
+ IF (IFLAG/=0) GO TO 1
+ EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA))
+ RETURN
+1 WRITE(*,*)'Subroutine ZGPADM: there is a problem'
+ WRITE(*,*)'(called from function EXPONENTIAL)'
+ STOP
+END FUNCTION EXPONENTIAL_complex
+
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
-! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
+! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
-! Function that computes the Frobenius or infinity norm of a square real matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
+! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
-IF (CHAR=='F') THEN
+ IF (CHAR=='1') THEN
+ NORM=DLANGE('1',N,N,M,N,WORK)
+ ELSE IF (CHAR=='F') THEN
NORM=DLANGE('F',N,N,M,N,WORK)
ELSE IF (CHAR=='I') THEN
NORM=DLANGE('I',N,N,M,N,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=DLANGE('1',N,N,M,N,WORK)
ELSE
STOP'undefined matrix norm'
END IF
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
-! Function that computes the Frobenius or infinity norm of a square complex matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
+! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
-IF (CHAR=='F') THEN
+ IF (CHAR=='1') THEN
+ NORM=ZLANGE('1',N,N,M,N,WORK)
+ ELSE IF (CHAR=='F') THEN
NORM=ZLANGE('F',N,N,M,N,WORK)
ELSE IF (CHAR=='I') THEN
NORM=ZLANGE('I',N,N,M,N,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=ZLANGE('1',N,N,M,N,WORK)
ELSE
STOP'undefined matrix norm'
END IF
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
-! Function that returns the Frobenius norm, the infinity norm or the one norm of a symmetric matrix, which upper triangular part is stored in packed format.
+! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
- IF (CHAR=='F') THEN
+ IF (CHAR=='1') THEN
+ NORM=DLANSP('1','U',N,PM,WORK)
+ ELSE IF (CHAR=='F') THEN
NORM=DLANSP('F','U',N,PM,WORK)
ELSE IF (CHAR=='I') THEN
NORM=DLANSP('I','U',N,PM,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=DLANSP('1','U',N,PM,WORK)
ELSE
STOP'Function NORM: undefined matrix norm.'
END IF
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
-! Function that returns the Frobenius norm, the infinity norm or the one norm of a hermitian matrix, which upper triangular part is stored in packed format.
+! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
- IF (CHAR=='F') THEN
+ IF (CHAR=='1') THEN
+ NORM=ZLANHP('1','U',N,PM,WORK)
+ ELSE IF (CHAR=='F') THEN
NORM=ZLANHP('F','U',N,PM,WORK)
ELSE IF (CHAR=='I') THEN
NORM=ZLANHP('I','U',N,PM,WORK)
- ELSE IF (CHAR=='1') THEN
- NORM=ZLANHP('1','U',N,PM,WORK)
ELSE
STOP'Function NORM: undefined matrix norm.'
END IF
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
- INTEGER,INTENT(IN) :: N
- DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
- DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
- DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
- INTEGER,INTENT(OUT) :: INFO
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: N
+ DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
+ DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
+ DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
+ INTEGER,INTENT(OUT) :: INFO
- INTEGER :: I,NEIG
- DOUBLE PRECISION,DIMENSION(3*N) :: WORK
- DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
+ INTEGER :: I,NEIG
+ DOUBLE PRECISION,DIMENSION(3*N) :: WORK
+ DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
- AP=PA ; BP=PCFB
+ AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
- CALL DSPGST(1,'U',N,AP,BP,INFO)
- IF (INFO/=0) GO TO 1
- CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
- IF (INFO/=0) GO TO 2
+ CALL DSPGST(1,'U',N,AP,BP,INFO)
+ IF (INFO/=0) GO TO 1
+ CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
+ IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
- NEIG=N
- IF (INFO>0) NEIG=INFO-1
- DO I=1,NEIG
- CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
- END DO
- RETURN
+ NEIG=N
+ IF (INFO>0) NEIG=INFO-1
+ DO I=1,NEIG
+ CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
+ END DO
+ RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
- &of an intermediate tridiagonal form did not converge to zero'
+ &of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
- INTEGER,INTENT(IN) :: N
- DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
- DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
- DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
- INTEGER,INTENT(OUT) :: INFO
-
- INTEGER :: I,NEIG
- DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
- DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
- DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
-
- AP=PA ; BP=PCFB
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: N
+ DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
+ DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
+ DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
+ INTEGER,INTENT(OUT) :: INFO
+ INTEGER :: I,NEIG
+ DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
+ DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
+ DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
+
+ AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
- CALL ZHPGST(1,'U',N,AP,BP,INFO)
- IF (INFO/=0) GO TO 1
- CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
- IF (INFO/=0) GO TO 2
+ CALL ZHPGST(1,'U',N,AP,BP,INFO)
+ IF (INFO/=0) GO TO 1
+ CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
+ IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
- NEIG=N
- IF (INFO>0) NEIG=INFO-1
- DO I=1,NEIG
- CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
- END DO
- RETURN
+ NEIG=N
+ IF (INFO>0) NEIG=INFO-1
+ DO I=1,NEIG
+ CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
+ END DO
+ RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
- &of an intermediate tridiagonal form did not converge to zero'
+ &of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
-function EXPONENTIAL_real(t,H,N) result(expH)
-! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
-! from http://fortranwiki.org/fortran/show/Expokit
- INTEGER,INTENT(IN) :: N
- DOUBLE PRECISION, intent(in) :: t
- DOUBLE PRECISION, dimension(N,N), intent(in) :: H
- DOUBLE PRECISION, dimension(N,N) :: expH
-
- ! Expokit variables
- integer, parameter :: ideg = 6
- DOUBLE PRECISION, dimension(4*N*N + ideg + 1) :: wsp
- integer, dimension(N) :: iwsp
- integer :: iexp, ns, iflag
-
- call DGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
- expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
-end function
-
-function EXPONENTIAL_complex(t,H,N) result(expH)
-! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
-! from http://fortranwiki.org/fortran/show/Expokit
- INTEGER,INTENT(IN) :: N
- DOUBLE PRECISION, intent(in) :: t
- DOUBLE COMPLEX, dimension(N,N), intent(in) :: H
- DOUBLE COMPLEX, dimension(N,N) :: expH
-
- ! Expokit variables
- external :: ZGPADM
- integer, parameter :: ideg = 6
- DOUBLE COMPLEX, dimension(4*N*N + ideg + 1) :: wsp
- integer, dimension(N) :: iwsp
- integer :: iexp, ns, iflag
-
- call ZGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
- expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
-end function
-
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a symmetric matrix of size N*N stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a hermitian matrix of size N*N stored in packed format.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,2E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_hermitian
END MODULE
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
ee5826dedaae183189f1ce3f29348132c7834500
|
Set speed of light via scale factor
|
diff --git a/src/esa.f90 b/src/esa.f90
index eceefa7..e082d13 100644
--- a/src/esa.f90
+++ b/src/esa.f90
@@ -1,285 +1,282 @@
MODULE esa_mod
USE basis_parameters
INTEGER,POINTER :: NBAST_P
DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_P,PTDM_P,PDMDIF_P
TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_P
CHARACTER,POINTER :: METHOD_P
CONTAINS
FUNCTION THETA(PDM,POEFM,N,PHI,METHOD) RESULT (PDMNEW)
! Function that computes the value of $\Theta(D)$ (with $D$ a hermitian matrix of size N, which upper triangular part is stored in packed form in PDM) with precision TOL (if the (geometrical) convergence of the fixed-point iterative sequence is attained), \Theta being the function defined in: A new definition of the Dirac-Fock ground state, Eric Séré, preprint (2009).
USE case_parameters ; USE basis_parameters ; USE matrices
USE matrix_tools ; USE metric_relativistic
USE debug
CHARACTER,INTENT(IN) :: METHOD
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDM,POEFM
TYPE(twospinor),DIMENSION(N),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDMNEW
INTEGER,PARAMETER :: ITERMAX=50
DOUBLE PRECISION,PARAMETER :: TOL=1.D-8
INTEGER :: ITER,INFO,LOON
- DOUBLE PRECISION :: AC
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PTEFM,PFM,PDMOLD,PPROJM
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF
- AC=SCALING_FACTOR*C
-
ITER=0
PDMOLD=PDM
IF (THETA_CHECK) THEN
WRITE(13,*)'tr(SD)=',REAL(TRACEOFPRODUCT(PS,PDM,N))
! PTMP=PDM ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO)
! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG
END IF
! Fixed-point iterative sequence
DO
ITER=ITER+1
! Projection of the current density matrix
CALL BUILDTEFM(PTEFM,N,PHI,PDMOLD)
PFM=POEFM+PTEFM
IF (METHOD=='D') THEN
! computation of the "positive" spectral projector associated to the Fock matrix based on the current density matrix via diagonalization
CALL EIGENSOLVER(PFM,PCFS,N,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 1
- CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-AC*AC))
+ CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-C*C))
PDMNEW=ABCBA(PPROJM,PS,PDMOLD,N)
ELSE
! OR
! computation of the "positive" spectral projector via the sign function obtained by polynomial recursion
- DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+AC*AC*PS,N)
+ DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+C*C*PS,N)
TSF=TRANSPOSE(CONJG(SF))
PDMNEW=PACK((DM+MATMUL(DM,TSF)+MATMUL(SF,DM+MATMUL(DM,TSF)))/4.D0,N)
END IF
IF (THETA_CHECK) THEN
WRITE(13,*)'Iter #',ITER
WRITE(13,*)'tr(SPSDSP)=',REAL(TRACEOFPRODUCT(PS,PDMNEW,N))
! PTMP=PDMNEW ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO)
! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG
END IF
IF (THETA_CHECK) WRITE(13,*)'Residual =',NORM(ABA(PSRS,PDMNEW-PDMOLD,N),N,'I')
IF (NORM(PDMNEW-PDMOLD,N,'I')<TOL) THEN
IF (THETA_CHECK) THEN
WRITE(13,'(a,i3,a)')' Function THETA: convergence after ',ITER,' iteration(s).'
WRITE(13,*)ITER,NORM(PDMNEW-PDMOLD,N,'I')
END IF
RETURN
ELSE IF (ITER>=ITERMAX) THEN
WRITE(*,*)'Function THETA: no convergence after ',ITER,' iteration(s).'
IF (THETA_CHECK) THEN
WRITE(13,*)'Function THETA: no convergence after ',ITER,' iteration(s).'
WRITE(13,*)'Residual =',NORM(PDMNEW-PDMOLD,N,'I')
END IF
STOP
END IF
PDMOLD=PDMNEW
END DO
1 WRITE(*,*)'(called from subroutine THETA)'
END FUNCTION THETA
FUNCTION SIGN(PA,N) RESULT (SA)
! Function that computes the sign function of the hermitian matrix of a selfadjoint operator, which upper triangular part is stored in packed form, using a polynomial recursion (PINVS contains the inverse of the overlap matrix, which upper triangular part is stored in packed form).
! Note: the result is an unpacked matrix due to subsequent use.
USE matrix_tools ; USE metric_relativistic
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: SA
DOUBLE COMPLEX,DIMENSION(N,N) :: A,ISRS
INTEGER,PARAMETER :: ITERMAX=50
DOUBLE PRECISION,PARAMETER :: TOL=1.D-8
INTEGER :: I,ITER
A=UNPACK(PA,N) ; ISRS=UNPACK(PISRS,N)
SA=MATMUL(UNPACK(PIS,N),A)/NORM(MATMUL(ISRS,MATMUL(A,ISRS)),N,'F')
ITER=0
DO
ITER=ITER+1
A=SA
SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0
IF (NORM(SA-A,N,'F')<TOL) THEN
! WRITE(*,*)' Function SIGN: convergence after ',ITER,' iteration(s).'
RETURN
ELSE IF (ITER==ITERMAX) THEN
WRITE(*,*)'Function SIGN: no convergence after ',ITER,' iteration(s).'
STOP
END IF
END DO
END FUNCTION SIGN
END MODULE
FUNCTION DFE(LAMBDA) RESULT (ETOT)
USE common_functions ; USE matrices ; USE matrix_tools ; USE esa_mod
DOUBLE PRECISION,INTENT(IN) :: LAMBDA
DOUBLE PRECISION :: ETOT
DOUBLE COMPLEX,DIMENSION(NBAST_P*(NBAST_P+1)/2) :: PDM,PTEFM,PTMP
PDM=THETA(PTDM_P+LAMBDA*PDMDIF_P,POEFM_P,NBAST_P,PHI_P,METHOD_P)
CALL BUILDTEFM(PTEFM,NBAST_P,PHI_P,PDM)
ETOT=ENERGY(POEFM_P,PTEFM,PDM,NBAST_P)
END FUNCTION DFE
SUBROUTINE ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! Eric Séré's Algorithm
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools
USE optimization_tools ; USE esa_mod
USE debug
INTEGER,INTENT(IN),TARGET :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
CHARACTER,TARGET :: METHOD
INTEGER :: ITER,LOON,INFO,I,NUM
DOUBLE PRECISION :: ALPHA,BETA,LAMBDA
DOUBLE PRECISION :: DPDUMMY,TOL
DOUBLE PRECISION :: ETOT,ETOT1,ETTOT,PDMDIFNORM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: PTDM,PDMDIF
LOGICAL :: NUMCONV
INTERFACE
DOUBLE PRECISION FUNCTION DFE(LAMBDA)
DOUBLE PRECISION,INTENT(IN) :: LAMBDA
END FUNCTION
END INTERFACE
! INITIALIZATIONS AND PRELIMINARIES
OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ')
CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO)
READ(100,'(/,a)')METHOD
CLOSE(100)
IF (METHOD=='D') THEN
WRITE(*,*)'Function $Theta$ computed using diagonalization'
ELSE
WRITE(*,*)'Function $Theta$ computed using polynomial recursion'
END IF
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
! Pointer assignments
NBAST_P=>NBAST ; POEFM_P=>POEFM ; PTDM_P=>PTDM ; PDMDIF_P=>PDMDIF ; PHI_P=>PHI ; METHOD_P=>METHOD
ITER=0
TOL=1.D-4
PDM=(0.D0,0.D0) ; PTDM=(0.D0,0.D0)
ETOT1=0.D0
OPEN(16,FILE='plots/esaenrgy.txt',STATUS='unknown',ACTION='write')
OPEN(17,FILE='plots/esacrit1.txt',STATUS='unknown',ACTION='write')
OPEN(18,FILE='plots/esacrit2.txt',STATUS='unknown',ACTION='write')
OPEN(19,FILE='plots/esaenrgyt.txt',STATUS='unknown',ACTION='write')
! LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
PFM=POEFM+PTTEFM
CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 5
! Assembly of the density matrix according to the aufbau principle
CALL CHECKORB(EIG,NBAST,LOON)
PDM1=PDM
CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
! Computation of the energy associated to the density matrix
CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! test ERIC
! PFM=POEFM+PTEFM
! CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
! CALL CHECKORB(EIG,NBAST,LOON)
! computation of the positive spectral projector associated to PFM
! CALL FORMDM(PTMP,EIGVEC,NBAST,LOON,NBAST)
! infinity norm of the commutator between PFM and its positive spectral projector
! WRITE(44,*)ITER,NORM(COMMUTATOR(POEFM+PTEFM,PTMP,PS,NBAST),NBAST,'I')
! fin test ERIC
! Computation of the pseudo density matrix
IF (THETA_CHECK) WRITE(13,*)'theta(D-~D)'
PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD)
PDMDIFNORM=NORM(ABA(PSRS,PDMDIF,NBAST),NBAST,'I')
WRITE(*,*)'Infinity norm of the difference D_{n-1}-~D_{n-2}=',PDMDIFNORM
IF (PDMDIFNORM<=TRSHLD) GO TO 2
BETA=REAL(TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST))
write(*,*)'beta=',beta
IF (BETA>0.D0) THEN
WRITE(*,*)'Warning: internal computation error (beta>0).'
GO TO 4
ELSE
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF)
ALPHA=REAL(TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST))
write(*,*)'alpha=',alpha
IF (ALPHA>0.D0) THEN
LAMBDA=-BETA/ALPHA
IF (LAMBDA<1.D0) THEN
WRITE(*,*)'lambda=',LAMBDA
! on peut raffiner avec la methode de la section doree (la fonction n'etant a priori pas quadratique), voir comment optimiser un peu cela...
! WRITE(*,*)'refinement using golden section search (',0.D0,',',LAMBDA,',',1.D0,')'
! DPDUMMY=GOLDEN(0.D0,LAMBDA,1.D0,DFE,TOL,LAMBDA)
IF (THETA_CHECK) WRITE(13,*)'theta(~D+s(D-~D))'
PTDM=THETA(PTDM+LAMBDA*PDMDIF,POEFM,NBAST,PHI,METHOD)
ELSE
WRITE(*,*)'lambda=1.'
IF (THETA_CHECK) WRITE(13,*)'theta(D)'
PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD)
END IF
ELSE IF (ALPHA<0.D0) THEN
WRITE(*,*)'lambda=1.'
IF (THETA_CHECK) WRITE(13,*)'theta(D)'
PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD)
ELSE
WRITE(*,*)'Warning: internal computation error (alpha=0).'
GO TO 4
END IF
END IF
! Trace of the pseudo density matrix
WRITE(*,*)'tr(tilde{D}_n)=',REAL(TRACE(ABA(PSRS,PTDM,NBAST),NBAST))
! Energy associated to the pseudo density matrix
CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM)
ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST)
WRITE(19,*)ETTOT
WRITE(*,*)'E(tilde{D}_n)=',ETTOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: convergence after',ITER,'iteration(s).'
GO TO 6
3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: no convergence after',ITER,'iteration(s).'
GO TO 6
4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: computation stopped after',ITER,'iteration(s).'
GO TO 6
5 WRITE(*,*)'(called from subroutine ESA)'
GO TO 7
6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,'(i4,e22.14)')I,EIG(I)
END DO
CLOSE(9)
7 NULLIFY(NBAST_P,POEFM_P,PTDM_P,PDMDIF_P,PHI_P)
DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM)
CLOSE(16) ; CLOSE(17) ; CLOSE(18) ; CLOSE(19)
END SUBROUTINE ESA
diff --git a/src/matrices.f90 b/src/matrices.f90
index faa053f..9e13f65 100644
--- a/src/matrices.f90
+++ b/src/matrices.f90
@@ -1,699 +1,696 @@
SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON)
! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PDM=(0.D0,0.D0)
DO I=LOON,HOON
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
END DO
END SUBROUTINE FORMDM_relativistic
SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON)
! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PDM=0.D0
DO I=LOON,HOON
CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM)
END DO
END SUBROUTINE FORMDM_nonrelativistic
SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON)
! Assembly of the matrix of the projector on the "positive" space (i.e., the electronic states) associated to a Dirac-Fock Hamiltonian (only the upper triangular part of the matrix is stored in packed format).
INTEGER,INTENT(IN) :: NBAST,LOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PPROJM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
INTEGER :: I
PPROJM=(0.D0,0.D0)
DO I=0,NBAST-LOON
CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM)
END DO
END SUBROUTINE FORMPROJ
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POM=(0.D0,0.D0)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
POM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOM_relativistic
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J
DO J=1,NBAST
DO I=1,J
POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J))
END DO
END DO
END SUBROUTINE BUILDOM_nonrelativistic
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
DO J=1,NBAST
DO I=1,J
PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0
END DO
END DO
END SUBROUTINE BUILDKPFM_nonrelativistic
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: I,J,K,L,M,N
- DOUBLE PRECISION :: AC
DOUBLE COMPLEX :: TMP,VALUE
-
- AC=SCALING_FACTOR*C
-
+
POEFM=(0.D0,0.D0)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
DO N=1,NBN
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=1,NBAS(1)
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(1)
- VALUE=VALUE-AC*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) &
+ VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
- VALUE=VALUE-AC*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
+ VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), &
& DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
- VALUE=VALUE-AC*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
+ VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), &
& DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(2)
- VALUE=VALUE+AC*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) &
+ VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3))
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
- TMP=2.D0*AC*AC*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
+ TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
DO N=1,NBN
TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N))
END DO
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP
END DO
END DO
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOEFM_relativistic
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format).
USE data_parameters ; USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I,J,N
DOUBLE PRECISION :: VALUE
POEFM=0.D0
DO J=1,NBAST
DO I=1,J
VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0
DO N=1,NBN
VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N))
END DO
POEFM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SUBROUTINE BUILDOEFM_nonrelativistic
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM
TEFM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
! IF ((I==J).AND.(I==K).AND.(I==L)) THEN
! NO CONTRIBUTION
! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K))
! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN
! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN
! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I))
! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I))
! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN
! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K))
! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I))
ELSE
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_relativistic
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term.
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
TEFM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I)
TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J)
TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J)
TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I))
TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J))
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J))
TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I))
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J))
TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J))
TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I))
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I)
TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J)
TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K)
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K)
TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I)
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I)
TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K)
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K))
TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I))
TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J)
TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J)
TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I)
TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I)
TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L)
TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K)
TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L)
TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PTEFM=PACK(TEFM,NBAST)
END SUBROUTINE BUILDTEFM_RHF
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM
CM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(I,J)
ELSE
CM(I,J)=CM(I,J)+INTGRL*DM(K,L)
CM(K,L)=CM(K,L)+INTGRL*DM(I,J)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_relativistic
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
CM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
CM(I,I)=CM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(J,J)
CM(J,I)=CM(J,I)+INTGRL*DM(J,J)
CM(J,J)=CM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
CM(L,I)=CM(L,I)+INTGRL*DM(I,I)
CM(I,L)=CM(I,L)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
CM(I,I)=CM(I,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*DM(I,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(I,J)+DM(J,I))
CM(J,I)=CM(J,I)+INTGRL*(DM(J,I)+DM(I,J))
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(I,L)+DM(L,I))
CM(J,I)=CM(J,I)+INTGRL*(DM(I,L)+DM(L,I))
CM(I,L)=CM(I,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,I)=CM(L,I)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,L)+DM(L,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,L)+DM(L,J))
CM(J,L)=CM(J,L)+INTGRL*(DM(J,I)+DM(I,J))
CM(L,J)=CM(L,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,K)+DM(K,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,K)+DM(K,J))
CM(J,K)=CM(J,K)+INTGRL*(DM(J,I)+DM(I,J))
CM(K,J)=CM(K,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(K,K)
CM(J,I)=CM(J,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
CM(K,L)=CM(K,L)+INTGRL*DM(I,I)
CM(L,K)=CM(L,K)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(K,L)+DM(L,K))
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(K,L)+DM(L,K))
CM(J,I)=CM(J,I)+INTGRL*(DM(K,L)+DM(L,K))
CM(K,L)=CM(K,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,K)=CM(L,K)+INTGRL*(DM(I,J)+DM(J,I))
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_nonrelativistic
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM
EM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
ELSE
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_relativistic
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
EM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,J)
EM(J,I)=EM(J,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
EM(L,I)=EM(L,I)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(I,I)
EM(I,I)=EM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
EM(I,K)=EM(I,K)+INTGRL*DM(I,K)
EM(K,I)=EM(K,I)+INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*DM(I,I)
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(I,J)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
EM(I,I)=EM(I,I)+INTGRL*(DM(J,L)+DM(L,J))
EM(L,I)=EM(L,I)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(L,I)
EM(L,J)=EM(L,J)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(I,L)
EM(J,L)=EM(J,L)+INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
EM(J,J)=EM(J,J)+INTGRL*(DM(I,L)+DM(L,I))
EM(L,J)=EM(L,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(L,J)
EM(L,I)=EM(L,I)+INTGRL*DM(J,J)
EM(J,L)=EM(J,L)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(J,L)
EM(I,L)=EM(I,L)+INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
diff --git a/src/scf.f90 b/src/scf.f90
index 4bb60a2..40ab732 100644
--- a/src/scf.f90
+++ b/src/scf.f90
@@ -1,463 +1,460 @@
MODULE scf_tools
INTERFACE CHECKNUMCONV
MODULE PROCEDURE CHECKNUMCONV_relativistic,CHECKNUMCONV_AOCOSDHF,CHECKNUMCONV_RHF,CHECKNUMCONV_UHF
END INTERFACE
CONTAINS
SUBROUTINE CHECKORB(EIG,N,LOON)
! Subroutine that determines the number of the lowest and highest occupied electronic orbitals and checks if they are both in the spectral gap (in the relavistic case).
USE case_parameters ; USE data_parameters
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N),INTENT(IN) :: EIG
INTEGER,INTENT(IN) :: N
INTEGER,INTENT(OUT) :: LOON
INTEGER :: HGEN
- DOUBLE PRECISION :: AC
-
- AC=SCALING_FACTOR*C
! Determination of the number of the lowest occupied orbital (i.e., the one relative to the first eigenvalue associated to an electronic state in the gap)
- LOON=MINLOC(EIG,DIM=1,MASK=EIG>-AC*AC)
+ LOON=MINLOC(EIG,DIM=1,MASK=EIG>-C*C)
IF (LOON.EQ.0) THEN
STOP'Subroutine CHECKORB: no eigenvalue associated to an electronic state.'
ELSE
WRITE(*,'(a,i3,a,i3,a)')' Number of the lowest occupied electronic orbital = ',LOON,'(/',N,')'
IF (N-LOON.LT.NBE) THEN
WRITE(*,'(a)')' Subroutine CHECKORB: there are not enough eigenvalues associated to electronic states (',N-LOON,').'
STOP
END IF
! Determination of the number of the highest orbital relative to an eigenvalue associated to an electronic state in the gap
HGEN=MAXLOC(EIG,DIM=1,MASK=EIG<0.D0)
WRITE(*,'(a,i3)')' Number of eigenvalues associated to electronic states in the gap = ',HGEN-LOON+1
IF (HGEN-LOON+1.LT.NBE) THEN
WRITE(*,'(a,i2,a)')' Warning: there are less than ',NBE,' eigenvalues associated to electronic states in the gap.'
END IF
END IF
END SUBROUTINE CHECKORB
SUBROUTINE CHECKNUMCONV_relativistic(PDMN,PDMO,PFM,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock equations (restricted closed-shell Hartree-Fock and closed-shell Dirac-Hartree-Fock formalisms).
USE matrix_tools ; USE metric_relativistic
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMN,PDMO,PFM
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE COMPLEX,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMT
DOUBLE PRECISION,DIMENSION(N) :: WORK
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMN-PDMO,N)
WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
WRITE(17,'(e22.14)')FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFM,PDMN,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n),D_n] =',NORM(CMT,N,'I')
FNCMT=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n),D_n] =',FNCMT
WRITE(18,'(e22.14)')FNCMT
IF (FNCMT<=TRSHLD) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
WRITE(16,'(e22.14)')ETOTN
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_relativistic
SUBROUTINE CHECKNUMCONV_RHF(PDMN,PDMO,PFM,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock equations (restricted closed-shell Hartree-Fock formalism).
USE matrix_tools ; USE metric_nonrelativistic
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMN,PDMO,PFM
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE PRECISION,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMT
DOUBLE PRECISION,DIMENSION(N) :: WORK
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMN-PDMO,N)
WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
WRITE(17,'(e22.14)')FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFM,PDMN,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n),D_n] =',NORM(CMT,N,'I')
FNCMT=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n),D_n] =',FNCMT
WRITE(18,'(e22.14)')FNCMT
IF (FNCMT<=TRSHLD) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
WRITE(16,'(e22.14)')ETOTN
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_RHF
SUBROUTINE CHECKNUMCONV_UHF(PDMA,PDMB,PTDMO,PFMA,PFMB,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock type equations (unrestricted open-shell Hartree-Fock formalism).
USE matrix_tools ; USE metric_nonrelativistic
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMA,PDMB,PTDMO,PFMA,PFMB
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE PRECISION,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDN,FNCMTA,FNCMTB
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=ABA(PSRS,PDMA+PDMB-PTDMO,N)
WRITE(*,*)'Infinity norm of the difference D_n-D_{n-1} =',NORM(PDIFF,N,'I')
FNDFDN=NORM(PDIFF,N,'F')
WRITE(*,*)'Frobenius norm of the difference D_n-D_{n-1} =',FNDFDN
IF (FNDFDN<=TRSHLD) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMA,PDMA,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n^a),D_n^a] =',NORM(CMT,N,'I')
FNCMTA=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^a),D_n^a] =',FNCMTA
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMB,PDMB,PS,N),ISRS))
WRITE(*,*)'Infinity norm of the commutator [F(D_n^b),D_n^b] =',NORM(CMT,N,'I')
FNCMTB=NORM(CMT,N,'F')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^b),D_n^b] =',FNCMTB
IF ((FNCMTA<=TRSHLD).AND.(FNCMTB<=TRSHLD)) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_UHF
SUBROUTINE CHECKNUMCONV_AOCOSDHF(PDMCN,PDMON,PDMCO,PDMOO,PFMC,PFMO,N,ETOTN,ETOTO,TRSHLD,NUMCONV)
! Subroutine that checks several numerical convergence criteria for the SCF solutions of Hartree-Fock type equations (average-of-configuration open-shell Dirac-Hartree-Fock formalism).
USE matrix_tools ; USE metric_relativistic
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDMCN,PDMON,PDMCO,PDMOO,PFMC,PFMO
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,INTENT(IN) :: ETOTN,ETOTO,TRSHLD
LOGICAL,INTENT(OUT) :: NUMCONV
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDIFF
DOUBLE COMPLEX,DIMENSION(N,N) :: CMT,ISRS
DOUBLE PRECISION :: FNDFDNC,FNDFDNO,FNCMTC,FNCMTO
LOGICAL :: CONVD,CONVC
CONVD=.FALSE. ; CONVC=.FALSE.
PDIFF=PDMCN-PDMCO
FNDFDNC=NORM(PDIFF,N,'F')
WRITE(*,*)'Infinity norm of the difference D_n^c-DC_{n-1}^c =',NORM(PDIFF,N,'I')
WRITE(*,*)'Frobenius norm of the difference D_n^c-DC_{n-1}^c =',FNDFDNC
PDIFF=PDMON-PDMOO
FNDFDNO=NORM(PDIFF,N,'F')
WRITE(*,*)'Infinity norm of the difference D_n^o-DC_{n-1}^o =',NORM(PDIFF,N,'I')
WRITE(*,*)'Frobenius norm of the difference D_n^o-DC_{n-1}^o =',FNDFDNO
IF ((FNDFDNC<=TRSHLD).AND.(FNDFDNO<=TRSHLD)) CONVD=.TRUE.
ISRS=UNPACK(PISRS,N)
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMC,PDMCN,PS,N),ISRS))
FNCMTC=NORM(CMT,N,'F')
WRITE(*,*)'Infinity norm of the commutator [F(D_n^c),D_n^c] =',NORM(CMT,N,'I')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^c),D_n^c] =',FNCMTC
CMT=MATMUL(ISRS,MATMUL(COMMUTATOR(PFMO,PDMON,PS,N),ISRS))
FNCMTO=NORM(CMT,N,'F')
WRITE(*,*)'Infinity norm of the commutator [F(D_n^o),D_n^o] =',NORM(CMT,N,'I')
WRITE(*,*)'Frobenius norm of the commutator [F(D_n^o),D_n^o] =',FNCMTO
IF ((FNCMTC<=TRSHLD).AND.(FNCMTO<=TRSHLD)) CONVC=.TRUE.
! This criterion is not used to assert convergence
WRITE(*,*)'Difference of the energies E_n-E_{n-1} =',ETOTN-ETOTO
IF (CONVD.AND.CONVC) THEN
NUMCONV=.TRUE.
ELSE
NUMCONV=.FALSE.
END IF
END SUBROUTINE CHECKNUMCONV_AOCOSDHF
END MODULE
MODULE graphics_tools
INTERFACE DENSITY_POINTWISE_VALUE
MODULE PROCEDURE DENSITY_POINTWISE_VALUE_relativistic,DENSITY_POINTWISE_VALUE_nonrelativistic
END INTERFACE
INTERFACE EXPORT_DENSITY
MODULE PROCEDURE EXPORT_DENSITY_relativistic,EXPORT_DENSITY_nonrelativistic
END INTERFACE
CONTAINS
FUNCTION DENSITY_POINTWISE_VALUE_relativistic(PDM,PHI,NBAST,POINT) RESULT(VALUE)
! Function that computes the value of the electronic density associated to a given density matrix (only the upper triangular part of this matrix is stored in packed format) at a given point of space.
USE basis_parameters ; USE matrix_tools
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE PRECISION :: VALUE
INTEGER :: I
DOUBLE COMPLEX,DIMENSION(NBAST,2) :: POINTWISE_VALUES
DOUBLE COMPLEX,DIMENSION(2,2) :: MATRIX
DO I=1,NBAST
POINTWISE_VALUES(I,:)=TWOSPINOR_POINTWISE_VALUE(PHI(I),POINT)
END DO
MATRIX=MATMUL(TRANSPOSE(CONJG(POINTWISE_VALUES)),MATMUL(UNPACK(PDM,NBAST),POINTWISE_VALUES))
VALUE=REAL(MATRIX(1,1)+MATRIX(2,2))
END FUNCTION DENSITY_POINTWISE_VALUE_relativistic
FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic(PDM,PHI,NBAST,POINT) RESULT(VALUE)
! Function that computes the value of the electronic density associated to a given density matrix (only the upper triangular part of this matrix is stored in packed format) at a given point of space.
USE basis_parameters ; USE matrix_tools
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
DOUBLE PRECISION :: VALUE
INTEGER :: I
REAL(KIND=C_DOUBLE),DIMENSION(NBAST) :: POINTWISE_VALUES
DO I=1,NBAST
POINTWISE_VALUES(I)=GBF_POINTWISE_VALUE(PHI(I),POINT)
END DO
VALUE=DOT_PRODUCT(POINTWISE_VALUES,MATMUL(UNPACK(PDM,NBAST),POINTWISE_VALUES))
END FUNCTION DENSITY_POINTWISE_VALUE_nonrelativistic
SUBROUTINE EXPORT_DENSITY_relativistic(PDM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
USE basis_parameters ; USE data_parameters ; USE matrices
IMPLICIT NONE
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST,NPOINTS
DOUBLE PRECISION,INTENT(IN) :: RMIN,RMAX
CHARACTER(*),INTENT(IN) :: FILENAME
CHARACTER(*),INTENT(IN) :: FILEFORMAT
INTEGER :: I,J,K
DOUBLE PRECISION :: GRID_STEPSIZE
DOUBLE PRECISION,DIMENSION(3) :: X
IF (NPOINTS/=1) THEN
GRID_STEPSIZE=(RMAX-RMIN)/(NPOINTS-1)
ELSE
STOP
END IF
IF ((FILEFORMAT=='matlab').OR.(FILEFORMAT=='MATLAB')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME)
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
ELSE IF ((FILEFORMAT=='cube').OR.(FILEFORMAT=='CUBE')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME//'.cube')
WRITE(42,*)'CUBE FILE.'
WRITE(42,*)'OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z'
WRITE(42,*)NBN,RMIN,RMIN,RMIN
WRITE(42,*)NPOINTS,(RMAX-RMIN)/NPOINTS,0.D0,0.D0
WRITE(42,*)NPOINTS,0.D0,(RMAX-RMIN)/NPOINTS,0.D0
WRITE(42,*)NPOINTS,0.D0,0.D0,(RMAX-RMIN)/NPOINTS
DO I=1,NBN
WRITE(42,*)Z(I),0.D0,CENTER(:,I)
END DO
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
END IF
END SUBROUTINE EXPORT_DENSITY_relativistic
SUBROUTINE EXPORT_DENSITY_nonrelativistic(PDM,PHI,NBAST,RMIN,RMAX,NPOINTS,FILENAME,FILEFORMAT)
USE basis_parameters ; USE data_parameters ; USE matrices
IMPLICIT NONE
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,INTENT(IN) :: NBAST,NPOINTS
DOUBLE PRECISION,INTENT(IN) :: RMIN,RMAX
CHARACTER(*),INTENT(IN) :: FILENAME
CHARACTER(*),INTENT(IN) :: FILEFORMAT
INTEGER :: I,J,K
DOUBLE PRECISION :: GRID_STEPSIZE
DOUBLE PRECISION,DIMENSION(3) :: X
IF (NPOINTS/=1) THEN
GRID_STEPSIZE=(RMAX-RMIN)/(NPOINTS-1)
ELSE
STOP
END IF
IF ((FILEFORMAT=='matlab').OR.(FILEFORMAT=='MATLAB')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME)
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)X(:),DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
ELSE IF ((FILEFORMAT=='cube').OR.(FILEFORMAT=='CUBE')) THEN
OPEN(UNIT=42,FILE='plots/'//FILENAME//'.cube')
WRITE(42,*)'CUBE FILE.'
WRITE(42,*)'OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z'
WRITE(42,*)NBN,RMIN,RMIN,RMIN
WRITE(42,*)NPOINTS,(RMAX-RMIN)/NPOINTS,0.D0,0.D0
WRITE(42,*)NPOINTS,0.D0,(RMAX-RMIN)/NPOINTS,0.D0
WRITE(42,*)NPOINTS,0.D0,0.D0,(RMAX-RMIN)/NPOINTS
DO I=1,NBN
WRITE(42,*)Z(I),0.D0,CENTER(:,I)
END DO
DO I=0,NPOINTS-1
DO J=0,NPOINTS-1
DO K=0,NPOINTS-1
X(1)=RMIN+REAL(I)*GRID_STEPSIZE
X(2)=RMIN+REAL(J)*GRID_STEPSIZE
X(3)=RMIN+REAL(K)*GRID_STEPSIZE
WRITE(42,*)DENSITY_POINTWISE_VALUE(PDM,PHI,NBAST,X)
END DO
END DO
END DO
CLOSE(42)
END IF
END SUBROUTINE EXPORT_DENSITY_nonrelativistic
END MODULE
MODULE output
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ALL_EIG
INTERFACE OUTPUT_ITER
MODULE PROCEDURE OUTPUT_ITER_nonrelativistic,OUTPUT_ITER_relativistic
END INTERFACE OUTPUT_ITER
INTERFACE OUTPUT_FINALIZE
MODULE PROCEDURE OUTPUT_FINALIZE_nonrelativistic,OUTPUT_FINALIZE_relativistic
END INTERFACE OUTPUT_FINALIZE
CONTAINS
SUBROUTINE OUTPUT_ITER_relativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE scf_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
IF (ITER==1) ALLOCATE(ALL_EIG(NBAST,MAXITR))
ALL_EIG(:,ITER)=EIG
END SUBROUTINE OUTPUT_ITER_relativistic
SUBROUTINE OUTPUT_ITER_nonrelativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE scf_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
IF (ITER==1) ALLOCATE(ALL_EIG(NBAST,MAXITR))
ALL_EIG(:,ITER)=EIG
END SUBROUTINE OUTPUT_ITER_nonrelativistic
SUBROUTINE OUTPUT_FINALIZE_relativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE graphics_tools
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
OPEN(42,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,ITER
WRITE(42,*)ALL_EIG(:,I)
END DO
CLOSE(42)
DEALLOCATE(ALL_EIG)
CALL EXPORT_DENSITY(PDM,PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
END SUBROUTINE OUTPUT_FINALIZE_relativistic
SUBROUTINE OUTPUT_FINALIZE_nonrelativistic(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
USE basis_parameters ; USE graphics_tools
IMPLICIT NONE
INTEGER,INTENT(IN) :: ITER,NBAST
DOUBLE PRECISION,INTENT(IN) :: ETOT
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER :: I
OPEN(42,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,ITER
WRITE(42,*)ALL_EIG(:,I)
END DO
CLOSE(42)
DEALLOCATE(ALL_EIG)
CALL EXPORT_DENSITY(PDM,PHI,NBAST,-12.D0,12.D0,20,'density','matlab')
END SUBROUTINE OUTPUT_FINALIZE_nonrelativistic
END MODULE output
diff --git a/src/setup.f90 b/src/setup.f90
index 31aa0b9..e0bfd28 100644
--- a/src/setup.f90
+++ b/src/setup.f90
@@ -1,544 +1,545 @@
MODULE case_parameters
! relativistic or non-relativistic case flag
LOGICAL :: RELATIVISTIC
-! speed of light in the vacuum in atomic units (for the relativistic case)
-! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006.
- DOUBLE PRECISION :: C=137.035999967994D0
-! scaling factor for the study of the non-relativistic limit
- DOUBLE PRECISION :: SCALING_FACTOR
+! speed of light. Might be defined by the user via a scale factor
+ DOUBLE PRECISION :: C
! approximation index (1 is Hartree, 2 is Hartree-Fock)
INTEGER :: APPROXIMATION
! model/formalism index (see below)
INTEGER :: MODEL
CONTAINS
SUBROUTINE SETUP_CASE
USE setup_tools
+! speed of light in the vacuum in atomic units (for the relativistic case)
+! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006.
+ DOUBLE PRECISION,PARAMETER :: SPEED_OF_LIGHT=137.035999967994D0
+ DOUBLE PRECISION :: SCALING_FACTOR=1.D0
CHARACTER(2) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## CASE',INFO)
IF (INFO/=0) STOP
READ(100,'(a2)') CHAR
IF (CHAR=='RE') THEN
RELATIVISTIC=.TRUE.
WRITE(*,'(a)')' Relativistic case'
- CALL LOOKFOR(100,'## SPEED OF LIGHT',INFO)
+ CALL LOOKFOR(100,'## SPEED OF LIGHT SCALE FACTOR',INFO)
IF (INFO==0) THEN
- READ(100,*) C
+ READ(100,*) SCALING_FACTOR
END IF
+ C = SCALING_FACTOR*SPEED_OF_LIGHT
WRITE(*,'(a,f16.8)')' Speed of light c = ',C
- SCALING_FACTOR=1.D0
ELSE IF (CHAR=='NO') THEN
RELATIVISTIC=.FALSE.
WRITE(*,'(a)')' Non-relativistic case'
ELSE
WRITE(*,*)'Subroutine SETUP_CASE: error!'
STOP
END IF
CLOSE(100)
END SUBROUTINE SETUP_CASE
SUBROUTINE SETUP_APPROXIMATION
USE setup_tools
CHARACTER(12) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## APPROXIMATION',INFO)
IF (INFO/=0) STOP
READ(100,'(a12)') CHAR
IF (LEN_TRIM(CHAR)==7) THEN
APPROXIMATION=1
WRITE(*,'(a)')' Hartree approximation (Hartree product wave function)'
IF (RELATIVISTIC) STOP' This option is incompatible with the previous one (for the time being)'
ELSE IF (LEN_TRIM(CHAR)>7) THEN
APPROXIMATION=2
WRITE(*,'(a)')' Hartree-Fock approximation (Slater determinant wave function)'
ELSE
WRITE(*,*)'Subroutine SETUP_APPROXIMATION: error!'
STOP
END IF
CLOSE(100)
END SUBROUTINE SETUP_APPROXIMATION
SUBROUTINE SETUP_FORMALISM
USE setup_tools
CHARACTER(3) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## MODEL',INFO)
IF (INFO/=0) STOP
READ(100,'(a3)') CHAR
IF (RELATIVISTIC) THEN
IF (APPROXIMATION==2) THEN
IF (CHAR=='CSD') THEN
MODEL=1
WRITE(*,'(a)')' Closed-shell formalism'
ELSE IF (CHAR=='OSD') THEN
MODEL=2
WRITE(*,'(a)')' Average-of-configuration open-shell formalism'
ELSE
GO TO 1
END IF
END IF
ELSE
IF (APPROXIMATION==1) THEN
IF (CHAR=='BOS') THEN
! MODEL=1
WRITE(*,'(a)')' Boson star model (preliminary)'
ELSE
GO TO 1
END IF
ELSE IF (APPROXIMATION==2) THEN
IF (CHAR=='RHF') THEN
! Restricted (closed-shell) Hartree-Fock (RHF) formalism (doubly occupied orbitals)
MODEL=1
WRITE(*,'(a)')' Restricted (closed-shell) Hartree-Fock (RHF) formalism'
ELSE IF (CHAR=='UHF') THEN
! Unrestricted (open-shell) Hartree-Fock (UHF) formalism (different orbitals for different spins (DODS method))
! Reference: J. A. Pople and R. K. Nesbet, Self-consistent orbitals for radicals, J. Chem. Phys., 22(3), 571-572, 1954.
MODEL=2
WRITE(*,'(a)')' Unrestricted (open-shell) Hartree-Fock (UHF) formalism'
ELSE IF (CHAR=='ROH') THEN
! Restricted Open-shell Hartree-Fock (ROHF) formalism
! Reference: C. C. J. Roothaan, Self-consistent field theory for open shells of electronic systems, Rev. Modern Phys., 32(2), 179-185, 1960.
MODEL=3
WRITE(*,'(a)')' Restricted Open-shell Hartree-Fock (ROHF) formalism'
WRITE(*,*)'Option not implemented yet!'
STOP
ELSE
GO TO 1
END IF
END IF
END IF
CLOSE(100)
RETURN
1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!'
STOP
END SUBROUTINE SETUP_FORMALISM
END MODULE
MODULE data_parameters
USE iso_c_binding
! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS **
! number of nuclei in the molecular system (at most 10)
INTEGER :: NBN
! atomic numbers of the nuclei
INTEGER,DIMENSION(10) :: Z
! positions of the nucleii
DOUBLE PRECISION,DIMENSION(3,10) :: CENTER
! total number of electrons in the molecular system
INTEGER :: NBE
! total number of electrons in the closed shells (open-shell DHF formalism)
INTEGER :: NBECS
! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism)
INTEGER :: NBEOS,NBOOS
! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms)
INTEGER :: NBEA,NBEB
! internuclear repulsion energy
DOUBLE PRECISION :: INTERNUCLEAR_ENERGY
! ** DATA FOR BOSON STAR MODEL **
DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0
! mass
DOUBLE PRECISION :: MASS
! temperature
DOUBLE PRECISION :: TEMPERATURE
! exponent for the function defining the Tsallis-related entropy term
DOUBLE PRECISION :: MB
!
INTEGER,POINTER :: RANK_P
DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I
CONTAINS
SUBROUTINE SETUP_DATA
USE case_parameters ; USE setup_tools
IMPLICIT NONE
CHARACTER(30) :: NAME
INTEGER :: INFO,N
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN
CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- **** ---'
READ(100,*) NAME
READ(100,*) MASS
WRITE(*,'(a,f5.3)')' * Mass = ',MASS
READ(100,*) TEMPERATURE
WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE
READ(100,*) MB
WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB
WRITE(*,'(a)')' --- **** ---'
ELSE
CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- Molecular system ---'
READ(100,'(3/,a)')NAME
WRITE(*,'(a,a)')' ** NAME: ',NAME
READ(100,'(i2)') NBN
DO N=1,NBN
WRITE(*,'(a,i2)')' * Nucleus #',N
READ(100,*) Z(N),CENTER(:,N)
WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')'
WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N)
END DO
CALL INTERNUCLEAR_REPULSION_ENERGY
WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY
READ(100,'(i3)') NBE
WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE
IF (RELATIVISTIC) THEN
IF (MODEL==2) THEN
READ(100,'(3(i3))')NBECS,NBEOS,NBOOS
WRITE(*,'(a,i3)')' - number of closed shell electrons = ',NBECS
WRITE(*,'(a,i3)')' - number of open shell electrons = ',NBEOS
WRITE(*,'(a,i3)')' - number of open shell orbitals = ',NBOOS
IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons'
IF (NBOOS<=NBEOS) STOP' Problem with the number of open shell orbitals!'
END IF
ELSE
IF (MODEL==1) THEN
IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!'
ELSE IF (MODEL==2) THEN
READ(100,'(2(i3))')NBEA,NBEB
WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA
WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB
IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!'
! ELSE IF (MODEL==3) THEN
END IF
END IF
WRITE(*,'(a)')' --------- **** ---------'
END IF
CLOSE(100)
END SUBROUTINE SETUP_DATA
FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL)
! Function returning the symbol of a chemical element given its atomic number Z.
INTEGER,INTENT(IN) :: Z
CHARACTER(2) :: SYMBOL
IF (Z>104) THEN
WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!'
STOP
END IF
! List of symbols from Hydrogen up to Rutherfordium.
SELECT CASE (Z)
CASE (1) ; SYMBOL='H'
CASE (2) ; SYMBOL='He'
CASE (3) ; SYMBOL='Li'
CASE (4) ; SYMBOL='Be'
CASE (5) ; SYMBOL='B'
CASE (6) ; SYMBOL='C'
CASE (7) ; SYMBOL='N'
CASE (8) ; SYMBOL='O'
CASE (9) ; SYMBOL='F'
CASE (10) ; SYMBOL='Ne'
CASE (11) ; SYMBOL='Na'
CASE (12) ; SYMBOL='Mg'
CASE (13) ; SYMBOL='Al'
CASE (14) ; SYMBOL='Si'
CASE (15) ; SYMBOL='P'
CASE (16) ; SYMBOL='S'
CASE (17) ; SYMBOL='Cl'
CASE (18) ; SYMBOL='Ar'
CASE (19) ; SYMBOL='K'
CASE (20) ; SYMBOL='Ca'
CASE (21) ; SYMBOL='Sc'
CASE (22) ; SYMBOL='Ti'
CASE (23) ; SYMBOL='V'
CASE (24) ; SYMBOL='Cr'
CASE (25) ; SYMBOL='Mn'
CASE (26) ; SYMBOL='Fe'
CASE (27) ; SYMBOL='Co'
CASE (28) ; SYMBOL='Ni'
CASE (29) ; SYMBOL='Cu'
CASE (30) ; SYMBOL='Zn'
CASE (31) ; SYMBOL='Ga'
CASE (32) ; SYMBOL='Ge'
CASE (33) ; SYMBOL='As'
CASE (34) ; SYMBOL='Se'
CASE (35) ; SYMBOL='Br'
CASE (36) ; SYMBOL='Kr'
CASE (37) ; SYMBOL='Rb'
CASE (38) ; SYMBOL='Sr'
CASE (39) ; SYMBOL='Y'
CASE (40) ; SYMBOL='Zr'
CASE (41) ; SYMBOL='Nb'
CASE (42) ; SYMBOL='Mo'
CASE (43) ; SYMBOL='Tc'
CASE (44) ; SYMBOL='Ru'
CASE (45) ; SYMBOL='Rh'
CASE (46) ; SYMBOL='Pd'
CASE (47) ; SYMBOL='Ag'
CASE (48) ; SYMBOL='Cd'
CASE (49) ; SYMBOL='In'
CASE (50) ; SYMBOL='Sn'
CASE (51) ; SYMBOL='Sb'
CASE (52) ; SYMBOL='Te'
CASE (53) ; SYMBOL='I'
CASE (54) ; SYMBOL='Xe'
CASE (55) ; SYMBOL='Cs'
CASE (56) ; SYMBOL='Ba'
CASE (57) ; SYMBOL='La'
! Lanthanide elements (lanthanoids)
CASE (58) ; SYMBOL='Ce'
CASE (59) ; SYMBOL='Pr'
CASE (60) ; SYMBOL='Nd'
CASE (61) ; SYMBOL='Pm'
CASE (62) ; SYMBOL='Sm'
CASE (63) ; SYMBOL='Eu'
CASE (64) ; SYMBOL='Gd'
CASE (65) ; SYMBOL='Tb'
CASE (66) ; SYMBOL='Dy'
CASE (67) ; SYMBOL='Ho'
CASE (68) ; SYMBOL='Er'
CASE (69) ; SYMBOL='Tm'
CASE (70) ; SYMBOL='Yb'
CASE (71) ; SYMBOL='Lu'
CASE (72) ; SYMBOL='Hf'
CASE (73) ; SYMBOL='Ta'
CASE (74) ; SYMBOL='W'
CASE (75) ; SYMBOL='Re'
CASE (76) ; SYMBOL='Os'
CASE (77) ; SYMBOL='Ir'
CASE (78) ; SYMBOL='Pt'
CASE (79) ; SYMBOL='Au'
CASE (80) ; SYMBOL='Hg'
CASE (81) ; SYMBOL='Tl'
CASE (82) ; SYMBOL='Pb'
CASE (83) ; SYMBOL='Bi'
CASE (84) ; SYMBOL='Po'
CASE (85) ; SYMBOL='As'
CASE (86) ; SYMBOL='Rn'
CASE (87) ; SYMBOL='Fr'
CASE (88) ; SYMBOL='Ra'
CASE (89) ; SYMBOL='Ac'
! Actinide elements (actinoids)
CASE (90) ; SYMBOL='Th'
CASE (91) ; SYMBOL='Pa'
CASE (92) ; SYMBOL='U'
CASE (93) ; SYMBOL='Np'
CASE (94) ; SYMBOL='Pu'
CASE (95) ; SYMBOL='Am'
CASE (96) ; SYMBOL='Cm'
CASE (97) ; SYMBOL='Bk'
CASE (98) ; SYMBOL='Cf'
CASE (99) ; SYMBOL='Es'
CASE (100); SYMBOL='Fm'
CASE (101); SYMBOL='Md'
CASE (102); SYMBOL='No'
CASE (103); SYMBOL='Lr'
CASE (104); SYMBOL='Rf'
END SELECT
END FUNCTION IDENTIFYZ
SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system.
INTEGER :: I,J
DOUBLE PRECISION,DIMENSION(3) :: DIFF
INTERNUCLEAR_ENERGY=0.D0
DO I=1,NBN
DO J=I+1,NBN
DIFF=CENTER(:,I)-CENTER(:,J)
INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF))
END DO
END DO
END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Various functions for the Hartree model with temperature
FUNCTION POSITIVE_PART(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
FUNC=0.D0
ELSE
FUNC=X
END IF
END FUNCTION POSITIVE_PART
FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC)
! beta test function for the entropy
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
FUNC=POSITIVE_PART(X)**MB/MB
END FUNCTION ENTROPY_FUNCTION
FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE
FUNC=X**(1.D0/(MB-1.D0))
END IF
END FUNCTION RECIP_DENTFUNC
FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE IF (X==0.D0) THEN
STOP'No derivative at origin'
ELSE
FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0)
END IF
END FUNCTION
FUNCTION FUNCFORMU(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
INTEGER :: I
DOUBLE PRECISION :: Y
FUNC=-MASS
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
IF (Y>=0.D0) THEN
FUNC=FUNC+RECIP_DENTFUNC(Y)
END IF
END DO
END FUNCTION FUNCFORMU
SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV
INTEGER :: I
DOUBLE PRECISION :: Y
FVAL=-MASS ; FDERIV=0.D0
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
FVAL=FVAL+RECIP_DENTFUNC(Y)
FDERIV=FDERIV+DRECIP_DENTFUNC(Y)
END DO
END SUBROUTINE RDENTFUNCD
END MODULE
MODULE basis_parameters
USE iso_c_binding
! flag for the choice of the basis set type (either existing in the library or even-tempered)
LOGICAL :: LIBRARY
! PARAMETERS FOR A GIVEN BASIS SET
CHARACTER(26) :: BASISFILE
INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4
! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme.
! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET
INTEGER :: NUMBER_OF_TERMS
DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO
! Various flags for the contraction of the primitives and the Kinetic Balance scheme
LOGICAL :: UNCONT
LOGICAL :: KINBAL,UKB
TYPE gaussianbasisfunction
! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function.
! nbrofexponents: the number of different gaussian primitives present in the contraction
! center: coordinates (x,y,z) of the center of the basis function
! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center)
! exponents: array containing the exponent of each of the gaussian primitives present in the contraction
! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction
! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives
! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance).
INTEGER(KIND=C_INT) :: nbrofexponents
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center
INTEGER :: center_id
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree
END TYPE gaussianbasisfunction
TYPE twospinor
! Definition of a Pauli 2-spinor type basis function using gaussian basis functions.
! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor
! contractions: array containing the contractions present in each of the components of the 2-spinor
! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes)
! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor
! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0
INTEGER,DIMENSION(2) :: nbrofcontractions
TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions
INTEGER,DIMENSION(2,MNOGBF) :: contidx
DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients
END TYPE twospinor
CONTAINS
SUBROUTINE SETUP_BASIS
USE case_parameters ; USE setup_tools
CHARACTER(LEN=4) :: CHAR
CHARACTER(LEN=26) :: BASISNAME
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## BASIS DEFINITION',INFO)
IF (INFO/=0) STOP
READ(100,'(3/,a)') BASISNAME
IF (BASISNAME(1:6)=='BASIS ') THEN
! The basis set is an existing one in the basis library
LIBRARY=.TRUE.
BASISFILE='basis/'//BASISNAME(7:)
READ(100,'(a4)') CHAR
IF (CHAR=='UNCO') THEN
UNCONT=.TRUE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)'
ELSE
UNCONT=.FALSE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)'
END IF
ELSE IF (BASISNAME(1:4)=='EVEN') THEN
! The basis set is an even-tempered one
LIBRARY=.FALSE.
IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)'
WRITE(*,'(a)')' Even-tempered basis set (preliminary support)'
READ(100,'(i4)') NUMBER_OF_TERMS
WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS
READ(100,*) FIRST_TERM
WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM
READ(100,*) COMMON_RATIO
WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO
ELSE
STOP' Unknown basis set type'
END IF
IF (RELATIVISTIC) THEN
READ(100,'(a2)') CHAR
IF (CHAR=='KI') THEN
KINBAL=.TRUE.
READ(100,'(a4)') CHAR
IF (CHAR=='REST') THEN
UKB=.FALSE.
WRITE(*,'(a)')' Restricted kinetic balance'
ELSE
UKB=.TRUE.
WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance'
END IF
ELSE
KINBAL=.FALSE.
WRITE(*,'(a)')' No kinetic balance'
END IF
END IF
CLOSE(100)
END SUBROUTINE SETUP_BASIS
FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE)
! Function that computes the value of a gaussian basis function at a given point of space.
USE iso_c_binding
TYPE(gaussianbasisfunction),INTENT(IN) :: GBF
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) &
& *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), &
& EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2)))
|
antoine-levitt/ACCQUAREL
|
a623128e12d2d126efa0dd461ca65cc6798732a1
|
Allow speed of light to be changed in setup file
|
diff --git a/src/setup.f90 b/src/setup.f90
index 73eb667..31aa0b9 100644
--- a/src/setup.f90
+++ b/src/setup.f90
@@ -1,538 +1,542 @@
MODULE case_parameters
! relativistic or non-relativistic case flag
LOGICAL :: RELATIVISTIC
! speed of light in the vacuum in atomic units (for the relativistic case)
! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006.
- DOUBLE PRECISION,PARAMETER :: C=137.035999967994D0
+ DOUBLE PRECISION :: C=137.035999967994D0
! scaling factor for the study of the non-relativistic limit
DOUBLE PRECISION :: SCALING_FACTOR
! approximation index (1 is Hartree, 2 is Hartree-Fock)
INTEGER :: APPROXIMATION
! model/formalism index (see below)
INTEGER :: MODEL
CONTAINS
SUBROUTINE SETUP_CASE
USE setup_tools
CHARACTER(2) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## CASE',INFO)
IF (INFO/=0) STOP
READ(100,'(a2)') CHAR
IF (CHAR=='RE') THEN
RELATIVISTIC=.TRUE.
WRITE(*,'(a)')' Relativistic case'
+ CALL LOOKFOR(100,'## SPEED OF LIGHT',INFO)
+ IF (INFO==0) THEN
+ READ(100,*) C
+ END IF
WRITE(*,'(a,f16.8)')' Speed of light c = ',C
SCALING_FACTOR=1.D0
ELSE IF (CHAR=='NO') THEN
RELATIVISTIC=.FALSE.
WRITE(*,'(a)')' Non-relativistic case'
ELSE
WRITE(*,*)'Subroutine SETUP_CASE: error!'
STOP
END IF
CLOSE(100)
END SUBROUTINE SETUP_CASE
SUBROUTINE SETUP_APPROXIMATION
USE setup_tools
CHARACTER(12) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## APPROXIMATION',INFO)
IF (INFO/=0) STOP
READ(100,'(a12)') CHAR
IF (LEN_TRIM(CHAR)==7) THEN
APPROXIMATION=1
WRITE(*,'(a)')' Hartree approximation (Hartree product wave function)'
IF (RELATIVISTIC) STOP' This option is incompatible with the previous one (for the time being)'
ELSE IF (LEN_TRIM(CHAR)>7) THEN
APPROXIMATION=2
WRITE(*,'(a)')' Hartree-Fock approximation (Slater determinant wave function)'
ELSE
WRITE(*,*)'Subroutine SETUP_APPROXIMATION: error!'
STOP
END IF
CLOSE(100)
END SUBROUTINE SETUP_APPROXIMATION
SUBROUTINE SETUP_FORMALISM
USE setup_tools
CHARACTER(3) :: CHAR
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## MODEL',INFO)
IF (INFO/=0) STOP
READ(100,'(a3)') CHAR
IF (RELATIVISTIC) THEN
IF (APPROXIMATION==2) THEN
IF (CHAR=='CSD') THEN
MODEL=1
WRITE(*,'(a)')' Closed-shell formalism'
ELSE IF (CHAR=='OSD') THEN
MODEL=2
WRITE(*,'(a)')' Average-of-configuration open-shell formalism'
ELSE
GO TO 1
END IF
END IF
ELSE
IF (APPROXIMATION==1) THEN
IF (CHAR=='BOS') THEN
! MODEL=1
WRITE(*,'(a)')' Boson star model (preliminary)'
ELSE
GO TO 1
END IF
ELSE IF (APPROXIMATION==2) THEN
IF (CHAR=='RHF') THEN
! Restricted (closed-shell) Hartree-Fock (RHF) formalism (doubly occupied orbitals)
MODEL=1
WRITE(*,'(a)')' Restricted (closed-shell) Hartree-Fock (RHF) formalism'
ELSE IF (CHAR=='UHF') THEN
! Unrestricted (open-shell) Hartree-Fock (UHF) formalism (different orbitals for different spins (DODS method))
! Reference: J. A. Pople and R. K. Nesbet, Self-consistent orbitals for radicals, J. Chem. Phys., 22(3), 571-572, 1954.
MODEL=2
WRITE(*,'(a)')' Unrestricted (open-shell) Hartree-Fock (UHF) formalism'
ELSE IF (CHAR=='ROH') THEN
! Restricted Open-shell Hartree-Fock (ROHF) formalism
! Reference: C. C. J. Roothaan, Self-consistent field theory for open shells of electronic systems, Rev. Modern Phys., 32(2), 179-185, 1960.
MODEL=3
WRITE(*,'(a)')' Restricted Open-shell Hartree-Fock (ROHF) formalism'
WRITE(*,*)'Option not implemented yet!'
STOP
ELSE
GO TO 1
END IF
END IF
END IF
CLOSE(100)
RETURN
1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!'
STOP
END SUBROUTINE SETUP_FORMALISM
END MODULE
MODULE data_parameters
USE iso_c_binding
! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS **
! number of nuclei in the molecular system (at most 10)
INTEGER :: NBN
! atomic numbers of the nuclei
INTEGER,DIMENSION(10) :: Z
! positions of the nucleii
DOUBLE PRECISION,DIMENSION(3,10) :: CENTER
! total number of electrons in the molecular system
INTEGER :: NBE
! total number of electrons in the closed shells (open-shell DHF formalism)
INTEGER :: NBECS
! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism)
INTEGER :: NBEOS,NBOOS
! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms)
INTEGER :: NBEA,NBEB
! internuclear repulsion energy
DOUBLE PRECISION :: INTERNUCLEAR_ENERGY
! ** DATA FOR BOSON STAR MODEL **
DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0
! mass
DOUBLE PRECISION :: MASS
! temperature
DOUBLE PRECISION :: TEMPERATURE
! exponent for the function defining the Tsallis-related entropy term
DOUBLE PRECISION :: MB
!
INTEGER,POINTER :: RANK_P
DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I
CONTAINS
SUBROUTINE SETUP_DATA
USE case_parameters ; USE setup_tools
IMPLICIT NONE
CHARACTER(30) :: NAME
INTEGER :: INFO,N
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN
CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- **** ---'
READ(100,*) NAME
READ(100,*) MASS
WRITE(*,'(a,f5.3)')' * Mass = ',MASS
READ(100,*) TEMPERATURE
WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE
READ(100,*) MB
WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB
WRITE(*,'(a)')' --- **** ---'
ELSE
CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO)
IF (INFO/=0) STOP
WRITE(*,'(a)')' --- Molecular system ---'
READ(100,'(3/,a)')NAME
WRITE(*,'(a,a)')' ** NAME: ',NAME
READ(100,'(i2)') NBN
DO N=1,NBN
WRITE(*,'(a,i2)')' * Nucleus #',N
READ(100,*) Z(N),CENTER(:,N)
WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')'
WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N)
END DO
CALL INTERNUCLEAR_REPULSION_ENERGY
WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY
READ(100,'(i3)') NBE
WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE
IF (RELATIVISTIC) THEN
IF (MODEL==2) THEN
READ(100,'(3(i3))')NBECS,NBEOS,NBOOS
WRITE(*,'(a,i3)')' - number of closed shell electrons = ',NBECS
WRITE(*,'(a,i3)')' - number of open shell electrons = ',NBEOS
WRITE(*,'(a,i3)')' - number of open shell orbitals = ',NBOOS
IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons'
IF (NBOOS<=NBEOS) STOP' Problem with the number of open shell orbitals!'
END IF
ELSE
IF (MODEL==1) THEN
IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!'
ELSE IF (MODEL==2) THEN
READ(100,'(2(i3))')NBEA,NBEB
WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA
WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB
IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!'
! ELSE IF (MODEL==3) THEN
END IF
END IF
WRITE(*,'(a)')' --------- **** ---------'
END IF
CLOSE(100)
END SUBROUTINE SETUP_DATA
FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL)
! Function returning the symbol of a chemical element given its atomic number Z.
INTEGER,INTENT(IN) :: Z
CHARACTER(2) :: SYMBOL
IF (Z>104) THEN
WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!'
STOP
END IF
! List of symbols from Hydrogen up to Rutherfordium.
SELECT CASE (Z)
CASE (1) ; SYMBOL='H'
CASE (2) ; SYMBOL='He'
CASE (3) ; SYMBOL='Li'
CASE (4) ; SYMBOL='Be'
CASE (5) ; SYMBOL='B'
CASE (6) ; SYMBOL='C'
CASE (7) ; SYMBOL='N'
CASE (8) ; SYMBOL='O'
CASE (9) ; SYMBOL='F'
CASE (10) ; SYMBOL='Ne'
CASE (11) ; SYMBOL='Na'
CASE (12) ; SYMBOL='Mg'
CASE (13) ; SYMBOL='Al'
CASE (14) ; SYMBOL='Si'
CASE (15) ; SYMBOL='P'
CASE (16) ; SYMBOL='S'
CASE (17) ; SYMBOL='Cl'
CASE (18) ; SYMBOL='Ar'
CASE (19) ; SYMBOL='K'
CASE (20) ; SYMBOL='Ca'
CASE (21) ; SYMBOL='Sc'
CASE (22) ; SYMBOL='Ti'
CASE (23) ; SYMBOL='V'
CASE (24) ; SYMBOL='Cr'
CASE (25) ; SYMBOL='Mn'
CASE (26) ; SYMBOL='Fe'
CASE (27) ; SYMBOL='Co'
CASE (28) ; SYMBOL='Ni'
CASE (29) ; SYMBOL='Cu'
CASE (30) ; SYMBOL='Zn'
CASE (31) ; SYMBOL='Ga'
CASE (32) ; SYMBOL='Ge'
CASE (33) ; SYMBOL='As'
CASE (34) ; SYMBOL='Se'
CASE (35) ; SYMBOL='Br'
CASE (36) ; SYMBOL='Kr'
CASE (37) ; SYMBOL='Rb'
CASE (38) ; SYMBOL='Sr'
CASE (39) ; SYMBOL='Y'
CASE (40) ; SYMBOL='Zr'
CASE (41) ; SYMBOL='Nb'
CASE (42) ; SYMBOL='Mo'
CASE (43) ; SYMBOL='Tc'
CASE (44) ; SYMBOL='Ru'
CASE (45) ; SYMBOL='Rh'
CASE (46) ; SYMBOL='Pd'
CASE (47) ; SYMBOL='Ag'
CASE (48) ; SYMBOL='Cd'
CASE (49) ; SYMBOL='In'
CASE (50) ; SYMBOL='Sn'
CASE (51) ; SYMBOL='Sb'
CASE (52) ; SYMBOL='Te'
CASE (53) ; SYMBOL='I'
CASE (54) ; SYMBOL='Xe'
CASE (55) ; SYMBOL='Cs'
CASE (56) ; SYMBOL='Ba'
CASE (57) ; SYMBOL='La'
! Lanthanide elements (lanthanoids)
CASE (58) ; SYMBOL='Ce'
CASE (59) ; SYMBOL='Pr'
CASE (60) ; SYMBOL='Nd'
CASE (61) ; SYMBOL='Pm'
CASE (62) ; SYMBOL='Sm'
CASE (63) ; SYMBOL='Eu'
CASE (64) ; SYMBOL='Gd'
CASE (65) ; SYMBOL='Tb'
CASE (66) ; SYMBOL='Dy'
CASE (67) ; SYMBOL='Ho'
CASE (68) ; SYMBOL='Er'
CASE (69) ; SYMBOL='Tm'
CASE (70) ; SYMBOL='Yb'
CASE (71) ; SYMBOL='Lu'
CASE (72) ; SYMBOL='Hf'
CASE (73) ; SYMBOL='Ta'
CASE (74) ; SYMBOL='W'
CASE (75) ; SYMBOL='Re'
CASE (76) ; SYMBOL='Os'
CASE (77) ; SYMBOL='Ir'
CASE (78) ; SYMBOL='Pt'
CASE (79) ; SYMBOL='Au'
CASE (80) ; SYMBOL='Hg'
CASE (81) ; SYMBOL='Tl'
CASE (82) ; SYMBOL='Pb'
CASE (83) ; SYMBOL='Bi'
CASE (84) ; SYMBOL='Po'
CASE (85) ; SYMBOL='As'
CASE (86) ; SYMBOL='Rn'
CASE (87) ; SYMBOL='Fr'
CASE (88) ; SYMBOL='Ra'
CASE (89) ; SYMBOL='Ac'
! Actinide elements (actinoids)
CASE (90) ; SYMBOL='Th'
CASE (91) ; SYMBOL='Pa'
CASE (92) ; SYMBOL='U'
CASE (93) ; SYMBOL='Np'
CASE (94) ; SYMBOL='Pu'
CASE (95) ; SYMBOL='Am'
CASE (96) ; SYMBOL='Cm'
CASE (97) ; SYMBOL='Bk'
CASE (98) ; SYMBOL='Cf'
CASE (99) ; SYMBOL='Es'
CASE (100); SYMBOL='Fm'
CASE (101); SYMBOL='Md'
CASE (102); SYMBOL='No'
CASE (103); SYMBOL='Lr'
CASE (104); SYMBOL='Rf'
END SELECT
END FUNCTION IDENTIFYZ
SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system.
INTEGER :: I,J
DOUBLE PRECISION,DIMENSION(3) :: DIFF
INTERNUCLEAR_ENERGY=0.D0
DO I=1,NBN
DO J=I+1,NBN
DIFF=CENTER(:,I)-CENTER(:,J)
INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF))
END DO
END DO
END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY
! Various functions for the Hartree model with temperature
FUNCTION POSITIVE_PART(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
FUNC=0.D0
ELSE
FUNC=X
END IF
END FUNCTION POSITIVE_PART
FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC)
! beta test function for the entropy
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
FUNC=POSITIVE_PART(X)**MB/MB
END FUNCTION ENTROPY_FUNCTION
FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE
FUNC=X**(1.D0/(MB-1.D0))
END IF
END FUNCTION RECIP_DENTFUNC
FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
IF (X<0.D0) THEN
STOP'beta is not a bijection on R_-'
ELSE IF (X==0.D0) THEN
STOP'No derivative at origin'
ELSE
FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0)
END IF
END FUNCTION
FUNCTION FUNCFORMU(X) RESULT(FUNC)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION :: FUNC
INTEGER :: I
DOUBLE PRECISION :: Y
FUNC=-MASS
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
IF (Y>=0.D0) THEN
FUNC=FUNC+RECIP_DENTFUNC(Y)
END IF
END DO
END FUNCTION FUNCFORMU
SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV)
DOUBLE PRECISION,INTENT(IN) :: X
DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV
INTEGER :: I
DOUBLE PRECISION :: Y
FVAL=-MASS ; FDERIV=0.D0
DO I=1,RANK_P
Y=(X-MU_I(I))/TEMPERATURE
FVAL=FVAL+RECIP_DENTFUNC(Y)
FDERIV=FDERIV+DRECIP_DENTFUNC(Y)
END DO
END SUBROUTINE RDENTFUNCD
END MODULE
MODULE basis_parameters
USE iso_c_binding
! flag for the choice of the basis set type (either existing in the library or even-tempered)
LOGICAL :: LIBRARY
! PARAMETERS FOR A GIVEN BASIS SET
CHARACTER(26) :: BASISFILE
INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4
! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme.
! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET
INTEGER :: NUMBER_OF_TERMS
DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO
! Various flags for the contraction of the primitives and the Kinetic Balance scheme
LOGICAL :: UNCONT
LOGICAL :: KINBAL,UKB
TYPE gaussianbasisfunction
! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function.
! nbrofexponents: the number of different gaussian primitives present in the contraction
! center: coordinates (x,y,z) of the center of the basis function
! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center)
! exponents: array containing the exponent of each of the gaussian primitives present in the contraction
! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction
! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives
! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance).
INTEGER(KIND=C_INT) :: nbrofexponents
REAL(KIND=C_DOUBLE),DIMENSION(3) :: center
INTEGER :: center_id
REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents
REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients
INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree
END TYPE gaussianbasisfunction
TYPE twospinor
! Definition of a Pauli 2-spinor type basis function using gaussian basis functions.
! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor
! contractions: array containing the contractions present in each of the components of the 2-spinor
! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes)
! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor
! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0
INTEGER,DIMENSION(2) :: nbrofcontractions
TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions
INTEGER,DIMENSION(2,MNOGBF) :: contidx
DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients
END TYPE twospinor
CONTAINS
SUBROUTINE SETUP_BASIS
USE case_parameters ; USE setup_tools
CHARACTER(LEN=4) :: CHAR
CHARACTER(LEN=26) :: BASISNAME
INTEGER :: INFO
OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read')
CALL LOOKFOR(100,'## BASIS DEFINITION',INFO)
IF (INFO/=0) STOP
READ(100,'(3/,a)') BASISNAME
IF (BASISNAME(1:6)=='BASIS ') THEN
! The basis set is an existing one in the basis library
LIBRARY=.TRUE.
BASISFILE='basis/'//BASISNAME(7:)
READ(100,'(a4)') CHAR
IF (CHAR=='UNCO') THEN
UNCONT=.TRUE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)'
ELSE
UNCONT=.FALSE.
WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)'
END IF
ELSE IF (BASISNAME(1:4)=='EVEN') THEN
! The basis set is an even-tempered one
LIBRARY=.FALSE.
IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)'
WRITE(*,'(a)')' Even-tempered basis set (preliminary support)'
READ(100,'(i4)') NUMBER_OF_TERMS
WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS
READ(100,*) FIRST_TERM
WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM
READ(100,*) COMMON_RATIO
WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO
ELSE
STOP' Unknown basis set type'
END IF
IF (RELATIVISTIC) THEN
READ(100,'(a2)') CHAR
IF (CHAR=='KI') THEN
KINBAL=.TRUE.
READ(100,'(a4)') CHAR
IF (CHAR=='REST') THEN
UKB=.FALSE.
WRITE(*,'(a)')' Restricted kinetic balance'
ELSE
UKB=.TRUE.
WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance'
END IF
ELSE
KINBAL=.FALSE.
WRITE(*,'(a)')' No kinetic balance'
END IF
END IF
CLOSE(100)
END SUBROUTINE SETUP_BASIS
FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE)
! Function that computes the value of a gaussian basis function at a given point of space.
USE iso_c_binding
TYPE(gaussianbasisfunction),INTENT(IN) :: GBF
DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT
REAL(KIND=C_DOUBLE) :: VALUE
VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) &
|
antoine-levitt/ACCQUAREL
|
7b6c2a6c98fe0073f7d6d3676758315508a9779f
|
Add 1-norm for non-symmetric matrices
|
diff --git a/src/tools.f90 b/src/tools.f90
index b2dc266..25c8a83 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -141,839 +141,843 @@ FUNCTION UNPACK_symmetric(PA,N) RESULT (A)
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=PA(1+J:I-1+J)
END DO
END FUNCTION UNPACK_symmetric
FUNCTION UNPACK_hermitian(PA,N) RESULT (A)
! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N,N) :: A
INTEGER :: I,J
DO I=1,N
J=I*(I-1)/2
A(1:I,I)=PA(1+J:I+J)
A(I,1:I-1)=CONJG(PA(1+J:I-1+J))
END DO
END FUNCTION UNPACK_hermitian
FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2)
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2)
END DO
END DO
END DO
END DO
END FUNCTION ABA_symmetric
FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC)
! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC
INTEGER :: I,J,K,L,IJ
PC=(0.D0,0.D0)
IJ=0
DO J=1,N
DO I=1,J
IJ=IJ+1
DO K=1,I
DO L=1,K
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=I+1,J
DO L=1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=K+1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2)
END DO
DO L=J+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
DO K=J+1,N
DO L=1,J
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2)
END DO
DO L=J+1,K
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2))
END DO
DO L=K+1,N
PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2))
END DO
END DO
END DO
END DO
END FUNCTION ABA_hermitian
FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_symmetric
FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N)
END FUNCTION ABCBA_hermitian
FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_symmetric
FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD)
! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N)
PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N)
END FUNCTION ABC_CBA_hermitian
! diverse linear algebra routines
FUNCTION INVERSE_real(A,N) RESULT(INVA)
! Function that computes the inverse of a square real matrix.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N) :: A
DOUBLE PRECISION,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
INVA=A
CALL DGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the Frobenius or infinity norm of a square real matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
IF (CHAR=='F') THEN
NORM=DLANGE('F',N,N,M,N,WORK)
ELSE IF (CHAR=='I') THEN
NORM=DLANGE('I',N,N,M,N,WORK)
+ ELSE IF (CHAR=='1') THEN
+ NORM=DLANGE('1',N,N,M,N,WORK)
ELSE
STOP'undefined matrix norm'
END IF
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the Frobenius or infinity norm of a square complex matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
IF (CHAR=='F') THEN
NORM=ZLANGE('F',N,N,M,N,WORK)
ELSE IF (CHAR=='I') THEN
NORM=ZLANGE('I',N,N,M,N,WORK)
+ ELSE IF (CHAR=='1') THEN
+ NORM=ZLANGE('1',N,N,M,N,WORK)
ELSE
STOP'undefined matrix norm'
END IF
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the Frobenius norm, the infinity norm or the one norm of a symmetric matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
IF (CHAR=='F') THEN
NORM=DLANSP('F','U',N,PM,WORK)
ELSE IF (CHAR=='I') THEN
NORM=DLANSP('I','U',N,PM,WORK)
ELSE IF (CHAR=='1') THEN
NORM=DLANSP('1','U',N,PM,WORK)
ELSE
STOP'Function NORM: undefined matrix norm.'
END IF
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the Frobenius norm, the infinity norm or the one norm of a hermitian matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
IF (CHAR=='F') THEN
NORM=ZLANHP('F','U',N,PM,WORK)
ELSE IF (CHAR=='I') THEN
NORM=ZLANHP('I','U',N,PM,WORK)
ELSE IF (CHAR=='1') THEN
NORM=ZLANHP('1','U',N,PM,WORK)
ELSE
STOP'Function NORM: undefined matrix norm.'
END IF
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
function EXPONENTIAL_real(t,H,N) result(expH)
! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
! from http://fortranwiki.org/fortran/show/Expokit
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, intent(in) :: t
DOUBLE PRECISION, dimension(N,N), intent(in) :: H
DOUBLE PRECISION, dimension(N,N) :: expH
! Expokit variables
integer, parameter :: ideg = 6
DOUBLE PRECISION, dimension(4*N*N + ideg + 1) :: wsp
integer, dimension(N) :: iwsp
integer :: iexp, ns, iflag
call DGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
end function
function EXPONENTIAL_complex(t,H,N) result(expH)
! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
! from http://fortranwiki.org/fortran/show/Expokit
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, intent(in) :: t
DOUBLE COMPLEX, dimension(N,N), intent(in) :: H
DOUBLE COMPLEX, dimension(N,N) :: expH
! Expokit variables
external :: ZGPADM
integer, parameter :: ideg = 6
DOUBLE COMPLEX, dimension(4*N*N + ideg + 1) :: wsp
integer, dimension(N) :: iwsp
integer :: iexp, ns, iflag
call ZGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
end function
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a symmetric matrix of size N*N stored in packed format.
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a hermitian matrix of size N*N stored in packed format.
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,2E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_hermitian
END MODULE
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
antoine-levitt/ACCQUAREL
|
9f295614e97e7e66731da1be33305192eb5b5730
|
Output condition number of S
|
diff --git a/src/drivers.f90 b/src/drivers.f90
index be208d9..67794f1 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,550 +1,552 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! POUR L'INSTANT
RESUME=.FALSE.
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
+! Condition number
+ WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1')
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (6)
WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST)
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE(6)
WRITE(*,*)' Roothaan/Gradient algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
END SELECT
END DO
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
|
antoine-levitt/ACCQUAREL
|
b3378b3f29a51069ef974b5027009551e8f9a19c
|
cleaned up the code in FORMBASIS_relativistic
|
diff --git a/src/basis.f90 b/src/basis.f90
index e39aad4..f85d3b6 100644
--- a/src/basis.f90
+++ b/src/basis.f90
@@ -1,821 +1,813 @@
MODULE basis
USE iso_c_binding
INTEGER,DIMENSION(4),PARAMETER :: NGPMUSC=(/1,3,6,10/)
INTEGER,DIMENSION(4),PARAMETER :: NGPMLSC=(/3,7,13,21/)
INTERFACE FORMBASIS
MODULE PROCEDURE FORMBASIS_relativistic,FORMBASIS_nonrelativistic
END INTERFACE
CONTAINS
SUBROUTINE FORMBASIS_relativistic(PHI,NBAS,GBF,NGBF)
! Subroutine that builds the 2-spinor basis functions and related contracted cartesian Gaussian-type orbital functions for the molecular system considered, from the coefficients read in a file.
USE basis_parameters ; USE data_parameters ; USE case_parameters ; USE mathematical_functions ; USE constants
IMPLICIT NONE
TYPE(twospinor),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: GBF
INTEGER,DIMENSION(2),INTENT(OUT) :: NGBF
INTEGER,DIMENSION(NBN) :: HAQN
INTEGER,DIMENSION(MAQN,NBN) :: NOP,NOC
DOUBLE PRECISION :: NCOEF
DOUBLE PRECISION,DIMENSION(MNOP,MAQN,NBN) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN,NBN) :: CCOEF
INTEGER,DIMENSION(2,NBN) :: NBASN,NGBFN
INTEGER :: I,J,K,L,M,IUA,IUB,ILA,ILB,IP,IPIC,ICOEF,RNOC,NBOPIC,IUGBF,ILGBF,IDX
ALLOCATE(NBAS(1:2))
DO M=1,NBN
CALL READBASIS(Z(M),HAQN(M),NOP(:,M),NOC(:,M),ALPHA(:,:,M),CCOEF(:,:,:,M),NBASN(:,M),NGBFN(:,M))
END DO
NBAS=SUM(NBASN,DIM=2) ; NGBF=SUM(NGBFN,DIM=2)
ALLOCATE(PHI(1:SUM(NBAS)),GBF(1:SUM(NGBF)))
! Initialization of the indices for the upper 2-spinor basis functions and related gaussian basis functions
IUA=0 ; IUB=NBAS(1)/2 ; IUGBF=0
! Indices for the lower 2-spinor basis functions and related gaussian basis functions
ILA=NBAS(1) ; ILB=NBAS(1)+NBAS(2)/2 ; ILGBF=NGBF(1)
DO M=1,NBN
! Loop on the nuclei of the molecular system
DO I=1,HAQN(M)
IF (UNCONT) THEN
! uncontracted basis
DO J=1,NOP(I,M)
IF (KINBAL) THEN
! Construction of the gaussian primitives related to the lower 2-spinor basis functions when a kinetic balance scheme is used
! note: the coefficients in the contractions are derived from the RKB scheme and put to 1 if the UKB scheme is used.
DO K=1,NGPMLSC(I)
ILGBF=ILGBF+1
GBF(ILGBF)%center=CENTER(:,M)
GBF(ILGBF)%center_id=M
GBF(ILGBF)%nbrofexponents=1
GBF(ILGBF)%exponents(1)=ALPHA(J,I,M)
! note: see how the UKB scheme is to be interpreted before modifying and uncommenting.
! IF (((I==2).AND.(K==7)).OR.((I==3).AND.(K>=11)).OR.((I==4).AND.(K>=16))) THEN
GBF(ILGBF)%coefficients(1)=1.D0
! ELSE
! GBF(ILGBF)%coefficients(1)=2.D0*ALPHA(J,I,M)
! END IF
GBF(ILGBF)%monomialdegree=MDLSC(I,K)
IF (UKB) THEN
! Construction of the lower 2-spinor basis functions (unrestricted kinetic balance scheme)
! (nota bene: this scheme is not really functional due to linear depencies which have yet to be eliminated)
GBF(ILGBF)%coefficients(1)=1.D0
ILA=ILA+1 ; ILB=ILB+1
PHI(ILA)%nbrofcontractions=(/1,0/) ; PHI(ILB)%nbrofcontractions=(/0,1/)
PHI(ILA)%contractions(1,1)=GBF(ILGBF) ; PHI(ILB)%contractions(2,1)=GBF(ILGBF)
PHI(ILA)%contidx(1,1)=ILGBF ; PHI(ILB)%contidx(2,1)=ILGBF
PHI(ILA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(ILB)%coefficients(2,1)=(1.D0,0.D0)
END IF
END DO
END IF
DO K=1,NGPMUSC(I)
! Construction of the uncontracted GBF functions related to the upper 2-spinor basis functions
IUGBF=IUGBF+1
GBF(IUGBF)%center=CENTER(:,M)
GBF(IUGBF)%center_id=M
GBF(IUGBF)%nbrofexponents=1
GBF(IUGBF)%exponents(1)=ALPHA(J,I,M)
GBF(IUGBF)%coefficients(1)=1.D0
GBF(IUGBF)%monomialdegree=MDUSC(I,K)
! Construction of the upper 2-spinor basis functions
IUA=IUA+1 ; IUB=IUB+1
PHI(IUA)%nbrofcontractions=(/1,0/) ; PHI(IUB)%nbrofcontractions=(/0,1/)
PHI(IUA)%contractions(1,1)=GBF(IUGBF) ; PHI(IUB)%contractions(2,1)=GBF(IUGBF)
PHI(IUA)%contidx(1,1)=IUGBF ; PHI(IUB)%contidx(2,1)=IUGBF
PHI(IUA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(IUB)%coefficients(2,1)=(1.D0,0.D0)
! Construction of the lower 2-spinor basis functions (restricted kinetic balance scheme)
ILA=ILA+1 ; ILB=ILB+1
IF (KINBAL.AND..NOT.UKB) GO TO 3
1 END DO
END DO
ELSE
! a priori contracted basis
IF (KINBAL.AND.UKB) GO TO 4
ICOEF=1
IP=1
IF (NOC(I,M)==0) THEN
RNOC=NOP(I,M)
ELSE
RNOC=NOC(I,M)
END IF
DO J=1,RNOC
NBOPIC=0
DO
IF (CCOEF(ICOEF,J,I,M)==0.D0) EXIT
NBOPIC=NBOPIC+1
IF (ICOEF==NOP(I,M)) EXIT
ICOEF=ICOEF+1
END DO
IF (KINBAL) THEN
! Construction of the gaussian basis functions related to the lower 2-spinor basis functions when a kinetic balance scheme is used
DO K=1,NGPMLSC(I)
ILGBF=ILGBF+1
GBF(ILGBF)%center=CENTER(:,M)
GBF(ILGBF)%center_id=M
GBF(ILGBF)%nbrofexponents=NBOPIC
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
GBF(ILGBF)%exponents(IPIC)=ALPHA(L,I,M)
! part of the normalization coefficient depending only on the exponent and the monomial total degree
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1))
! nota bene: the multiplication of the contraction coefficient by the exponent, when needed, is done here.
IF (((I==2).AND.(K==7)).OR.((I==3).AND.(K>=11)).OR.((I==4).AND.(K>=16))) THEN
GBF(ILGBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
ELSE
GBF(ILGBF)%coefficients(IPIC)=ALPHA(L,I,M)*NCOEF*CCOEF(L,J,I,M)
END IF
GBF(ILGBF)%monomialdegree=MDLSC(I,K)
END DO
END DO
END IF
DO K=1,NGPMUSC(I)
! Construction of the gaussian basis functions related to the upper 2-spinor basis functions
IUGBF=IUGBF+1
GBF(IUGBF)%center=CENTER(:,M)
GBF(IUGBF)%center_id=M
GBF(IUGBF)%nbrofexponents=NBOPIC
GBF(IUGBF)%monomialdegree=MDUSC(I,K)
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
GBF(IUGBF)%exponents(IPIC)=ALPHA(L,I,M)
! normalization coefficient
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1)/(DFACT(2*GBF(IUGBF)%monomialdegree(1)-1) &
& *DFACT(2*GBF(IUGBF)%monomialdegree(2)-1)*DFACT(2*GBF(IUGBF)%monomialdegree(3)-1)))
GBF(IUGBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
END DO
! Construction of the upper 2-spinor basis functions
IUA=IUA+1 ; IUB=IUB+1
PHI(IUA)%nbrofcontractions=(/1,0/) ; PHI(IUB)%nbrofcontractions=(/0,1/)
PHI(IUA)%contractions(1,1)=GBF(IUGBF) ; PHI(IUB)%contractions(2,1)=GBF(IUGBF)
PHI(IUA)%contidx(1,1)=IUGBF ; PHI(IUB)%contidx(2,1)=IUGBF
PHI(IUA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(IUB)%coefficients(2,1)=(1.D0,0.D0)
! Construction of the lower 2-spinor basis functions (restricted kinetic balance scheme)
ILA=ILA+1 ; ILB=ILB+1
IF (KINBAL.AND..NOT.UKB) GO TO 3
2 END DO
IP=IP+NBOPIC
END DO
END IF
END DO
END DO
IF (.NOT.KINBAL) THEN
! If no kinetic balance scheme is used, basis functions for the lower 2-spinor are exactly the same as the ones for the upper 2-spinor
DO I=1,NGBF(2)
! HIS IS NOT OPTIMAL IN TERMS OF COMPUTATION...
GBF(NGBF(1)+I)=GBF(I)
END DO
DO I=1,NBAS(2)
PHI(NBAS(1)+I)=PHI(I)
END DO
END IF
WRITE(*,'(a,i4)')' Total number of basis functions =',SUM(NBAS)
RETURN
3 IDX=ILGBF-NGPMLSC(I)
SELECT CASE (I)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,2/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+1),GBF(IDX+2)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:2)=(/IDX+1,IDX+2/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
-! NOTE: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
CASE (2)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+7)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+7/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+5) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+7)/)
PHI(ILA)%contidx(1,1)=IDX+5 ; PHI(ILA)%contidx(2,1:3)=(/IDX+2,IDX+4,IDX+7/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+6),GBF(IDX+7)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+3),GBF(IDX+5)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+6,IDX+7/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+3,IDX+5/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
END SELECT
CASE (3)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+11)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+11/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-2.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+6) ; PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+11),GBF(IDX+12)/)
PHI(ILA)%contidx(1,1)=IDX+6 ; PHI(ILA)%contidx(2,1:4)=(/IDX+2,IDX+4,IDX+11,IDX+12/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+5),GBF(IDX+11)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+3),GBF(IDX+6),GBF(IDX+13)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+5,IDX+11/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+3,IDX+6,IDX+13/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (4)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+8) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+4),GBF(IDX+7),GBF(IDX+12)/)
PHI(ILA)%contidx(1,1)=IDX+8 ; PHI(ILA)%contidx(2,1:3)=(/IDX+4,IDX+7,IDX+12/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (5)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+9),GBF(IDX+12)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+6),GBF(IDX+8),GBF(IDX+13)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+9,IDX+12/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+6,IDX+8,IDX+13/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (6)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+10),GBF(IDX+13)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+5),GBF(IDX+9)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+10,IDX+13/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+5,IDX+9/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
END SELECT
CASE (4)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+16)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+16/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-3.D0)/)
NCOEF=15**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+5)
PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+16),GBF(IDX+17)/)
PHI(ILA)%contidx(1,1)=IDX+5 ; PHI(ILA)%contidx(2,1:4)=(/IDX+2,IDX+4,IDX+16,IDX+17/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0)
PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-2.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+6),GBF(IDX+16)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+3),GBF(IDX+5),GBF(IDX+18)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+6,IDX+16/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+3,IDX+5,IDX+18/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-2.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (4)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+8) ; PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+4),GBF(IDX+7),GBF(IDX+17),GBF(IDX+19)/)
PHI(ILA)%contidx(1,1)=IDX+8 ; PHI(ILA)%contidx(2,1:4)=(/IDX+4,IDX+7,IDX+17,IDX+19/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0),(0.D0,-1.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (5)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+10),GBF(IDX+18)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+6),GBF(IDX+9),GBF(IDX+21)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+10,IDX+18/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+6,IDX+9,IDX+21/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (6)
PHI(ILA)%nbrofcontractions=(/2,4/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+9),GBF(IDX+17)/)
PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+5),GBF(IDX+8),GBF(IDX+18),GBF(IDX+20)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+9,IDX+17/) ; PHI(ILA)%contidx(2,1:4)=(/IDX+5,IDX+8,IDX+18,IDX+20/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (7)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+12) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+10),GBF(IDX+11),GBF(IDX+19)/)
PHI(ILA)%contidx(1,1)=IDX+12 ; PHI(ILA)%contidx(2,1:3)=(/IDX+10,IDX+11,IDX+19/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(3.D0,0.D0)/)
NCOEF=15**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (8)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+13),GBF(IDX+19)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+8),GBF(IDX+12),GBF(IDX+20)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+13,IDX+19/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+8,IDX+12,IDX+20/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (9)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+14),GBF(IDX+20)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+9),GBF(IDX+13),GBF(IDX+21)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+14,IDX+20/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+9,IDX+13,IDX+21/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
NCOEF=3**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (10)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+15),GBF(IDX+21)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+10),GBF(IDX+14)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+15,IDX+21/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+10,IDX+14/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-3.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
NCOEF=15**(-0.5D0)
PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
END SELECT
END SELECT
PHI(ILB)%nbrofcontractions(1)=PHI(ILA)%nbrofcontractions(2)
PHI(ILB)%contractions(1,:)=PHI(ILA)%contractions(2,:)
PHI(ILB)%contidx(1,:)=PHI(ILA)%contidx(2,:)
PHI(ILB)%coefficients(1,:)=-CONJG(PHI(ILA)%coefficients(2,:))
PHI(ILB)%nbrofcontractions(2)=PHI(ILA)%nbrofcontractions(1)
PHI(ILB)%contractions(2,:)=PHI(ILA)%contractions(1,:)
PHI(ILB)%contidx(2,:)=PHI(ILA)%contidx(1,:)
PHI(ILB)%coefficients(2,:)=-PHI(ILA)%coefficients(1,:)
IF (UNCONT) THEN
GO TO 1
ELSE
GO TO 2
END IF
4 IF (KINBAL.AND.UKB) STOP 'Option not implemented yet!'
END SUBROUTINE FORMBASIS_relativistic
SUBROUTINE FORMBASIS_nonrelativistic(PHI,NBAS)
! Subroutine that builds the gaussian basis functions for the molecular system considered, from coefficients either read in a file (basis set from the existing literature) or depending on some given parameters (even-tempered basis set).
USE basis_parameters ; USE data_parameters ; USE mathematical_functions ; USE constants
IMPLICIT NONE
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: NBAS
INTEGER :: I,J,K,L,M,IBF,IP,IPIC,ICOEF,NBOPIC
INTEGER,DIMENSION(NBN) :: HAQN
INTEGER,DIMENSION(1,NBN) :: NBASN
INTEGER,DIMENSION(MAQN,NBN) :: NOP,NOC
DOUBLE PRECISION :: NCOEF
DOUBLE PRECISION,DIMENSION(MNOP,MAQN,NBN) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN,NBN) :: CCOEF
ALLOCATE(NBAS(1:1))
IF (LIBRARY) THEN
DO M=1,NBN
CALL READBASIS(Z(M),HAQN(M),NOP(:,M),NOC(:,M),ALPHA(:,:,M),CCOEF(:,:,:,M),NBASN(:,M))
END DO
NBAS=SUM(NBASN,DIM=2)
ALLOCATE(PHI(1:SUM(NBAS)))
IBF=0
DO M=1,NBN
! Loop on the nuclei of the molecular system
DO I=1,HAQN(M)
IF (UNCONT) THEN
DO J=1,NOP(I,M)
DO K=1,NGPMUSC(I)
IBF=IBF+1
PHI(IBF)%center=CENTER(:,M)
PHI(IBF)%center_id=M
PHI(IBF)%nbrofexponents=1
PHI(IBF)%exponents(1)=ALPHA(J,I,M)
PHI(IBF)%coefficients(1)=1.D0
PHI(IBF)%monomialdegree=MDUSC(I,K)
END DO
END DO
ELSE
ICOEF=1
IP=1
DO J=1,NOC(I,M)
NBOPIC=0
DO
IF (CCOEF(ICOEF,J,I,M)==0.D0) EXIT
NBOPIC=NBOPIC+1
IF (ICOEF==NOP(I,M)) EXIT
ICOEF=ICOEF+1
END DO
DO K=1,NGPMUSC(I)
IBF=IBF+1
PHI(IBF)%center=CENTER(:,M)
PHI(IBF)%center_id=M
PHI(IBF)%nbrofexponents=NBOPIC
PHI(IBF)%monomialdegree=MDUSC(I,K)
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
PHI(IBF)%exponents(IPIC)=ALPHA(L,I,M)
! normalization coefficient
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1)/(DFACT(2*PHI(IBF)%monomialdegree(1)-1) &
& *DFACT(2*PHI(IBF)%monomialdegree(2)-1)*DFACT(2*PHI(IBF)%monomialdegree(3)-1)))
PHI(IBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
END DO
END DO
IP=IP+NBOPIC
END DO
END IF
END DO
END DO
ELSE
NBAS=NUMBER_OF_TERMS
open(22)
ALLOCATE(PHI(1:SUM(NBAS)))
DO I=1,SUM(NBAS)
PHI(I)%center=(/0.D0,0.D0,0.D0/)
PHI(I)%nbrofexponents=1
PHI(I)%exponents(1)=FIRST_TERM*COMMON_RATIO**(I-1)
write(22,*)FIRST_TERM*COMMON_RATIO**(I-1)
PHI(I)%coefficients(1)=1.D0
PHI(I)%monomialdegree=(/0,0,0/)
END DO
close(22)
END IF
WRITE(*,'(a,i4)')' Total number of basis functions =',SUM(NBAS)
END SUBROUTINE FORMBASIS_nonrelativistic
SUBROUTINE READBASIS(Z,HAQN,NOP,NOC,ALPHA,CCOEF,NBAS,NGBF)
! Subroutine that reads (for a given chemical element) the coefficients of the functions of a chosen basis in the DALTON library and computes the number of basis functions (and related cartesian gaussian-type orbital functions) for the components of the upper and lower 2-spinors with respect to the indicated options (contracted basis or not, use of the "kinetic balance" process or not, etc...)
! Note: the name (and path) of the file containing the basis name is stored in the variable BASISFILE from the module basis_parameters.
! Z : atomic number of the element under consideration
! MAQN : maximum angular quantum number + 1 (= number of function types) allowed (s=1, p=2, d=3, etc...)
! MNOP : maximum number of primitives of any given type allowed
! MNOC : maximum number of contractions of any given type allowed
! HAQN : highest angular quantum number of the element basis functions + 1
! NOP : array containing the number of primitives of each type of basis function
! NOC : array containing the number of contractions for each type of basis function
! ALPHA : array containing the exponents of the primitives for each type of basis functions
! CCOEF : array containing the contraction coefficients for each type of basis functions
USE case_parameters ; USE basis_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: Z
INTEGER,INTENT(OUT) :: HAQN
INTEGER,DIMENSION(MAQN),INTENT(OUT) :: NOP,NOC
DOUBLE PRECISION,DIMENSION(MNOP,MAQN),INTENT(OUT) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN),INTENT(OUT) :: CCOEF
INTEGER,DIMENSION(:),INTENT(OUT) :: NBAS
INTEGER,DIMENSION(2),INTENT(OUT),OPTIONAL :: NGBF
INTEGER :: LUBAS,PRINUM,CONNUM,IDUMMY,I
LOGICAL :: LEX,CHKNELM
LUBAS=20
INQUIRE(FILE=BASISFILE,EXIST=LEX)
IF (LEX) THEN
! Open the file containing the basis
OPEN(UNIT=LUBAS,FILE=BASISFILE,ACTION='READ')
! Search for the right atomic element in this file
CALL FINDELM(Z,BASISFILE,LUBAS)
NOP=0 ; NOC=0 ; HAQN=0
! Find the number of primitives and contractions of each type and read them
1 CALL READPCN(CHKNELM,PRINUM,CONNUM,IDUMMY,BASISFILE,LUBAS)
IF (UNCONT) CONNUM=-CONNUM
IF (.NOT.CHKNELM) THEN
HAQN=HAQN+1
IF (HAQN>MAQN) GO TO 3
NOP(HAQN)=PRINUM ; NOC(HAQN)=CONNUM
! Fill ALPHA and CCOEF by reading the corresponding exponents and contraction coefficients
CALL READECC(MNOP,MNOC,NOP(HAQN),NOC(HAQN),ALPHA(:,HAQN),CCOEF(:,:,HAQN),BASISFILE,LUBAS)
GO TO 1
END IF
CLOSE(LUBAS)
ELSE
GO TO 2
END IF
! Computation of the number of basis functions
IF (RELATIVISTIC) THEN
! relativistic case
NBAS=0 ; NGBF=0
DO I=1,HAQN
IF (UNCONT) THEN
! uncontracted basis
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOP(I)*NGPMUSC(I)
IF (KINBAL) THEN
NGBF(2)=NGBF(2)+NOP(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOP(I)*NGPMLSC(I)
END IF
ELSE
! a priori contracted basis
IF (NOC(I)/=0) THEN
NBAS(1)=NBAS(1)+NOC(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOC(I)*NGPMUSC(I)
ELSE
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOP(I)*NGPMUSC(I)
END IF
IF (KINBAL) THEN
IF (NOC(I)/=0) THEN
NGBF(2)=NGBF(2)+NOC(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOC(I)*NGPMLSC(I)
ELSE
NGBF(2)=NGBF(2)+NOP(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOP(I)*NGPMLSC(I)
END IF
END IF
END IF
END DO
IF (KINBAL.AND..NOT.UKB) NBAS(2)=NBAS(1)
IF (.NOT.KINBAL) THEN
NBAS(2)=NBAS(1) ; NGBF(2)=NGBF(1)
END IF
NBAS=2*NBAS
ELSE
! non-relativistic case
NBAS(1)=0
DO I=1,HAQN
IF (UNCONT) THEN
! uncontracted basis
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
ELSE
! a priori contracted basis
IF (NOC(I)/=0) THEN
NBAS(1)=NBAS(1)+NOC(I)*NGPMUSC(I)
ELSE
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
END IF
END IF
END DO
END IF
RETURN
! MESSAGES
2 WRITE(*,'(a)')' Subroutine READBASIS: the file containing the basis could not be found.'
GO TO 4
3 WRITE(*,'(a)')' Subroutine READBASIS: this type of gaussian basis function is not supported!'
4 STOP
END SUBROUTINE READBASIS
SUBROUTINE FINDELM(Z,BASNAM,LUBAS)
IMPLICIT NONE
INTEGER :: Z,LUBAS
CHARACTER(*) :: BASNAM
CHARACTER(20) :: STRING
CHARACTER :: CHDUMMY
INTEGER :: IDUMMY,IOERR
1 READ(LUBAS,'(a20)',IOSTAT=IOERR,ERR=2,END=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF ((CHDUMMY=='a').OR.(CHDUMMY=='A')) THEN
READ(STRING,'(BN,a1,i4)')CHDUMMY,IDUMMY
IF (Z==IDUMMY) THEN
RETURN
ELSE
GO TO 1
END IF
ELSE
GO TO 1
END IF
! MESSAGES
2 WRITE(*,'(a,a,a,i2,a)')' Subroutine FINDELM: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
3 WRITE(*,'(a,i2,a,a,a)')' Subroutine FINDELM: the basis functions relative to atomic element number ',Z, &
& ' could not be found in the basis ',BASNAM,'.'
STOP
END SUBROUTINE FINDELM
SUBROUTINE READPCN(CHKNELM,PRINUM,CONNUM,INTISG,BASNAM,LUBAS)
IMPLICIT NONE
LOGICAL :: CHKNELM
INTEGER :: PRINUM,CONNUM,INTISG,LUBAS
CHARACTER(*) :: BASNAM
LOGICAL :: BLANK
CHARACTER(88) :: STRING
CHARACTER :: CHDUMMY
INTEGER :: IDUMMY,IOERR
CHKNELM=.FALSE.
1 READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=2,END=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (BLANK) THEN
GO TO 1
ELSE
READ (STRING,'(BN,3i5)')PRINUM,CONNUM,INTISG
RETURN
END IF
ELSE IF ((CHDUMMY=='a').OR.(CHDUMMY=='A')) THEN
CHKNELM=.TRUE.
RETURN
ELSE
GO TO 1
END IF
2 WRITE(*,'(a,a,a,i2,a)')' Subroutine READPCN: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
3 CHKNELM=.TRUE.
RETURN
END SUBROUTINE READPCN
SUBROUTINE READECC(MNOP,MNOC,NOP,NOC,ALPHA,CCOEF,BASNAM,LUBAS)
IMPLICIT NONE
INTEGER :: MNOP,MNOC,NOP,NOC,LUBAS
DOUBLE PRECISION,DIMENSION(MNOP) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC) :: CCOEF
CHARACTER(*) :: BASNAM
INTEGER :: I,J,K,L,IOERR,NUMLIN,NUMRCC,NUM
CHARACTER :: CHDUMMY
CHARACTER(88) :: STRING
LOGICAL :: BLANK
! NUMCCA is the maximum number of contraction coefficients on the first line of a block. If NOC is greater than NUMCCA, the reading of the coefficients will continue on the following line, which contains NUMCCB coefficients at most.
INTEGER,PARAMETER :: NUMCCA=6,NUMCCB=7
ALPHA=0.D0 ; CCOEF=0.D0
J=0
1 IF (J<NOP) THEN
READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (.NOT.BLANK) THEN
! This line contains an exponent and some contraction coefficients
J=J+1
L=ABS(NOC)
CALL CONLIN(L,NUMLIN)
IF (NOC<=0) THEN
! We want an uncontracted basis set: we just read the exponent and skip the continuation lines
READ(STRING,'(f16.9)')ALPHA(J)
CCOEF(J,J)=1.D0
DO I=2,NUMLIN
READ(LUBAS,*)
END DO
GO TO 1
ELSE
! Get the right format for the read statement
IF (NUMLIN==1) THEN
L=NOC
ELSE
L=NUMCCA
END IF
! Read the exponent and contraction coefficients on the first line
READ(STRING,'(f16.9,6f12.9)')ALPHA(J),(CCOEF(J,I),I=1,L)
! If there are more lines with contraction coefficients, read them
DO I=2,NUMLIN
NUMRCC=NUMCCA+(I-1)*NUMCCB
! Get the right format for the read statement
NUM=MIN(NUMRCC,NOC)
2 READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=3)STRING
READ (STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (.NOT.BLANK) THEN
! This line contains contraction coefficients
READ(STRING,'(7f12.9)')(CCOEF(J,K),K=NUMCCA+(I-2)*NUMCCB+1,NUM)
END IF
ELSE
! This line is a blank one, read the next one
GO TO 2
END IF
END DO
GO TO 1
END IF
ELSE
! This line is a blank one, read the next one
GO TO 1
END IF
ELSE
! Skip this line
GO TO 1
END IF
END IF
RETURN
3 WRITE(*,'(a,a,a,i2,a)')' Subroutine READECC: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
END SUBROUTINE READECC
SUBROUTINE CHBLANK(BLANK,STRING)
! Subroutine that checks whether a line is a blank one or not.
IMPLICIT NONE
LOGICAL :: BLANK
CHARACTER*(*) :: STRING
INTEGER :: J
BLANK=.TRUE.
DO J=1,LEN(STRING)
BLANK=BLANK.AND.(STRING(J:J)==' ')
END DO
RETURN
END SUBROUTINE CHBLANK
SUBROUTINE CONLIN(NOC,NUMLIN)
! Subroutine that finds out on how many lines the contraction coefficients are written in a given block (knowing there at most NUMCCA coefficients on the first line and NUMCCB on the following ones), and returns that number.
IMPLICIT NONE
INTEGER :: NOC,NUMLIN
INTEGER,PARAMETER :: NUMCCA=6,NUMCCB=7
IF (NOC<=NUMCCA) THEN
NUMLIN=1
ELSE IF (MOD(NOC-NUMCCA,NUMCCB)==0) THEN
NUMLIN=(NOC-NUMCCA)/NUMCCB+1
ELSE
NUMLIN=(NOC-NUMCCA)/NUMCCB+2
END IF
END SUBROUTINE CONLIN
FUNCTION MDUSC(I,J) RESULT (MONOMIALDEGREE)
! Function that returns the monomial degree of each cartesian gaussian primitive function of shell type "I" (where "I=1" means "s", "I=2" means "p", "I=3" means "d", etc...) appearing in the components of the upper 2-spinor basis functions.
IMPLICIT NONE
INTEGER,INTENT(IN) :: I,J
INTEGER,DIMENSION(3) :: MONOMIALDEGREE
SELECT CASE (I)
CASE (1)
! shell type s (1 associated monomial)
MONOMIALDEGREE=(/0,0,0/)
CASE (2)
! shell type p (3 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/1,0,0/)
CASE (2) ; MONOMIALDEGREE=(/0,1,0/)
CASE (3) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (3)
! shell type d (6 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/2,0,0/)
CASE (2) ; MONOMIALDEGREE=(/1,1,0/)
CASE (3) ; MONOMIALDEGREE=(/1,0,1/)
CASE (4) ; MONOMIALDEGREE=(/0,2,0/)
CASE (5) ; MONOMIALDEGREE=(/0,1,1/)
CASE (6) ; MONOMIALDEGREE=(/0,0,2/)
END SELECT
CASE (4)
! shell type f (10 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/3,0,0/)
CASE (2) ; MONOMIALDEGREE=(/2,1,0/)
CASE (3) ; MONOMIALDEGREE=(/2,0,1/)
CASE (4) ; MONOMIALDEGREE=(/1,2,0/)
CASE (5) ; MONOMIALDEGREE=(/1,0,2/)
CASE (6) ; MONOMIALDEGREE=(/1,1,1/)
CASE (7) ; MONOMIALDEGREE=(/0,3,0/)
CASE (8) ; MONOMIALDEGREE=(/0,2,1/)
CASE (9) ; MONOMIALDEGREE=(/0,1,2/)
CASE (10) ; MONOMIALDEGREE=(/0,0,3/)
END SELECT
END SELECT
END FUNCTION MDUSC
FUNCTION MDLSC(I,J) RESULT (MONOMIALDEGREE)
! Function that returns the monomial degree of each cartesian gaussian primitive function appearing in the components of the lower 2-spinor basis functions when a kinetic balance scheme is applied on the upper 2-spinor basis functions.
! Note: the integer I refers to the shell type of the gaussian basis functions appearing in the components of the upper 2-spinor basis function to which the (R/U)KB scheme is applied (see the function MDUSC above).
IMPLICIT NONE
INTEGER,INTENT(IN) :: I,J
INTEGER,DIMENSION(3) :: MONOMIALDEGREE
SELECT CASE (I)
CASE (1)
! shell type s (3 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/1,0,0/)
CASE (2) ; MONOMIALDEGREE=(/0,1,0/)
CASE (3) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (2)
! shell type p (7 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/2,0,0/)
CASE (2) ; MONOMIALDEGREE=(/1,1,0/)
CASE (3) ; MONOMIALDEGREE=(/1,0,1/)
CASE (4) ; MONOMIALDEGREE=(/0,2,0/)
CASE (5) ; MONOMIALDEGREE=(/0,1,1/)
CASE (6) ; MONOMIALDEGREE=(/0,0,2/)
CASE (7) ; MONOMIALDEGREE=(/0,0,0/)
END SELECT
CASE (3)
! shell type d (13 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/3,0,0/)
CASE (2) ; MONOMIALDEGREE=(/2,1,0/)
CASE (3) ; MONOMIALDEGREE=(/2,0,1/)
CASE (4) ; MONOMIALDEGREE=(/1,2,0/)
CASE (5) ; MONOMIALDEGREE=(/1,0,2/)
CASE (6) ; MONOMIALDEGREE=(/1,1,1/)
CASE (7) ; MONOMIALDEGREE=(/0,3,0/)
CASE (8) ; MONOMIALDEGREE=(/0,2,1/)
CASE (9) ; MONOMIALDEGREE=(/0,1,2/)
CASE (10) ; MONOMIALDEGREE=(/0,0,3/)
CASE (11) ; MONOMIALDEGREE=(/1,0,0/)
CASE (12) ; MONOMIALDEGREE=(/0,1,0/)
CASE (13) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (4)
! shell type f (21 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/4,0,0/)
CASE (2) ; MONOMIALDEGREE=(/3,1,0/)
CASE (3) ; MONOMIALDEGREE=(/3,0,1/)
CASE (4) ; MONOMIALDEGREE=(/2,2,0/)
|
antoine-levitt/ACCQUAREL
|
e0a88652c47bbd6fa04910b66108b2705bcddff7
|
Remove scaling in basis
|
diff --git a/src/basis.f90 b/src/basis.f90
index cdf8a78..e39aad4 100644
--- a/src/basis.f90
+++ b/src/basis.f90
@@ -1,842 +1,842 @@
MODULE basis
USE iso_c_binding
INTEGER,DIMENSION(4),PARAMETER :: NGPMUSC=(/1,3,6,10/)
INTEGER,DIMENSION(4),PARAMETER :: NGPMLSC=(/3,7,13,21/)
INTERFACE FORMBASIS
MODULE PROCEDURE FORMBASIS_relativistic,FORMBASIS_nonrelativistic
END INTERFACE
CONTAINS
SUBROUTINE FORMBASIS_relativistic(PHI,NBAS,GBF,NGBF)
! Subroutine that builds the 2-spinor basis functions and related contracted cartesian Gaussian-type orbital functions for the molecular system considered, from the coefficients read in a file.
USE basis_parameters ; USE data_parameters ; USE case_parameters ; USE mathematical_functions ; USE constants
IMPLICIT NONE
TYPE(twospinor),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: GBF
INTEGER,DIMENSION(2),INTENT(OUT) :: NGBF
INTEGER,DIMENSION(NBN) :: HAQN
INTEGER,DIMENSION(MAQN,NBN) :: NOP,NOC
DOUBLE PRECISION :: NCOEF
DOUBLE PRECISION,DIMENSION(MNOP,MAQN,NBN) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN,NBN) :: CCOEF
INTEGER,DIMENSION(2,NBN) :: NBASN,NGBFN
INTEGER :: I,J,K,L,M,IUA,IUB,ILA,ILB,IP,IPIC,ICOEF,RNOC,NBOPIC,IUGBF,ILGBF,IDX
ALLOCATE(NBAS(1:2))
DO M=1,NBN
CALL READBASIS(Z(M),HAQN(M),NOP(:,M),NOC(:,M),ALPHA(:,:,M),CCOEF(:,:,:,M),NBASN(:,M),NGBFN(:,M))
END DO
NBAS=SUM(NBASN,DIM=2) ; NGBF=SUM(NGBFN,DIM=2)
ALLOCATE(PHI(1:SUM(NBAS)),GBF(1:SUM(NGBF)))
! Initialization of the indices for the upper 2-spinor basis functions and related gaussian basis functions
IUA=0 ; IUB=NBAS(1)/2 ; IUGBF=0
! Indices for the lower 2-spinor basis functions and related gaussian basis functions
ILA=NBAS(1) ; ILB=NBAS(1)+NBAS(2)/2 ; ILGBF=NGBF(1)
DO M=1,NBN
! Loop on the nuclei of the molecular system
DO I=1,HAQN(M)
IF (UNCONT) THEN
! uncontracted basis
DO J=1,NOP(I,M)
IF (KINBAL) THEN
! Construction of the gaussian primitives related to the lower 2-spinor basis functions when a kinetic balance scheme is used
! note: the coefficients in the contractions are derived from the RKB scheme and put to 1 if the UKB scheme is used.
DO K=1,NGPMLSC(I)
ILGBF=ILGBF+1
GBF(ILGBF)%center=CENTER(:,M)
GBF(ILGBF)%center_id=M
GBF(ILGBF)%nbrofexponents=1
GBF(ILGBF)%exponents(1)=ALPHA(J,I,M)
! note: see how the UKB scheme is to be interpreted before modifying and uncommenting.
! IF (((I==2).AND.(K==7)).OR.((I==3).AND.(K>=11)).OR.((I==4).AND.(K>=16))) THEN
GBF(ILGBF)%coefficients(1)=1.D0
! ELSE
! GBF(ILGBF)%coefficients(1)=2.D0*ALPHA(J,I,M)
! END IF
GBF(ILGBF)%monomialdegree=MDLSC(I,K)
IF (UKB) THEN
! Construction of the lower 2-spinor basis functions (unrestricted kinetic balance scheme)
! (nota bene: this scheme is not really functional due to linear depencies which have yet to be eliminated)
GBF(ILGBF)%coefficients(1)=1.D0
ILA=ILA+1 ; ILB=ILB+1
PHI(ILA)%nbrofcontractions=(/1,0/) ; PHI(ILB)%nbrofcontractions=(/0,1/)
PHI(ILA)%contractions(1,1)=GBF(ILGBF) ; PHI(ILB)%contractions(2,1)=GBF(ILGBF)
PHI(ILA)%contidx(1,1)=ILGBF ; PHI(ILB)%contidx(2,1)=ILGBF
PHI(ILA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(ILB)%coefficients(2,1)=(1.D0,0.D0)
END IF
END DO
END IF
DO K=1,NGPMUSC(I)
! Construction of the uncontracted GBF functions related to the upper 2-spinor basis functions
IUGBF=IUGBF+1
GBF(IUGBF)%center=CENTER(:,M)
GBF(IUGBF)%center_id=M
GBF(IUGBF)%nbrofexponents=1
GBF(IUGBF)%exponents(1)=ALPHA(J,I,M)
GBF(IUGBF)%coefficients(1)=1.D0
GBF(IUGBF)%monomialdegree=MDUSC(I,K)
! Construction of the upper 2-spinor basis functions
IUA=IUA+1 ; IUB=IUB+1
PHI(IUA)%nbrofcontractions=(/1,0/) ; PHI(IUB)%nbrofcontractions=(/0,1/)
PHI(IUA)%contractions(1,1)=GBF(IUGBF) ; PHI(IUB)%contractions(2,1)=GBF(IUGBF)
PHI(IUA)%contidx(1,1)=IUGBF ; PHI(IUB)%contidx(2,1)=IUGBF
PHI(IUA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(IUB)%coefficients(2,1)=(1.D0,0.D0)
! Construction of the lower 2-spinor basis functions (restricted kinetic balance scheme)
ILA=ILA+1 ; ILB=ILB+1
IF (KINBAL.AND..NOT.UKB) GO TO 3
1 END DO
END DO
ELSE
! a priori contracted basis
IF (KINBAL.AND.UKB) GO TO 4
ICOEF=1
IP=1
IF (NOC(I,M)==0) THEN
RNOC=NOP(I,M)
ELSE
RNOC=NOC(I,M)
END IF
DO J=1,RNOC
NBOPIC=0
DO
IF (CCOEF(ICOEF,J,I,M)==0.D0) EXIT
NBOPIC=NBOPIC+1
IF (ICOEF==NOP(I,M)) EXIT
ICOEF=ICOEF+1
END DO
IF (KINBAL) THEN
! Construction of the gaussian basis functions related to the lower 2-spinor basis functions when a kinetic balance scheme is used
DO K=1,NGPMLSC(I)
ILGBF=ILGBF+1
GBF(ILGBF)%center=CENTER(:,M)
GBF(ILGBF)%center_id=M
GBF(ILGBF)%nbrofexponents=NBOPIC
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
GBF(ILGBF)%exponents(IPIC)=ALPHA(L,I,M)
! part of the normalization coefficient depending only on the exponent and the monomial total degree
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1))
! nota bene: the multiplication of the contraction coefficient by the exponent, when needed, is done here.
IF (((I==2).AND.(K==7)).OR.((I==3).AND.(K>=11)).OR.((I==4).AND.(K>=16))) THEN
GBF(ILGBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
ELSE
GBF(ILGBF)%coefficients(IPIC)=ALPHA(L,I,M)*NCOEF*CCOEF(L,J,I,M)
END IF
GBF(ILGBF)%monomialdegree=MDLSC(I,K)
END DO
END DO
END IF
DO K=1,NGPMUSC(I)
! Construction of the gaussian basis functions related to the upper 2-spinor basis functions
IUGBF=IUGBF+1
GBF(IUGBF)%center=CENTER(:,M)
GBF(IUGBF)%center_id=M
GBF(IUGBF)%nbrofexponents=NBOPIC
GBF(IUGBF)%monomialdegree=MDUSC(I,K)
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
GBF(IUGBF)%exponents(IPIC)=ALPHA(L,I,M)
! normalization coefficient
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1)/(DFACT(2*GBF(IUGBF)%monomialdegree(1)-1) &
& *DFACT(2*GBF(IUGBF)%monomialdegree(2)-1)*DFACT(2*GBF(IUGBF)%monomialdegree(3)-1)))
GBF(IUGBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
END DO
! Construction of the upper 2-spinor basis functions
IUA=IUA+1 ; IUB=IUB+1
PHI(IUA)%nbrofcontractions=(/1,0/) ; PHI(IUB)%nbrofcontractions=(/0,1/)
PHI(IUA)%contractions(1,1)=GBF(IUGBF) ; PHI(IUB)%contractions(2,1)=GBF(IUGBF)
PHI(IUA)%contidx(1,1)=IUGBF ; PHI(IUB)%contidx(2,1)=IUGBF
PHI(IUA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(IUB)%coefficients(2,1)=(1.D0,0.D0)
! Construction of the lower 2-spinor basis functions (restricted kinetic balance scheme)
ILA=ILA+1 ; ILB=ILB+1
IF (KINBAL.AND..NOT.UKB) GO TO 3
2 END DO
IP=IP+NBOPIC
END DO
END IF
END DO
END DO
IF (.NOT.KINBAL) THEN
! If no kinetic balance scheme is used, basis functions for the lower 2-spinor are exactly the same as the ones for the upper 2-spinor
DO I=1,NGBF(2)
! HIS IS NOT OPTIMAL IN TERMS OF COMPUTATION...
GBF(NGBF(1)+I)=GBF(I)
END DO
DO I=1,NBAS(2)
PHI(NBAS(1)+I)=PHI(I)
END DO
END IF
WRITE(*,'(a,i4)')' Total number of basis functions =',SUM(NBAS)
RETURN
3 IDX=ILGBF-NGPMLSC(I)
SELECT CASE (I)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,2/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+1),GBF(IDX+2)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:2)=(/IDX+1,IDX+2/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
! NOTE: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (2)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+7)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+7/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+5) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+7)/)
PHI(ILA)%contidx(1,1)=IDX+5 ; PHI(ILA)%contidx(2,1:3)=(/IDX+2,IDX+4,IDX+7/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+6),GBF(IDX+7)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+3),GBF(IDX+5)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+6,IDX+7/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+3,IDX+5/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
END SELECT
CASE (3)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+11)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+11/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-2.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+6) ; PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+11),GBF(IDX+12)/)
PHI(ILA)%contidx(1,1)=IDX+6 ; PHI(ILA)%contidx(2,1:4)=(/IDX+2,IDX+4,IDX+11,IDX+12/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+5),GBF(IDX+11)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+3),GBF(IDX+6),GBF(IDX+13)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+5,IDX+11/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+3,IDX+6,IDX+13/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (4)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+8) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+4),GBF(IDX+7),GBF(IDX+12)/)
PHI(ILA)%contidx(1,1)=IDX+8 ; PHI(ILA)%contidx(2,1:3)=(/IDX+4,IDX+7,IDX+12/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (5)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+9),GBF(IDX+12)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+6),GBF(IDX+8),GBF(IDX+13)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+9,IDX+12/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+6,IDX+8,IDX+13/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (6)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+10),GBF(IDX+13)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+5),GBF(IDX+9)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+10,IDX+13/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+5,IDX+9/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
END SELECT
CASE (4)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+16)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+16/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-3.D0)/)
NCOEF=15**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+5)
PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+16),GBF(IDX+17)/)
PHI(ILA)%contidx(1,1)=IDX+5 ; PHI(ILA)%contidx(2,1:4)=(/IDX+2,IDX+4,IDX+16,IDX+17/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0)
PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-2.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+6),GBF(IDX+16)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+3),GBF(IDX+5),GBF(IDX+18)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+6,IDX+16/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+3,IDX+5,IDX+18/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-2.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (4)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+8) ; PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+4),GBF(IDX+7),GBF(IDX+17),GBF(IDX+19)/)
PHI(ILA)%contidx(1,1)=IDX+8 ; PHI(ILA)%contidx(2,1:4)=(/IDX+4,IDX+7,IDX+17,IDX+19/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0),(0.D0,-1.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (5)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+10),GBF(IDX+18)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+6),GBF(IDX+9),GBF(IDX+21)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+10,IDX+18/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+6,IDX+9,IDX+21/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (6)
PHI(ILA)%nbrofcontractions=(/2,4/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+9),GBF(IDX+17)/)
PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+5),GBF(IDX+8),GBF(IDX+18),GBF(IDX+20)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+9,IDX+17/) ; PHI(ILA)%contidx(2,1:4)=(/IDX+5,IDX+8,IDX+18,IDX+20/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-1.D0)/)
! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
- PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=PHI(ILA)%coefficients(:,:)
CASE (7)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+12) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+10),GBF(IDX+11),GBF(IDX+19)/)
PHI(ILA)%contidx(1,1)=IDX+12 ; PHI(ILA)%contidx(2,1:3)=(/IDX+10,IDX+11,IDX+19/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(3.D0,0.D0)/)
NCOEF=15**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (8)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+13),GBF(IDX+19)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+8),GBF(IDX+12),GBF(IDX+20)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+13,IDX+19/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+8,IDX+12,IDX+20/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (9)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+14),GBF(IDX+20)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+9),GBF(IDX+13),GBF(IDX+21)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+14,IDX+20/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+9,IDX+13,IDX+21/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
CASE (10)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+15),GBF(IDX+21)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+10),GBF(IDX+14)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+15,IDX+21/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+10,IDX+14/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-3.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
NCOEF=15**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
END SELECT
END SELECT
PHI(ILB)%nbrofcontractions(1)=PHI(ILA)%nbrofcontractions(2)
PHI(ILB)%contractions(1,:)=PHI(ILA)%contractions(2,:)
PHI(ILB)%contidx(1,:)=PHI(ILA)%contidx(2,:)
PHI(ILB)%coefficients(1,:)=-CONJG(PHI(ILA)%coefficients(2,:))
PHI(ILB)%nbrofcontractions(2)=PHI(ILA)%nbrofcontractions(1)
PHI(ILB)%contractions(2,:)=PHI(ILA)%contractions(1,:)
PHI(ILB)%contidx(2,:)=PHI(ILA)%contidx(1,:)
PHI(ILB)%coefficients(2,:)=-PHI(ILA)%coefficients(1,:)
IF (UNCONT) THEN
GO TO 1
ELSE
GO TO 2
END IF
4 IF (KINBAL.AND.UKB) STOP 'Option not implemented yet!'
END SUBROUTINE FORMBASIS_relativistic
SUBROUTINE FORMBASIS_nonrelativistic(PHI,NBAS)
! Subroutine that builds the gaussian basis functions for the molecular system considered, from coefficients either read in a file (basis set from the existing literature) or depending on some given parameters (even-tempered basis set).
USE basis_parameters ; USE data_parameters ; USE mathematical_functions ; USE constants
IMPLICIT NONE
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: NBAS
INTEGER :: I,J,K,L,M,IBF,IP,IPIC,ICOEF,NBOPIC
INTEGER,DIMENSION(NBN) :: HAQN
INTEGER,DIMENSION(1,NBN) :: NBASN
INTEGER,DIMENSION(MAQN,NBN) :: NOP,NOC
DOUBLE PRECISION :: NCOEF
DOUBLE PRECISION,DIMENSION(MNOP,MAQN,NBN) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN,NBN) :: CCOEF
ALLOCATE(NBAS(1:1))
IF (LIBRARY) THEN
DO M=1,NBN
CALL READBASIS(Z(M),HAQN(M),NOP(:,M),NOC(:,M),ALPHA(:,:,M),CCOEF(:,:,:,M),NBASN(:,M))
END DO
NBAS=SUM(NBASN,DIM=2)
ALLOCATE(PHI(1:SUM(NBAS)))
IBF=0
DO M=1,NBN
! Loop on the nuclei of the molecular system
DO I=1,HAQN(M)
IF (UNCONT) THEN
DO J=1,NOP(I,M)
DO K=1,NGPMUSC(I)
IBF=IBF+1
PHI(IBF)%center=CENTER(:,M)
PHI(IBF)%center_id=M
PHI(IBF)%nbrofexponents=1
PHI(IBF)%exponents(1)=ALPHA(J,I,M)
PHI(IBF)%coefficients(1)=1.D0
PHI(IBF)%monomialdegree=MDUSC(I,K)
END DO
END DO
ELSE
ICOEF=1
IP=1
DO J=1,NOC(I,M)
NBOPIC=0
DO
IF (CCOEF(ICOEF,J,I,M)==0.D0) EXIT
NBOPIC=NBOPIC+1
IF (ICOEF==NOP(I,M)) EXIT
ICOEF=ICOEF+1
END DO
DO K=1,NGPMUSC(I)
IBF=IBF+1
PHI(IBF)%center=CENTER(:,M)
PHI(IBF)%center_id=M
PHI(IBF)%nbrofexponents=NBOPIC
PHI(IBF)%monomialdegree=MDUSC(I,K)
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
PHI(IBF)%exponents(IPIC)=ALPHA(L,I,M)
! normalization coefficient
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1)/(DFACT(2*PHI(IBF)%monomialdegree(1)-1) &
& *DFACT(2*PHI(IBF)%monomialdegree(2)-1)*DFACT(2*PHI(IBF)%monomialdegree(3)-1)))
PHI(IBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
END DO
END DO
IP=IP+NBOPIC
END DO
END IF
END DO
END DO
ELSE
NBAS=NUMBER_OF_TERMS
open(22)
ALLOCATE(PHI(1:SUM(NBAS)))
DO I=1,SUM(NBAS)
PHI(I)%center=(/0.D0,0.D0,0.D0/)
PHI(I)%nbrofexponents=1
PHI(I)%exponents(1)=FIRST_TERM*COMMON_RATIO**(I-1)
write(22,*)FIRST_TERM*COMMON_RATIO**(I-1)
PHI(I)%coefficients(1)=1.D0
PHI(I)%monomialdegree=(/0,0,0/)
END DO
close(22)
END IF
WRITE(*,'(a,i4)')' Total number of basis functions =',SUM(NBAS)
END SUBROUTINE FORMBASIS_nonrelativistic
SUBROUTINE READBASIS(Z,HAQN,NOP,NOC,ALPHA,CCOEF,NBAS,NGBF)
! Subroutine that reads (for a given chemical element) the coefficients of the functions of a chosen basis in the DALTON library and computes the number of basis functions (and related cartesian gaussian-type orbital functions) for the components of the upper and lower 2-spinors with respect to the indicated options (contracted basis or not, use of the "kinetic balance" process or not, etc...)
! Note: the name (and path) of the file containing the basis name is stored in the variable BASISFILE from the module basis_parameters.
! Z : atomic number of the element under consideration
! MAQN : maximum angular quantum number + 1 (= number of function types) allowed (s=1, p=2, d=3, etc...)
! MNOP : maximum number of primitives of any given type allowed
! MNOC : maximum number of contractions of any given type allowed
! HAQN : highest angular quantum number of the element basis functions + 1
! NOP : array containing the number of primitives of each type of basis function
! NOC : array containing the number of contractions for each type of basis function
! ALPHA : array containing the exponents of the primitives for each type of basis functions
! CCOEF : array containing the contraction coefficients for each type of basis functions
USE case_parameters ; USE basis_parameters
IMPLICIT NONE
INTEGER,INTENT(IN) :: Z
INTEGER,INTENT(OUT) :: HAQN
INTEGER,DIMENSION(MAQN),INTENT(OUT) :: NOP,NOC
DOUBLE PRECISION,DIMENSION(MNOP,MAQN),INTENT(OUT) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN),INTENT(OUT) :: CCOEF
INTEGER,DIMENSION(:),INTENT(OUT) :: NBAS
INTEGER,DIMENSION(2),INTENT(OUT),OPTIONAL :: NGBF
INTEGER :: LUBAS,PRINUM,CONNUM,IDUMMY,I
LOGICAL :: LEX,CHKNELM
LUBAS=20
INQUIRE(FILE=BASISFILE,EXIST=LEX)
IF (LEX) THEN
! Open the file containing the basis
OPEN(UNIT=LUBAS,FILE=BASISFILE,ACTION='READ')
! Search for the right atomic element in this file
CALL FINDELM(Z,BASISFILE,LUBAS)
NOP=0 ; NOC=0 ; HAQN=0
! Find the number of primitives and contractions of each type and read them
1 CALL READPCN(CHKNELM,PRINUM,CONNUM,IDUMMY,BASISFILE,LUBAS)
IF (UNCONT) CONNUM=-CONNUM
IF (.NOT.CHKNELM) THEN
HAQN=HAQN+1
IF (HAQN>MAQN) GO TO 3
NOP(HAQN)=PRINUM ; NOC(HAQN)=CONNUM
! Fill ALPHA and CCOEF by reading the corresponding exponents and contraction coefficients
CALL READECC(MNOP,MNOC,NOP(HAQN),NOC(HAQN),ALPHA(:,HAQN),CCOEF(:,:,HAQN),BASISFILE,LUBAS)
GO TO 1
END IF
CLOSE(LUBAS)
ELSE
GO TO 2
END IF
! Computation of the number of basis functions
IF (RELATIVISTIC) THEN
! relativistic case
NBAS=0 ; NGBF=0
DO I=1,HAQN
IF (UNCONT) THEN
! uncontracted basis
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOP(I)*NGPMUSC(I)
IF (KINBAL) THEN
NGBF(2)=NGBF(2)+NOP(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOP(I)*NGPMLSC(I)
END IF
ELSE
! a priori contracted basis
IF (NOC(I)/=0) THEN
NBAS(1)=NBAS(1)+NOC(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOC(I)*NGPMUSC(I)
ELSE
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOP(I)*NGPMUSC(I)
END IF
IF (KINBAL) THEN
IF (NOC(I)/=0) THEN
NGBF(2)=NGBF(2)+NOC(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOC(I)*NGPMLSC(I)
ELSE
NGBF(2)=NGBF(2)+NOP(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOP(I)*NGPMLSC(I)
END IF
END IF
END IF
END DO
IF (KINBAL.AND..NOT.UKB) NBAS(2)=NBAS(1)
IF (.NOT.KINBAL) THEN
NBAS(2)=NBAS(1) ; NGBF(2)=NGBF(1)
END IF
NBAS=2*NBAS
ELSE
! non-relativistic case
NBAS(1)=0
DO I=1,HAQN
IF (UNCONT) THEN
! uncontracted basis
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
ELSE
! a priori contracted basis
IF (NOC(I)/=0) THEN
NBAS(1)=NBAS(1)+NOC(I)*NGPMUSC(I)
ELSE
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
END IF
END IF
END DO
END IF
RETURN
! MESSAGES
2 WRITE(*,'(a)')' Subroutine READBASIS: the file containing the basis could not be found.'
GO TO 4
3 WRITE(*,'(a)')' Subroutine READBASIS: this type of gaussian basis function is not supported!'
4 STOP
END SUBROUTINE READBASIS
SUBROUTINE FINDELM(Z,BASNAM,LUBAS)
IMPLICIT NONE
INTEGER :: Z,LUBAS
CHARACTER(*) :: BASNAM
CHARACTER(20) :: STRING
CHARACTER :: CHDUMMY
INTEGER :: IDUMMY,IOERR
1 READ(LUBAS,'(a20)',IOSTAT=IOERR,ERR=2,END=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF ((CHDUMMY=='a').OR.(CHDUMMY=='A')) THEN
READ(STRING,'(BN,a1,i4)')CHDUMMY,IDUMMY
IF (Z==IDUMMY) THEN
RETURN
ELSE
GO TO 1
END IF
ELSE
GO TO 1
END IF
! MESSAGES
2 WRITE(*,'(a,a,a,i2,a)')' Subroutine FINDELM: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
3 WRITE(*,'(a,i2,a,a,a)')' Subroutine FINDELM: the basis functions relative to atomic element number ',Z, &
& ' could not be found in the basis ',BASNAM,'.'
STOP
END SUBROUTINE FINDELM
SUBROUTINE READPCN(CHKNELM,PRINUM,CONNUM,INTISG,BASNAM,LUBAS)
IMPLICIT NONE
LOGICAL :: CHKNELM
INTEGER :: PRINUM,CONNUM,INTISG,LUBAS
CHARACTER(*) :: BASNAM
LOGICAL :: BLANK
CHARACTER(88) :: STRING
CHARACTER :: CHDUMMY
INTEGER :: IDUMMY,IOERR
CHKNELM=.FALSE.
1 READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=2,END=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (BLANK) THEN
GO TO 1
ELSE
READ (STRING,'(BN,3i5)')PRINUM,CONNUM,INTISG
RETURN
END IF
ELSE IF ((CHDUMMY=='a').OR.(CHDUMMY=='A')) THEN
CHKNELM=.TRUE.
RETURN
ELSE
GO TO 1
END IF
2 WRITE(*,'(a,a,a,i2,a)')' Subroutine READPCN: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
3 CHKNELM=.TRUE.
RETURN
END SUBROUTINE READPCN
SUBROUTINE READECC(MNOP,MNOC,NOP,NOC,ALPHA,CCOEF,BASNAM,LUBAS)
IMPLICIT NONE
INTEGER :: MNOP,MNOC,NOP,NOC,LUBAS
DOUBLE PRECISION,DIMENSION(MNOP) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC) :: CCOEF
CHARACTER(*) :: BASNAM
INTEGER :: I,J,K,L,IOERR,NUMLIN,NUMRCC,NUM
CHARACTER :: CHDUMMY
CHARACTER(88) :: STRING
LOGICAL :: BLANK
! NUMCCA is the maximum number of contraction coefficients on the first line of a block. If NOC is greater than NUMCCA, the reading of the coefficients will continue on the following line, which contains NUMCCB coefficients at most.
INTEGER,PARAMETER :: NUMCCA=6,NUMCCB=7
ALPHA=0.D0 ; CCOEF=0.D0
J=0
1 IF (J<NOP) THEN
READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (.NOT.BLANK) THEN
! This line contains an exponent and some contraction coefficients
J=J+1
L=ABS(NOC)
CALL CONLIN(L,NUMLIN)
IF (NOC<=0) THEN
! We want an uncontracted basis set: we just read the exponent and skip the continuation lines
READ(STRING,'(f16.9)')ALPHA(J)
CCOEF(J,J)=1.D0
DO I=2,NUMLIN
READ(LUBAS,*)
END DO
GO TO 1
ELSE
! Get the right format for the read statement
IF (NUMLIN==1) THEN
L=NOC
ELSE
L=NUMCCA
END IF
! Read the exponent and contraction coefficients on the first line
READ(STRING,'(f16.9,6f12.9)')ALPHA(J),(CCOEF(J,I),I=1,L)
! If there are more lines with contraction coefficients, read them
DO I=2,NUMLIN
NUMRCC=NUMCCA+(I-1)*NUMCCB
! Get the right format for the read statement
NUM=MIN(NUMRCC,NOC)
2 READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=3)STRING
READ (STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (.NOT.BLANK) THEN
! This line contains contraction coefficients
READ(STRING,'(7f12.9)')(CCOEF(J,K),K=NUMCCA+(I-2)*NUMCCB+1,NUM)
END IF
ELSE
! This line is a blank one, read the next one
GO TO 2
END IF
END DO
GO TO 1
END IF
ELSE
! This line is a blank one, read the next one
GO TO 1
END IF
ELSE
! Skip this line
GO TO 1
END IF
END IF
RETURN
3 WRITE(*,'(a,a,a,i2,a)')' Subroutine READECC: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
END SUBROUTINE READECC
SUBROUTINE CHBLANK(BLANK,STRING)
! Subroutine that checks whether a line is a blank one or not.
IMPLICIT NONE
LOGICAL :: BLANK
CHARACTER*(*) :: STRING
INTEGER :: J
BLANK=.TRUE.
DO J=1,LEN(STRING)
BLANK=BLANK.AND.(STRING(J:J)==' ')
END DO
RETURN
END SUBROUTINE CHBLANK
SUBROUTINE CONLIN(NOC,NUMLIN)
! Subroutine that finds out on how many lines the contraction coefficients are written in a given block (knowing there at most NUMCCA coefficients on the first line and NUMCCB on the following ones), and returns that number.
IMPLICIT NONE
INTEGER :: NOC,NUMLIN
INTEGER,PARAMETER :: NUMCCA=6,NUMCCB=7
IF (NOC<=NUMCCA) THEN
NUMLIN=1
ELSE IF (MOD(NOC-NUMCCA,NUMCCB)==0) THEN
NUMLIN=(NOC-NUMCCA)/NUMCCB+1
ELSE
NUMLIN=(NOC-NUMCCA)/NUMCCB+2
END IF
END SUBROUTINE CONLIN
FUNCTION MDUSC(I,J) RESULT (MONOMIALDEGREE)
! Function that returns the monomial degree of each cartesian gaussian primitive function of shell type "I" (where "I=1" means "s", "I=2" means "p", "I=3" means "d", etc...) appearing in the components of the upper 2-spinor basis functions.
IMPLICIT NONE
INTEGER,INTENT(IN) :: I,J
INTEGER,DIMENSION(3) :: MONOMIALDEGREE
SELECT CASE (I)
CASE (1)
! shell type s (1 associated monomial)
MONOMIALDEGREE=(/0,0,0/)
CASE (2)
! shell type p (3 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/1,0,0/)
CASE (2) ; MONOMIALDEGREE=(/0,1,0/)
CASE (3) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (3)
! shell type d (6 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/2,0,0/)
CASE (2) ; MONOMIALDEGREE=(/1,1,0/)
CASE (3) ; MONOMIALDEGREE=(/1,0,1/)
CASE (4) ; MONOMIALDEGREE=(/0,2,0/)
CASE (5) ; MONOMIALDEGREE=(/0,1,1/)
CASE (6) ; MONOMIALDEGREE=(/0,0,2/)
END SELECT
CASE (4)
! shell type f (10 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/3,0,0/)
CASE (2) ; MONOMIALDEGREE=(/2,1,0/)
CASE (3) ; MONOMIALDEGREE=(/2,0,1/)
CASE (4) ; MONOMIALDEGREE=(/1,2,0/)
CASE (5) ; MONOMIALDEGREE=(/1,0,2/)
CASE (6) ; MONOMIALDEGREE=(/1,1,1/)
CASE (7) ; MONOMIALDEGREE=(/0,3,0/)
CASE (8) ; MONOMIALDEGREE=(/0,2,1/)
CASE (9) ; MONOMIALDEGREE=(/0,1,2/)
CASE (10) ; MONOMIALDEGREE=(/0,0,3/)
END SELECT
END SELECT
END FUNCTION MDUSC
FUNCTION MDLSC(I,J) RESULT (MONOMIALDEGREE)
! Function that returns the monomial degree of each cartesian gaussian primitive function appearing in the components of the lower 2-spinor basis functions when a kinetic balance scheme is applied on the upper 2-spinor basis functions.
! Note: the integer I refers to the shell type of the gaussian basis functions appearing in the components of the upper 2-spinor basis function to which the (R/U)KB scheme is applied (see the function MDUSC above).
IMPLICIT NONE
INTEGER,INTENT(IN) :: I,J
INTEGER,DIMENSION(3) :: MONOMIALDEGREE
SELECT CASE (I)
CASE (1)
! shell type s (3 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/1,0,0/)
CASE (2) ; MONOMIALDEGREE=(/0,1,0/)
CASE (3) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (2)
! shell type p (7 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/2,0,0/)
CASE (2) ; MONOMIALDEGREE=(/1,1,0/)
CASE (3) ; MONOMIALDEGREE=(/1,0,1/)
CASE (4) ; MONOMIALDEGREE=(/0,2,0/)
CASE (5) ; MONOMIALDEGREE=(/0,1,1/)
CASE (6) ; MONOMIALDEGREE=(/0,0,2/)
CASE (7) ; MONOMIALDEGREE=(/0,0,0/)
END SELECT
CASE (3)
! shell type d (13 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/3,0,0/)
CASE (2) ; MONOMIALDEGREE=(/2,1,0/)
CASE (3) ; MONOMIALDEGREE=(/2,0,1/)
CASE (4) ; MONOMIALDEGREE=(/1,2,0/)
CASE (5) ; MONOMIALDEGREE=(/1,0,2/)
CASE (6) ; MONOMIALDEGREE=(/1,1,1/)
CASE (7) ; MONOMIALDEGREE=(/0,3,0/)
CASE (8) ; MONOMIALDEGREE=(/0,2,1/)
CASE (9) ; MONOMIALDEGREE=(/0,1,2/)
CASE (10) ; MONOMIALDEGREE=(/0,0,3/)
CASE (11) ; MONOMIALDEGREE=(/1,0,0/)
CASE (12) ; MONOMIALDEGREE=(/0,1,0/)
CASE (13) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (4)
! shell type f (21 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/4,0,0/)
CASE (2) ; MONOMIALDEGREE=(/3,1,0/)
CASE (3) ; MONOMIALDEGREE=(/3,0,1/)
CASE (4) ; MONOMIALDEGREE=(/2,2,0/)
CASE (5) ; MONOMIALDEGREE=(/2,1,1/)
CASE (6) ; MONOMIALDEGREE=(/2,0,2/)
CASE (7) ; MONOMIALDEGREE=(/1,3,0/)
CASE (8) ; MONOMIALDEGREE=(/1,2,1/)
CASE (9) ; MONOMIALDEGREE=(/1,1,2/)
CASE (10) ; MONOMIALDEGREE=(/1,0,3/)
CASE (11) ; MONOMIALDEGREE=(/0,4,0/)
CASE (12) ; MONOMIALDEGREE=(/0,3,1/)
CASE (13) ; MONOMIALDEGREE=(/0,2,2/)
CASE (14) ; MONOMIALDEGREE=(/0,1,3/)
CASE (15) ; MONOMIALDEGREE=(/0,0,4/)
CASE (16) ; MONOMIALDEGREE=(/2,0,0/)
CASE (17) ; MONOMIALDEGREE=(/1,1,0/)
CASE (18) ; MONOMIALDEGREE=(/1,0,1/)
CASE (19) ; MONOMIALDEGREE=(/0,2,0/)
CASE (20) ; MONOMIALDEGREE=(/0,1,1/)
CASE (21) ; MONOMIALDEGREE=(/0,0,2/)
END SELECT
END SELECT
END FUNCTION MDLSC
END MODULE
|
antoine-levitt/ACCQUAREL
|
0bb13957507ff78995d98b0c6276757605652b55
|
slightly modified the restricted kinetic balance implementation
|
diff --git a/src/basis.f90 b/src/basis.f90
index 976286d..cdf8a78 100644
--- a/src/basis.f90
+++ b/src/basis.f90
@@ -1,836 +1,842 @@
MODULE basis
USE iso_c_binding
INTEGER,DIMENSION(4),PARAMETER :: NGPMUSC=(/1,3,6,10/)
INTEGER,DIMENSION(4),PARAMETER :: NGPMLSC=(/3,7,13,21/)
INTERFACE FORMBASIS
MODULE PROCEDURE FORMBASIS_relativistic,FORMBASIS_nonrelativistic
END INTERFACE
CONTAINS
SUBROUTINE FORMBASIS_relativistic(PHI,NBAS,GBF,NGBF)
! Subroutine that builds the 2-spinor basis functions and related contracted cartesian Gaussian-type orbital functions for the molecular system considered, from the coefficients read in a file.
- USE basis_parameters ; USE data_parameters ; USE mathematical_functions ; USE constants
+ USE basis_parameters ; USE data_parameters ; USE case_parameters ; USE mathematical_functions ; USE constants
+ IMPLICIT NONE
TYPE(twospinor),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: GBF
INTEGER,DIMENSION(2),INTENT(OUT) :: NGBF
INTEGER,DIMENSION(NBN) :: HAQN
INTEGER,DIMENSION(MAQN,NBN) :: NOP,NOC
DOUBLE PRECISION :: NCOEF
DOUBLE PRECISION,DIMENSION(MNOP,MAQN,NBN) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN,NBN) :: CCOEF
INTEGER,DIMENSION(2,NBN) :: NBASN,NGBFN
INTEGER :: I,J,K,L,M,IUA,IUB,ILA,ILB,IP,IPIC,ICOEF,RNOC,NBOPIC,IUGBF,ILGBF,IDX
ALLOCATE(NBAS(1:2))
DO M=1,NBN
CALL READBASIS(Z(M),HAQN(M),NOP(:,M),NOC(:,M),ALPHA(:,:,M),CCOEF(:,:,:,M),NBASN(:,M),NGBFN(:,M))
END DO
NBAS=SUM(NBASN,DIM=2) ; NGBF=SUM(NGBFN,DIM=2)
ALLOCATE(PHI(1:SUM(NBAS)),GBF(1:SUM(NGBF)))
! Initialization of the indices for the upper 2-spinor basis functions and related gaussian basis functions
IUA=0 ; IUB=NBAS(1)/2 ; IUGBF=0
! Indices for the lower 2-spinor basis functions and related gaussian basis functions
ILA=NBAS(1) ; ILB=NBAS(1)+NBAS(2)/2 ; ILGBF=NGBF(1)
DO M=1,NBN
! Loop on the nuclei of the molecular system
DO I=1,HAQN(M)
IF (UNCONT) THEN
! uncontracted basis
DO J=1,NOP(I,M)
IF (KINBAL) THEN
! Construction of the gaussian primitives related to the lower 2-spinor basis functions when a kinetic balance scheme is used
! note: the coefficients in the contractions are derived from the RKB scheme and put to 1 if the UKB scheme is used.
DO K=1,NGPMLSC(I)
ILGBF=ILGBF+1
GBF(ILGBF)%center=CENTER(:,M)
GBF(ILGBF)%center_id=M
GBF(ILGBF)%nbrofexponents=1
GBF(ILGBF)%exponents(1)=ALPHA(J,I,M)
! note: see how the UKB scheme is to be interpreted before modifying and uncommenting.
! IF (((I==2).AND.(K==7)).OR.((I==3).AND.(K>=11)).OR.((I==4).AND.(K>=16))) THEN
GBF(ILGBF)%coefficients(1)=1.D0
! ELSE
! GBF(ILGBF)%coefficients(1)=2.D0*ALPHA(J,I,M)
! END IF
GBF(ILGBF)%monomialdegree=MDLSC(I,K)
IF (UKB) THEN
! Construction of the lower 2-spinor basis functions (unrestricted kinetic balance scheme)
! (nota bene: this scheme is not really functional due to linear depencies which have yet to be eliminated)
GBF(ILGBF)%coefficients(1)=1.D0
ILA=ILA+1 ; ILB=ILB+1
PHI(ILA)%nbrofcontractions=(/1,0/) ; PHI(ILB)%nbrofcontractions=(/0,1/)
PHI(ILA)%contractions(1,1)=GBF(ILGBF) ; PHI(ILB)%contractions(2,1)=GBF(ILGBF)
PHI(ILA)%contidx(1,1)=ILGBF ; PHI(ILB)%contidx(2,1)=ILGBF
PHI(ILA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(ILB)%coefficients(2,1)=(1.D0,0.D0)
END IF
END DO
END IF
DO K=1,NGPMUSC(I)
! Construction of the uncontracted GBF functions related to the upper 2-spinor basis functions
IUGBF=IUGBF+1
GBF(IUGBF)%center=CENTER(:,M)
GBF(IUGBF)%center_id=M
GBF(IUGBF)%nbrofexponents=1
GBF(IUGBF)%exponents(1)=ALPHA(J,I,M)
GBF(IUGBF)%coefficients(1)=1.D0
GBF(IUGBF)%monomialdegree=MDUSC(I,K)
! Construction of the upper 2-spinor basis functions
IUA=IUA+1 ; IUB=IUB+1
PHI(IUA)%nbrofcontractions=(/1,0/) ; PHI(IUB)%nbrofcontractions=(/0,1/)
PHI(IUA)%contractions(1,1)=GBF(IUGBF) ; PHI(IUB)%contractions(2,1)=GBF(IUGBF)
PHI(IUA)%contidx(1,1)=IUGBF ; PHI(IUB)%contidx(2,1)=IUGBF
PHI(IUA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(IUB)%coefficients(2,1)=(1.D0,0.D0)
! Construction of the lower 2-spinor basis functions (restricted kinetic balance scheme)
ILA=ILA+1 ; ILB=ILB+1
IF (KINBAL.AND..NOT.UKB) GO TO 3
1 END DO
END DO
ELSE
! a priori contracted basis
IF (KINBAL.AND.UKB) GO TO 4
ICOEF=1
IP=1
IF (NOC(I,M)==0) THEN
RNOC=NOP(I,M)
ELSE
RNOC=NOC(I,M)
END IF
DO J=1,RNOC
NBOPIC=0
DO
IF (CCOEF(ICOEF,J,I,M)==0.D0) EXIT
NBOPIC=NBOPIC+1
IF (ICOEF==NOP(I,M)) EXIT
ICOEF=ICOEF+1
END DO
IF (KINBAL) THEN
! Construction of the gaussian basis functions related to the lower 2-spinor basis functions when a kinetic balance scheme is used
DO K=1,NGPMLSC(I)
ILGBF=ILGBF+1
GBF(ILGBF)%center=CENTER(:,M)
GBF(ILGBF)%center_id=M
GBF(ILGBF)%nbrofexponents=NBOPIC
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
GBF(ILGBF)%exponents(IPIC)=ALPHA(L,I,M)
! part of the normalization coefficient depending only on the exponent and the monomial total degree
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1))
! nota bene: the multiplication of the contraction coefficient by the exponent, when needed, is done here.
IF (((I==2).AND.(K==7)).OR.((I==3).AND.(K>=11)).OR.((I==4).AND.(K>=16))) THEN
GBF(ILGBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
ELSE
GBF(ILGBF)%coefficients(IPIC)=ALPHA(L,I,M)*NCOEF*CCOEF(L,J,I,M)
END IF
GBF(ILGBF)%monomialdegree=MDLSC(I,K)
END DO
END DO
END IF
DO K=1,NGPMUSC(I)
! Construction of the gaussian basis functions related to the upper 2-spinor basis functions
IUGBF=IUGBF+1
GBF(IUGBF)%center=CENTER(:,M)
GBF(IUGBF)%center_id=M
GBF(IUGBF)%nbrofexponents=NBOPIC
GBF(IUGBF)%monomialdegree=MDUSC(I,K)
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
GBF(IUGBF)%exponents(IPIC)=ALPHA(L,I,M)
! normalization coefficient
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1)/(DFACT(2*GBF(IUGBF)%monomialdegree(1)-1) &
& *DFACT(2*GBF(IUGBF)%monomialdegree(2)-1)*DFACT(2*GBF(IUGBF)%monomialdegree(3)-1)))
GBF(IUGBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
END DO
! Construction of the upper 2-spinor basis functions
IUA=IUA+1 ; IUB=IUB+1
PHI(IUA)%nbrofcontractions=(/1,0/) ; PHI(IUB)%nbrofcontractions=(/0,1/)
PHI(IUA)%contractions(1,1)=GBF(IUGBF) ; PHI(IUB)%contractions(2,1)=GBF(IUGBF)
PHI(IUA)%contidx(1,1)=IUGBF ; PHI(IUB)%contidx(2,1)=IUGBF
PHI(IUA)%coefficients(1,1)=(1.D0,0.D0) ; PHI(IUB)%coefficients(2,1)=(1.D0,0.D0)
! Construction of the lower 2-spinor basis functions (restricted kinetic balance scheme)
ILA=ILA+1 ; ILB=ILB+1
IF (KINBAL.AND..NOT.UKB) GO TO 3
2 END DO
IP=IP+NBOPIC
END DO
END IF
END DO
END DO
IF (.NOT.KINBAL) THEN
! If no kinetic balance scheme is used, basis functions for the lower 2-spinor are exactly the same as the ones for the upper 2-spinor
DO I=1,NGBF(2)
! HIS IS NOT OPTIMAL IN TERMS OF COMPUTATION...
GBF(NGBF(1)+I)=GBF(I)
END DO
DO I=1,NBAS(2)
PHI(NBAS(1)+I)=PHI(I)
END DO
END IF
WRITE(*,'(a,i4)')' Total number of basis functions =',SUM(NBAS)
RETURN
3 IDX=ILGBF-NGPMLSC(I)
SELECT CASE (I)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,2/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+1),GBF(IDX+2)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:2)=(/IDX+1,IDX+2/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! NOTE: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (2)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+7)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+7/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+5) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+7)/)
PHI(ILA)%contidx(1,1)=IDX+5 ; PHI(ILA)%contidx(2,1:3)=(/IDX+2,IDX+4,IDX+7/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+6),GBF(IDX+7)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+3),GBF(IDX+5)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+6,IDX+7/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+3,IDX+5/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
END SELECT
CASE (3)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+11)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+11/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-2.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+6) ; PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+11),GBF(IDX+12)/)
PHI(ILA)%contidx(1,1)=IDX+6 ; PHI(ILA)%contidx(2,1:4)=(/IDX+2,IDX+4,IDX+11,IDX+12/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-1.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+5),GBF(IDX+11)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+3),GBF(IDX+6),GBF(IDX+13)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+5,IDX+11/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+3,IDX+6,IDX+13/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (4)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+8) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+4),GBF(IDX+7),GBF(IDX+12)/)
PHI(ILA)%contidx(1,1)=IDX+8 ; PHI(ILA)%contidx(2,1:3)=(/IDX+4,IDX+7,IDX+12/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (5)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+9),GBF(IDX+12)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+6),GBF(IDX+8),GBF(IDX+13)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+9,IDX+12/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+6,IDX+8,IDX+13/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (6)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+10),GBF(IDX+13)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+5),GBF(IDX+9)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+10,IDX+13/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+5,IDX+9/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
END SELECT
CASE (4)
SELECT CASE (K)
CASE (1)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+3) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+1),GBF(IDX+2),GBF(IDX+16)/)
PHI(ILA)%contidx(1,1)=IDX+3 ; PHI(ILA)%contidx(2,1:3)=(/IDX+1,IDX+2,IDX+16/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-3.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=15**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (2)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+5)
PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+2),GBF(IDX+4),GBF(IDX+16),GBF(IDX+17)/)
PHI(ILA)%contidx(1,1)=IDX+5 ; PHI(ILA)%contidx(2,1:4)=(/IDX+2,IDX+4,IDX+16,IDX+17/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0)
PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-2.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (3)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+6),GBF(IDX+16)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+3),GBF(IDX+5),GBF(IDX+18)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+6,IDX+16/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+3,IDX+5,IDX+18/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-2.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (4)
PHI(ILA)%nbrofcontractions=(/1,4/)
PHI(ILA)%contractions(1,1)=GBF(IDX+8) ; PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+4),GBF(IDX+7),GBF(IDX+17),GBF(IDX+19)/)
PHI(ILA)%contidx(1,1)=IDX+8 ; PHI(ILA)%contidx(2,1:4)=(/IDX+4,IDX+7,IDX+17,IDX+19/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0),(0.D0,-1.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (5)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+10),GBF(IDX+18)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+6),GBF(IDX+9),GBF(IDX+21)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+10,IDX+18/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+6,IDX+9,IDX+21/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(0.D0,-1.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (6)
PHI(ILA)%nbrofcontractions=(/2,4/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+9),GBF(IDX+17)/)
PHI(ILA)%contractions(2,1:4)=(/GBF(IDX+5),GBF(IDX+8),GBF(IDX+18),GBF(IDX+20)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+9,IDX+17/) ; PHI(ILA)%contidx(2,1:4)=(/IDX+5,IDX+8,IDX+18,IDX+20/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:4)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0),(0.D0,-1.D0)/)
-! part of the normalization coefficient depending only the monomial degrees is equal to 1, so there is nothing more to do here.
+! Note: the part of the normalization coefficient depending only the monomial degrees is equal to 1.
+ PHI(ILA)%coefficients(:,:)=C*PHI(ILA)%coefficients(:,:)
CASE (7)
PHI(ILA)%nbrofcontractions=(/1,3/)
PHI(ILA)%contractions(1,1)=GBF(IDX+12) ; PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+10),GBF(IDX+11),GBF(IDX+19)/)
PHI(ILA)%contidx(1,1)=IDX+12 ; PHI(ILA)%contidx(2,1:3)=(/IDX+10,IDX+11,IDX+19/)
PHI(ILA)%coefficients(1,1)=(0.D0,2.D0) ; PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(3.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=15**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (8)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+13),GBF(IDX+19)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+8),GBF(IDX+12),GBF(IDX+20)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+13,IDX+19/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+8,IDX+12,IDX+20/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-1.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(2.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (9)
PHI(ILA)%nbrofcontractions=(/2,3/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+14),GBF(IDX+20)/)
PHI(ILA)%contractions(2,1:3)=(/GBF(IDX+9),GBF(IDX+13),GBF(IDX+21)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+14,IDX+20/) ; PHI(ILA)%contidx(2,1:3)=(/IDX+9,IDX+13,IDX+21/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-2.D0)/)
PHI(ILA)%coefficients(2,1:3)=(/(0.D0,2.D0),(-2.D0,0.D0),(1.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=3**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
CASE (10)
PHI(ILA)%nbrofcontractions=(/2,2/)
PHI(ILA)%contractions(1,1:2)=(/GBF(IDX+15),GBF(IDX+21)/) ; PHI(ILA)%contractions(2,1:2)=(/GBF(IDX+10),GBF(IDX+14)/)
PHI(ILA)%contidx(1,1:2)=(/IDX+15,IDX+21/) ; PHI(ILA)%contidx(2,1:2)=(/IDX+10,IDX+14/)
PHI(ILA)%coefficients(1,1:2)=(/(0.D0,2.D0),(0.D0,-3.D0)/) ; PHI(ILA)%coefficients(2,1:2)=(/(0.D0,2.D0),(-2.D0,0.D0)/)
-! part of the normalization coefficient depending only the monomial degrees.
NCOEF=15**(-0.5D0)
- PHI(ILA)%coefficients(:,:)=NCOEF*PHI(ILA)%coefficients(:,:)
+ PHI(ILA)%coefficients(:,:)=C*NCOEF*PHI(ILA)%coefficients(:,:)
END SELECT
END SELECT
PHI(ILB)%nbrofcontractions(1)=PHI(ILA)%nbrofcontractions(2)
PHI(ILB)%contractions(1,:)=PHI(ILA)%contractions(2,:)
PHI(ILB)%contidx(1,:)=PHI(ILA)%contidx(2,:)
PHI(ILB)%coefficients(1,:)=-CONJG(PHI(ILA)%coefficients(2,:))
PHI(ILB)%nbrofcontractions(2)=PHI(ILA)%nbrofcontractions(1)
PHI(ILB)%contractions(2,:)=PHI(ILA)%contractions(1,:)
PHI(ILB)%contidx(2,:)=PHI(ILA)%contidx(1,:)
PHI(ILB)%coefficients(2,:)=-PHI(ILA)%coefficients(1,:)
IF (UNCONT) THEN
GO TO 1
ELSE
GO TO 2
END IF
4 IF (KINBAL.AND.UKB) STOP 'Option not implemented yet!'
END SUBROUTINE FORMBASIS_relativistic
SUBROUTINE FORMBASIS_nonrelativistic(PHI,NBAS)
! Subroutine that builds the gaussian basis functions for the molecular system considered, from coefficients either read in a file (basis set from the existing literature) or depending on some given parameters (even-tempered basis set).
USE basis_parameters ; USE data_parameters ; USE mathematical_functions ; USE constants
+ IMPLICIT NONE
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE,INTENT(OUT) :: NBAS
INTEGER :: I,J,K,L,M,IBF,IP,IPIC,ICOEF,NBOPIC
INTEGER,DIMENSION(NBN) :: HAQN
INTEGER,DIMENSION(1,NBN) :: NBASN
INTEGER,DIMENSION(MAQN,NBN) :: NOP,NOC
DOUBLE PRECISION :: NCOEF
DOUBLE PRECISION,DIMENSION(MNOP,MAQN,NBN) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN,NBN) :: CCOEF
ALLOCATE(NBAS(1:1))
IF (LIBRARY) THEN
DO M=1,NBN
CALL READBASIS(Z(M),HAQN(M),NOP(:,M),NOC(:,M),ALPHA(:,:,M),CCOEF(:,:,:,M),NBASN(:,M))
END DO
NBAS=SUM(NBASN,DIM=2)
ALLOCATE(PHI(1:SUM(NBAS)))
IBF=0
DO M=1,NBN
! Loop on the nuclei of the molecular system
DO I=1,HAQN(M)
IF (UNCONT) THEN
DO J=1,NOP(I,M)
DO K=1,NGPMUSC(I)
IBF=IBF+1
PHI(IBF)%center=CENTER(:,M)
PHI(IBF)%center_id=M
PHI(IBF)%nbrofexponents=1
PHI(IBF)%exponents(1)=ALPHA(J,I,M)
PHI(IBF)%coefficients(1)=1.D0
PHI(IBF)%monomialdegree=MDUSC(I,K)
END DO
END DO
ELSE
ICOEF=1
IP=1
DO J=1,NOC(I,M)
NBOPIC=0
DO
IF (CCOEF(ICOEF,J,I,M)==0.D0) EXIT
NBOPIC=NBOPIC+1
IF (ICOEF==NOP(I,M)) EXIT
ICOEF=ICOEF+1
END DO
DO K=1,NGPMUSC(I)
IBF=IBF+1
PHI(IBF)%center=CENTER(:,M)
PHI(IBF)%center_id=M
PHI(IBF)%nbrofexponents=NBOPIC
PHI(IBF)%monomialdegree=MDUSC(I,K)
IPIC=0
DO L=IP,IP+NBOPIC-1
IPIC=IPIC+1
PHI(IBF)%exponents(IPIC)=ALPHA(L,I,M)
! normalization coefficient
NCOEF=SQRT((2.D0*ALPHA(L,I,M)/PI)**1.5D0*(4.D0*ALPHA(L,I,M))**(I-1)/(DFACT(2*PHI(IBF)%monomialdegree(1)-1) &
& *DFACT(2*PHI(IBF)%monomialdegree(2)-1)*DFACT(2*PHI(IBF)%monomialdegree(3)-1)))
PHI(IBF)%coefficients(IPIC)=NCOEF*CCOEF(L,J,I,M)
END DO
END DO
IP=IP+NBOPIC
END DO
END IF
END DO
END DO
ELSE
NBAS=NUMBER_OF_TERMS
open(22)
ALLOCATE(PHI(1:SUM(NBAS)))
DO I=1,SUM(NBAS)
PHI(I)%center=(/0.D0,0.D0,0.D0/)
PHI(I)%nbrofexponents=1
PHI(I)%exponents(1)=FIRST_TERM*COMMON_RATIO**(I-1)
write(22,*)FIRST_TERM*COMMON_RATIO**(I-1)
PHI(I)%coefficients(1)=1.D0
PHI(I)%monomialdegree=(/0,0,0/)
END DO
close(22)
END IF
WRITE(*,'(a,i4)')' Total number of basis functions =',SUM(NBAS)
END SUBROUTINE FORMBASIS_nonrelativistic
SUBROUTINE READBASIS(Z,HAQN,NOP,NOC,ALPHA,CCOEF,NBAS,NGBF)
! Subroutine that reads (for a given chemical element) the coefficients of the functions of a chosen basis in the DALTON library and computes the number of basis functions (and related cartesian gaussian-type orbital functions) for the components of the upper and lower 2-spinors with respect to the indicated options (contracted basis or not, use of the "kinetic balance" process or not, etc...)
! Note: the name (and path) of the file containing the basis name is stored in the variable BASISFILE from the module basis_parameters.
! Z : atomic number of the element under consideration
! MAQN : maximum angular quantum number + 1 (= number of function types) allowed (s=1, p=2, d=3, etc...)
! MNOP : maximum number of primitives of any given type allowed
! MNOC : maximum number of contractions of any given type allowed
! HAQN : highest angular quantum number of the element basis functions + 1
! NOP : array containing the number of primitives of each type of basis function
! NOC : array containing the number of contractions for each type of basis function
! ALPHA : array containing the exponents of the primitives for each type of basis functions
! CCOEF : array containing the contraction coefficients for each type of basis functions
USE case_parameters ; USE basis_parameters
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: Z
INTEGER,INTENT(OUT) :: HAQN
INTEGER,DIMENSION(MAQN),INTENT(OUT) :: NOP,NOC
DOUBLE PRECISION,DIMENSION(MNOP,MAQN),INTENT(OUT) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC,MAQN),INTENT(OUT) :: CCOEF
INTEGER,DIMENSION(:),INTENT(OUT) :: NBAS
INTEGER,DIMENSION(2),INTENT(OUT),OPTIONAL :: NGBF
INTEGER :: LUBAS,PRINUM,CONNUM,IDUMMY,I
LOGICAL :: LEX,CHKNELM
LUBAS=20
INQUIRE(FILE=BASISFILE,EXIST=LEX)
IF (LEX) THEN
! Open the file containing the basis
OPEN(UNIT=LUBAS,FILE=BASISFILE,ACTION='READ')
! Search for the right atomic element in this file
CALL FINDELM(Z,BASISFILE,LUBAS)
NOP=0 ; NOC=0 ; HAQN=0
! Find the number of primitives and contractions of each type and read them
1 CALL READPCN(CHKNELM,PRINUM,CONNUM,IDUMMY,BASISFILE,LUBAS)
IF (UNCONT) CONNUM=-CONNUM
IF (.NOT.CHKNELM) THEN
HAQN=HAQN+1
IF (HAQN>MAQN) GO TO 3
NOP(HAQN)=PRINUM ; NOC(HAQN)=CONNUM
! Fill ALPHA and CCOEF by reading the corresponding exponents and contraction coefficients
CALL READECC(MNOP,MNOC,NOP(HAQN),NOC(HAQN),ALPHA(:,HAQN),CCOEF(:,:,HAQN),BASISFILE,LUBAS)
GO TO 1
END IF
CLOSE(LUBAS)
ELSE
GO TO 2
END IF
! Computation of the number of basis functions
IF (RELATIVISTIC) THEN
! relativistic case
NBAS=0 ; NGBF=0
DO I=1,HAQN
IF (UNCONT) THEN
! uncontracted basis
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOP(I)*NGPMUSC(I)
IF (KINBAL) THEN
NGBF(2)=NGBF(2)+NOP(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOP(I)*NGPMLSC(I)
END IF
ELSE
! a priori contracted basis
IF (NOC(I)/=0) THEN
NBAS(1)=NBAS(1)+NOC(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOC(I)*NGPMUSC(I)
ELSE
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
NGBF(1)=NGBF(1)+NOP(I)*NGPMUSC(I)
END IF
IF (KINBAL) THEN
IF (NOC(I)/=0) THEN
NGBF(2)=NGBF(2)+NOC(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOC(I)*NGPMLSC(I)
ELSE
NGBF(2)=NGBF(2)+NOP(I)*NGPMLSC(I)
IF (UKB) NBAS(2)=NBAS(2)+NOP(I)*NGPMLSC(I)
END IF
END IF
END IF
END DO
IF (KINBAL.AND..NOT.UKB) NBAS(2)=NBAS(1)
IF (.NOT.KINBAL) THEN
NBAS(2)=NBAS(1) ; NGBF(2)=NGBF(1)
END IF
NBAS=2*NBAS
ELSE
! non-relativistic case
NBAS(1)=0
DO I=1,HAQN
IF (UNCONT) THEN
! uncontracted basis
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
ELSE
! a priori contracted basis
IF (NOC(I)/=0) THEN
NBAS(1)=NBAS(1)+NOC(I)*NGPMUSC(I)
ELSE
NBAS(1)=NBAS(1)+NOP(I)*NGPMUSC(I)
END IF
END IF
END DO
END IF
RETURN
! MESSAGES
2 WRITE(*,'(a)')' Subroutine READBASIS: the file containing the basis could not be found.'
GO TO 4
3 WRITE(*,'(a)')' Subroutine READBASIS: this type of gaussian basis function is not supported!'
4 STOP
END SUBROUTINE READBASIS
SUBROUTINE FINDELM(Z,BASNAM,LUBAS)
+ IMPLICIT NONE
INTEGER :: Z,LUBAS
CHARACTER(*) :: BASNAM
CHARACTER(20) :: STRING
CHARACTER :: CHDUMMY
INTEGER :: IDUMMY,IOERR
1 READ(LUBAS,'(a20)',IOSTAT=IOERR,ERR=2,END=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF ((CHDUMMY=='a').OR.(CHDUMMY=='A')) THEN
READ(STRING,'(BN,a1,i4)')CHDUMMY,IDUMMY
IF (Z==IDUMMY) THEN
RETURN
ELSE
GO TO 1
END IF
ELSE
GO TO 1
END IF
! MESSAGES
2 WRITE(*,'(a,a,a,i2,a)')' Subroutine FINDELM: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
3 WRITE(*,'(a,i2,a,a,a)')' Subroutine FINDELM: the basis functions relative to atomic element number ',Z, &
& ' could not be found in the basis ',BASNAM,'.'
STOP
END SUBROUTINE FINDELM
SUBROUTINE READPCN(CHKNELM,PRINUM,CONNUM,INTISG,BASNAM,LUBAS)
+ IMPLICIT NONE
LOGICAL :: CHKNELM
INTEGER :: PRINUM,CONNUM,INTISG,LUBAS
CHARACTER(*) :: BASNAM
LOGICAL :: BLANK
CHARACTER(88) :: STRING
CHARACTER :: CHDUMMY
INTEGER :: IDUMMY,IOERR
CHKNELM=.FALSE.
1 READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=2,END=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (BLANK) THEN
GO TO 1
ELSE
READ (STRING,'(BN,3i5)')PRINUM,CONNUM,INTISG
RETURN
END IF
ELSE IF ((CHDUMMY=='a').OR.(CHDUMMY=='A')) THEN
CHKNELM=.TRUE.
RETURN
ELSE
GO TO 1
END IF
2 WRITE(*,'(a,a,a,i2,a)')' Subroutine READPCN: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
3 CHKNELM=.TRUE.
RETURN
END SUBROUTINE READPCN
SUBROUTINE READECC(MNOP,MNOC,NOP,NOC,ALPHA,CCOEF,BASNAM,LUBAS)
+ IMPLICIT NONE
INTEGER :: MNOP,MNOC,NOP,NOC,LUBAS
DOUBLE PRECISION,DIMENSION(MNOP) :: ALPHA
DOUBLE PRECISION,DIMENSION(MNOP,MNOC) :: CCOEF
CHARACTER(*) :: BASNAM
INTEGER :: I,J,K,L,IOERR,NUMLIN,NUMRCC,NUM
CHARACTER :: CHDUMMY
CHARACTER(88) :: STRING
LOGICAL :: BLANK
! NUMCCA is the maximum number of contraction coefficients on the first line of a block. If NOC is greater than NUMCCA, the reading of the coefficients will continue on the following line, which contains NUMCCB coefficients at most.
INTEGER,PARAMETER :: NUMCCA=6,NUMCCB=7
ALPHA=0.D0 ; CCOEF=0.D0
J=0
1 IF (J<NOP) THEN
READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=3)STRING
READ(STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (.NOT.BLANK) THEN
! This line contains an exponent and some contraction coefficients
J=J+1
L=ABS(NOC)
CALL CONLIN(L,NUMLIN)
IF (NOC<=0) THEN
! We want an uncontracted basis set: we just read the exponent and skip the continuation lines
READ(STRING,'(f16.9)')ALPHA(J)
CCOEF(J,J)=1.D0
DO I=2,NUMLIN
READ(LUBAS,*)
END DO
GO TO 1
ELSE
! Get the right format for the read statement
IF (NUMLIN==1) THEN
L=NOC
ELSE
L=NUMCCA
END IF
! Read the exponent and contraction coefficients on the first line
READ(STRING,'(f16.9,6f12.9)')ALPHA(J),(CCOEF(J,I),I=1,L)
! If there are more lines with contraction coefficients, read them
DO I=2,NUMLIN
NUMRCC=NUMCCA+(I-1)*NUMCCB
! Get the right format for the read statement
NUM=MIN(NUMRCC,NOC)
2 READ(LUBAS,'(a88)',IOSTAT=IOERR,ERR=3)STRING
READ (STRING,'(a1)')CHDUMMY
IF (CHDUMMY==' ') THEN
CALL CHBLANK(BLANK,STRING)
IF (.NOT.BLANK) THEN
! This line contains contraction coefficients
READ(STRING,'(7f12.9)')(CCOEF(J,K),K=NUMCCA+(I-2)*NUMCCB+1,NUM)
END IF
ELSE
! This line is a blank one, read the next one
GO TO 2
END IF
END DO
GO TO 1
END IF
ELSE
! This line is a blank one, read the next one
GO TO 1
END IF
ELSE
! Skip this line
GO TO 1
END IF
END IF
RETURN
3 WRITE(*,'(a,a,a,i2,a)')' Subroutine READECC: an error ocurred during the reading of the file containing the basis ', &
& BASNAM,' (IOSTAT code=',IOERR,') '
STOP
END SUBROUTINE READECC
SUBROUTINE CHBLANK(BLANK,STRING)
! Subroutine that checks whether a line is a blank one or not.
+ IMPLICIT NONE
LOGICAL :: BLANK
CHARACTER*(*) :: STRING
INTEGER :: J
BLANK=.TRUE.
DO J=1,LEN(STRING)
BLANK=BLANK.AND.(STRING(J:J)==' ')
END DO
RETURN
END SUBROUTINE CHBLANK
SUBROUTINE CONLIN(NOC,NUMLIN)
! Subroutine that finds out on how many lines the contraction coefficients are written in a given block (knowing there at most NUMCCA coefficients on the first line and NUMCCB on the following ones), and returns that number.
+ IMPLICIT NONE
INTEGER :: NOC,NUMLIN
INTEGER,PARAMETER :: NUMCCA=6,NUMCCB=7
IF (NOC<=NUMCCA) THEN
NUMLIN=1
ELSE IF (MOD(NOC-NUMCCA,NUMCCB)==0) THEN
NUMLIN=(NOC-NUMCCA)/NUMCCB+1
ELSE
NUMLIN=(NOC-NUMCCA)/NUMCCB+2
END IF
END SUBROUTINE CONLIN
FUNCTION MDUSC(I,J) RESULT (MONOMIALDEGREE)
! Function that returns the monomial degree of each cartesian gaussian primitive function of shell type "I" (where "I=1" means "s", "I=2" means "p", "I=3" means "d", etc...) appearing in the components of the upper 2-spinor basis functions.
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: I,J
INTEGER,DIMENSION(3) :: MONOMIALDEGREE
SELECT CASE (I)
CASE (1)
! shell type s (1 associated monomial)
MONOMIALDEGREE=(/0,0,0/)
CASE (2)
! shell type p (3 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/1,0,0/)
CASE (2) ; MONOMIALDEGREE=(/0,1,0/)
CASE (3) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (3)
! shell type d (6 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/2,0,0/)
CASE (2) ; MONOMIALDEGREE=(/1,1,0/)
CASE (3) ; MONOMIALDEGREE=(/1,0,1/)
CASE (4) ; MONOMIALDEGREE=(/0,2,0/)
CASE (5) ; MONOMIALDEGREE=(/0,1,1/)
CASE (6) ; MONOMIALDEGREE=(/0,0,2/)
END SELECT
CASE (4)
! shell type f (10 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/3,0,0/)
CASE (2) ; MONOMIALDEGREE=(/2,1,0/)
CASE (3) ; MONOMIALDEGREE=(/2,0,1/)
CASE (4) ; MONOMIALDEGREE=(/1,2,0/)
CASE (5) ; MONOMIALDEGREE=(/1,0,2/)
CASE (6) ; MONOMIALDEGREE=(/1,1,1/)
CASE (7) ; MONOMIALDEGREE=(/0,3,0/)
CASE (8) ; MONOMIALDEGREE=(/0,2,1/)
CASE (9) ; MONOMIALDEGREE=(/0,1,2/)
CASE (10) ; MONOMIALDEGREE=(/0,0,3/)
END SELECT
END SELECT
END FUNCTION MDUSC
FUNCTION MDLSC(I,J) RESULT (MONOMIALDEGREE)
! Function that returns the monomial degree of each cartesian gaussian primitive function appearing in the components of the lower 2-spinor basis functions when a kinetic balance scheme is applied on the upper 2-spinor basis functions.
! Note: the integer I refers to the shell type of the gaussian basis functions appearing in the components of the upper 2-spinor basis function to which the (R/U)KB scheme is applied (see the function MDUSC above).
+ IMPLICIT NONE
INTEGER,INTENT(IN) :: I,J
INTEGER,DIMENSION(3) :: MONOMIALDEGREE
SELECT CASE (I)
CASE (1)
! shell type s (3 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/1,0,0/)
CASE (2) ; MONOMIALDEGREE=(/0,1,0/)
CASE (3) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (2)
! shell type p (7 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/2,0,0/)
CASE (2) ; MONOMIALDEGREE=(/1,1,0/)
CASE (3) ; MONOMIALDEGREE=(/1,0,1/)
CASE (4) ; MONOMIALDEGREE=(/0,2,0/)
CASE (5) ; MONOMIALDEGREE=(/0,1,1/)
CASE (6) ; MONOMIALDEGREE=(/0,0,2/)
CASE (7) ; MONOMIALDEGREE=(/0,0,0/)
END SELECT
CASE (3)
! shell type d (13 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/3,0,0/)
CASE (2) ; MONOMIALDEGREE=(/2,1,0/)
CASE (3) ; MONOMIALDEGREE=(/2,0,1/)
CASE (4) ; MONOMIALDEGREE=(/1,2,0/)
CASE (5) ; MONOMIALDEGREE=(/1,0,2/)
CASE (6) ; MONOMIALDEGREE=(/1,1,1/)
CASE (7) ; MONOMIALDEGREE=(/0,3,0/)
CASE (8) ; MONOMIALDEGREE=(/0,2,1/)
CASE (9) ; MONOMIALDEGREE=(/0,1,2/)
CASE (10) ; MONOMIALDEGREE=(/0,0,3/)
CASE (11) ; MONOMIALDEGREE=(/1,0,0/)
CASE (12) ; MONOMIALDEGREE=(/0,1,0/)
CASE (13) ; MONOMIALDEGREE=(/0,0,1/)
END SELECT
CASE (4)
! shell type f (21 associated monomials)
SELECT CASE (J)
CASE (1) ; MONOMIALDEGREE=(/4,0,0/)
CASE (2) ; MONOMIALDEGREE=(/3,1,0/)
CASE (3) ; MONOMIALDEGREE=(/3,0,1/)
CASE (4) ; MONOMIALDEGREE=(/2,2,0/)
CASE (5) ; MONOMIALDEGREE=(/2,1,1/)
CASE (6) ; MONOMIALDEGREE=(/2,0,2/)
CASE (7) ; MONOMIALDEGREE=(/1,3,0/)
CASE (8) ; MONOMIALDEGREE=(/1,2,1/)
CASE (9) ; MONOMIALDEGREE=(/1,1,2/)
CASE (10) ; MONOMIALDEGREE=(/1,0,3/)
CASE (11) ; MONOMIALDEGREE=(/0,4,0/)
CASE (12) ; MONOMIALDEGREE=(/0,3,1/)
CASE (13) ; MONOMIALDEGREE=(/0,2,2/)
CASE (14) ; MONOMIALDEGREE=(/0,1,3/)
CASE (15) ; MONOMIALDEGREE=(/0,0,4/)
CASE (16) ; MONOMIALDEGREE=(/2,0,0/)
CASE (17) ; MONOMIALDEGREE=(/1,1,0/)
CASE (18) ; MONOMIALDEGREE=(/1,0,1/)
CASE (19) ; MONOMIALDEGREE=(/0,2,0/)
CASE (20) ; MONOMIALDEGREE=(/0,1,1/)
CASE (21) ; MONOMIALDEGREE=(/0,0,2/)
END SELECT
END SELECT
END FUNCTION MDLSC
END MODULE
|
antoine-levitt/ACCQUAREL
|
8c1e07a2e0bcfad0e74052ac7f5b84100c6e7b45
|
Fix misleading BUILDTEFM_UHF declaration (the code actually uses BUILDTEFM_RHF)
|
diff --git a/src/matrices.f90 b/src/matrices.f90
index 424c182..faa053f 100644
--- a/src/matrices.f90
+++ b/src/matrices.f90
@@ -543,558 +543,550 @@ SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
CM(J,I)=CM(J,I)+INTGRL*(DM(J,L)+DM(L,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,L)+DM(L,J))
CM(J,L)=CM(J,L)+INTGRL*(DM(J,I)+DM(I,J))
CM(L,J)=CM(L,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
CM(J,I)=CM(J,I)+INTGRL*(DM(J,K)+DM(K,J))
CM(I,J)=CM(I,J)+INTGRL*(DM(J,K)+DM(K,J))
CM(J,K)=CM(J,K)+INTGRL*(DM(J,I)+DM(I,J))
CM(K,J)=CM(K,J)+INTGRL*(DM(J,I)+DM(I,J))
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
CM(I,J)=CM(I,J)+INTGRL*DM(K,K)
CM(J,I)=CM(J,I)+INTGRL*DM(K,K)
CM(K,K)=CM(K,K)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
CM(K,L)=CM(K,L)+INTGRL*DM(I,I)
CM(L,K)=CM(L,K)+INTGRL*DM(I,I)
CM(I,I)=CM(I,I)+INTGRL*(DM(K,L)+DM(L,K))
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
CM(I,J)=CM(I,J)+INTGRL*(DM(K,L)+DM(L,K))
CM(J,I)=CM(J,I)+INTGRL*(DM(K,L)+DM(L,K))
CM(K,L)=CM(K,L)+INTGRL*(DM(I,J)+DM(J,I))
CM(L,K)=CM(L,K)+INTGRL*(DM(I,J)+DM(J,I))
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PCM=PACK(CM,NBAST)
END SUBROUTINE BUILDCOULOMB_nonrelativistic
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
INTEGER :: I,J,K,L,N
CHARACTER(2) :: CLASS
DOUBLE COMPLEX :: INTGRL
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM
EM=(0.D0,0.D0)
DM=UNPACK(PDM,NBAST)
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED')
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the value of the bielectronic integral is computed "on the fly"
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (SEMIDIRECT) THEN
! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals
IF (USEDISK) THEN
READ(LUNIT)I,J,K,L,CLASS
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
CLASS=BITYPE(N)
END IF
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS)
ELSE
IF (USEDISK) THEN
! the value of the bielectronic integral is read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=CBIVALUES(N)
END IF
END IF
END IF
IF ((I/=J).AND.(I==K).AND.(J==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
ELSE
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
END IF
END DO
IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT)
IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_relativistic
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format).
USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM
INTEGER :: I,J,K,L,N
DOUBLE PRECISION :: INTGRL
EM=0.D0
DM=UNPACK(PDM,NBAST)
IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED')
DO N=1,BINMBR
IF (DIRECT) THEN
! the values of the bielectronic integrals are computed "on the fly"
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L))
ELSE
IF (USEDISK) THEN
! the list and values of the bielectronic integrals are read on disk
READ(BIUNIT)I,J,K,L,INTGRL
ELSE
! the list and values of the bielectronic integrals are read in memory
I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4)
INTGRL=RBIVALUES(N)
END IF
END IF
! 1 value for the 4 indices
IF ((I==J).AND.(J==K).AND.(K==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(I,I)
! 2 distinct values for the 4 indices
ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN
EM(I,J)=EM(I,J)+INTGRL*DM(J,J)
EM(J,I)=EM(J,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*(DM(I,J)+DM(J,I))
ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN
EM(L,I)=EM(L,I)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(I,I)
EM(I,I)=EM(I,I)+INTGRL*(DM(L,I)+DM(I,L))
ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN
EM(I,K)=EM(I,K)+INTGRL*DM(I,K)
EM(K,I)=EM(K,I)+INTGRL*DM(K,I)
ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN
EM(I,I)=EM(I,I)+INTGRL*DM(J,J)
EM(J,J)=EM(J,J)+INTGRL*DM(I,I)
EM(I,J)=EM(I,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(I,J)
! 3 distinct values for the 4 indices
ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN
EM(I,I)=EM(I,I)+INTGRL*(DM(J,L)+DM(L,J))
EM(L,I)=EM(L,I)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(L,I)
EM(L,J)=EM(L,J)+INTGRL*DM(I,I)
EM(I,L)=EM(I,L)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(I,L)
EM(J,L)=EM(J,L)+INTGRL*DM(I,I)
ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN
EM(J,J)=EM(J,J)+INTGRL*(DM(I,L)+DM(L,I))
EM(L,J)=EM(L,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(L,J)
EM(L,I)=EM(L,I)+INTGRL*DM(J,J)
EM(J,L)=EM(J,L)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(J,L)
EM(I,L)=EM(I,L)+INTGRL*DM(J,J)
ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN
EM(J,J)=EM(J,J)+INTGRL*(DM(I,K)+DM(K,I))
EM(K,J)=EM(K,J)+INTGRL*DM(J,I)
EM(J,I)=EM(J,I)+INTGRL*DM(K,J)
EM(K,I)=EM(K,I)+INTGRL*DM(J,J)
EM(J,K)=EM(J,K)+INTGRL*DM(I,J)
EM(I,J)=EM(I,J)+INTGRL*DM(J,K)
EM(I,K)=EM(I,K)+INTGRL*DM(J,J)
ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN
EM(K,I)=EM(K,I)+INTGRL*DM(K,J)
EM(K,J)=EM(K,J)+INTGRL*DM(K,I)
EM(I,K)=EM(I,K)+INTGRL*DM(J,K)
EM(J,K)=EM(J,K)+INTGRL*DM(I,K)
ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN
EM(I,K)=EM(I,K)+INTGRL*DM(I,L)
EM(I,L)=EM(I,L)+INTGRL*DM(I,K)
EM(K,I)=EM(K,I)+INTGRL*DM(L,I)
EM(L,I)=EM(L,I)+INTGRL*DM(K,I)
! 4 distinct values for the 4 indices
ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) &
.OR.((I>K).AND.(K>J).AND.(J>L)) &
.OR.((I>K).AND.(K>L).AND.(L>J))) THEN
EM(K,I)=EM(K,I)+INTGRL*DM(L,J)
EM(L,I)=EM(L,I)+INTGRL*DM(K,J)
EM(K,J)=EM(K,J)+INTGRL*DM(L,I)
EM(L,J)=EM(L,J)+INTGRL*DM(K,I)
EM(I,K)=EM(I,K)+INTGRL*DM(J,L)
EM(I,L)=EM(I,L)+INTGRL*DM(J,K)
EM(J,K)=EM(J,K)+INTGRL*DM(I,L)
EM(J,L)=EM(J,L)+INTGRL*DM(I,K)
END IF
END DO
IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT)
PEM=PACK(EM,NBAST)
END SUBROUTINE BUILDEXCHANGE_nonrelativistic
SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
PSAMCM=(0.D0,0.D0)
SELECT CASE (COMPONENT)
CASE (1)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (2)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO L=1,PHI(I)%nbrofcontractions(1)
DO M=1,PHI(J)%nbrofcontractions(2)
VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)))
END DO
END DO
DO L=1,PHI(I)%nbrofcontractions(2)
DO M=1,PHI(J)%nbrofcontractions(1)
VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) &
& *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)))
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (3)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))
END DO
END DO
END DO
PSAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SELECT
END SUBROUTINE BUILDSAMCM
SUBROUTINE BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the orbital angular momentum operator L=x^p (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
INTEGER :: I,J,K,L,M
DOUBLE COMPLEX :: VALUE
POAMCM=(0.D0,0.D0)
SELECT CASE (COMPONENT)
CASE (1)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (2)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
CASE (3)
DO J=1,NBAS(1)
DO I=1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
DO J=NBAS(1)+1,SUM(NBAS)
DO I=NBAS(1)+1,J
VALUE=(0.D0,0.D0)
DO K=1,2
DO L=1,PHI(I)%nbrofcontractions(K)
DO M=1,PHI(J)%nbrofcontractions(K)
VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) &
& *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) &
& -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2))
END DO
END DO
END DO
POAMCM(I+(J-1)*J/2)=VALUE
END DO
END DO
END SELECT
END SUBROUTINE BUILDOAMCM
SUBROUTINE BUILDTAMCM(PTAMCM,PHI,NBAST,NBAS,COMPONENT)
! Computation and assembly of the matrix associated to one of the three components of the total angular momentum operator J=L+S (only the upper triangular part of the matrix is stored in packed format).
USE basis_parameters ; USE integrals
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTAMCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
INTEGER :: COMPONENT
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PSAMCM,POAMCM
CALL BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT)
CALL BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT)
PTAMCM=PSAMCM+POAMCM
END SUBROUTINE BUILDTAMCM
MODULE matrices
INTERFACE FORMDM
SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON)
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
END SUBROUTINE
SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON)
INTEGER,INTENT(IN) :: NBAST,LOON,HOON
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC
END SUBROUTINE
END INTERFACE
INTERFACE BUILDOM
SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
END SUBROUTINE
SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDKPFM
SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDOEFM
SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
INTEGER,DIMENSION(2),INTENT(IN) :: NBAS
END SUBROUTINE
SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
END SUBROUTINE
END INTERFACE
INTERFACE BUILDTEFM
SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
-
- SUBROUTINE BUILDTEFM_UHF(PTEFM,NBAST,PHI,PDMA,PDMB)
- USE basis_parameters
- INTEGER,INTENT(IN) :: NBAST
- DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM
- TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
- DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDMA,PDMB
- END SUBROUTINE
END INTERFACE
INTERFACE BUILDCOULOMB
SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
INTERFACE BUILDEXCHANGE
SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM
END SUBROUTINE
END INTERFACE
END MODULE
|
antoine-levitt/ACCQUAREL
|
d7e431f1acbb9bfcac301ae247808cb702be6ceb
|
Gradient algorithm, RHF and relativistic
|
diff --git a/src/Makefile b/src/Makefile
index f260953..c75a9b0 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -1,98 +1,99 @@
### MAKEFILE PREAMBLE ###
F95 = g95
#F95 = gfortran
#F95 = ifort
# common to compilers and linker
DEBUGFFLAGS = -fbounds-check -fimplicit-none -ffpe-trap=invalid,zero,denormal
PRODFFLAGS = -fimplicit-none
COMMONFLAGS = -O3 -g
FFLAGS = $(PRODFFLAGS) $(COMMONFLAGS)
ifndef ASPICROOT
ASPICROOT=../A.S.P.I.C
endif
ifeq ($(F95),g95)
F95FLAGS = -c $(FLAGS) -fmod=$(MODDIR) $(FFLAGS)
LD = g95
FLIBS = -llapack -lblas -lm
endif
ifeq ($(F95),gfortran)
F95FLAGS = -c $(FLAGS) -fopenmp -J $(MODDIR) $(FFLAGS)
LD = gfortran
FLIBS = -lgomp -llapack -lblas -lm
endif
ifeq ($(F95),ifort)
F95FLAGS = -c $(FLAGS) -module $(MODDIR) $(FFLAGS)
LD = ifort
FLIBS = -llapack -lblas -lm
endif
LDFLAGS = $(COMMONFLAGS)
CPP = g++
CXXFLAGS = -c $(COMMONFLAGS)
## DIRECTORIES ##
TARGET = accquarel.exe
EXEDIR = ../
MODDIR = ../mod/
OBJDIR = ../obj/
SRCDIR = ./
## ASPIC code ##
ASPICINCPATH = -I$(ASPICROOT)/include
ASPICLIBPATH = -L$(ASPICROOT)/lib
XERCESCLIBPATH = -L$(XERCESCROOT)/lib
ifeq ($(shell uname),Darwin)
## cluster osx darwin
ASPICLIBS = $(ASPICLIBPATH) -lgIntegrals -lchemics -lxmlParser -lgaussian -lpolynome -lcontainor -laspicUtils $(XERCESCLIBPATH) -lxerces-c -L/usr/lib/gcc/i686-apple-darwin9/4.0.1 -lstdc++
endif
ifeq ($(shell uname),Linux)
## linux ubuntu
ASPICLIBS = $(ASPICLIBPATH) -lgIntegrals -lchemics -lxmlParser -lgaussian -lpolynome -lcontainor -laspicUtils $(XERCESCLIBPATH) -lxerces-c -L/usr/lib/gcc/i686-linux-gnu/4.4/ -lstdc++
endif
## ACCQUAREL code ##
OBJ = \
$(OBJDIR)expokit.o \
$(OBJDIR)optimization.o \
$(OBJDIR)rootfinding.o \
$(OBJDIR)tools.o \
$(OBJDIR)setup.o \
$(OBJDIR)common.o \
$(OBJDIR)integrals_c.o \
$(OBJDIR)integrals_f.o \
$(OBJDIR)basis.o \
$(OBJDIR)matrices.o \
$(OBJDIR)scf.o \
$(OBJDIR)roothaan.o \
$(OBJDIR)levelshifting.o \
$(OBJDIR)diis.o \
$(OBJDIR)oda.o \
$(OBJDIR)esa.o \
+ $(OBJDIR)gradient.o \
$(OBJDIR)algorithms.o \
$(OBJDIR)drivers.o \
$(OBJDIR)main.o
# Compilation rules
$(TARGET) : $(OBJ)
$(LD) $(LDFLAGS) $(OBJ) -o $(EXEDIR)$(TARGET) $(FLIBS) $(ASPICLIBS)
@echo " ----------- $(TARGET) created ----------- "
$(OBJDIR)%.o : $(SRCDIR)%.f90
$(F95) $(F95FLAGS) -o $@ $<
$(OBJDIR)%.o : $(SRCDIR)%.f
$(F95) $(F95FLAGS) -o $@ $<
$(OBJDIR)%.o : $(SRCDIR)%.cpp
$(CPP) $(CXXFLAGS) -o $@ $(ASPICINCPATH) $<
#
clean :
rm $(EXEDIR)$(TARGET) $(OBJ) $(MODDIR)*.mod
diff --git a/src/algorithms.f90 b/src/algorithms.f90
index 0bc0247..3d01a40 100644
--- a/src/algorithms.f90
+++ b/src/algorithms.f90
@@ -1,94 +1,119 @@
MODULE scf_algorithms
INTERFACE DIIS
SUBROUTINE DIIS_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
SUBROUTINE DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
END INTERFACE
INTERFACE LEVELSHIFTING
SUBROUTINE LEVELSHIFTING_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
SUBROUTINE LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
END INTERFACE
INTERFACE ODA
SUBROUTINE ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
END INTERFACE
INTERFACE ROOTHAAN
SUBROUTINE ROOTHAAN_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
SUBROUTINE ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
USE basis_parameters
INTEGER,INTENT(IN) :: NBAST
DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
DOUBLE PRECISION,INTENT(IN) :: TRSHLD
INTEGER,INTENT(IN) :: MAXITR
LOGICAL,INTENT(IN) :: RESUME
END SUBROUTINE
END INTERFACE
-END MODULE
+
+INTERFACE GRADIENT
+ SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ USE basis_parameters
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
+ DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+ END SUBROUTINE
+ SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ USE basis_parameters
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
+ DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+ END SUBROUTINE
+END INTERFACE
+END MODULE scf_algorithms
diff --git a/src/drivers.f90 b/src/drivers.f90
index 33e5d81..be208d9 100644
--- a/src/drivers.f90
+++ b/src/drivers.f90
@@ -1,536 +1,550 @@
SUBROUTINE DRIVER_relativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools
USE metric_relativistic ; USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF
INTEGER,DIMENSION(2) :: NGBF
INTEGER :: TYPENMBR(3),INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM
DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! POUR L'INSTANT
RESUME=.FALSE.
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS,GBF,NGBF)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Computation and assembly of the core hamiltonian matrix
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR)
IF (DIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE IF (.NOT.DIRECT) THEN
! Precomputation of the bielectronic integrals is preferred to "on the fly" computation
! Precomputation of the bielectronic integrals involving gaussian basis functions
WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF'
CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF)
IF (SEMIDIRECT) THEN
IF (.NOT.USEDISK) THEN
! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(I)
END DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
ELSE
WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions'
IF (USEDISK) THEN
! storage of the list and values of nonzero bielectronic integrals on disk
ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:),BITYPE(1)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
DEALLOCATE(BILIST,BITYPE)
ELSE
! storage of the list and values of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:),BITYPE(1)
CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
CLOSE(LUNIT,STATUS='DELETE')
DEALLOCATE(BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
CASE (2)
CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR)
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (5)
WRITE(*,'(/,a)')' Eric Sere''s algorithm'
CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ CASE (6)
+ WRITE(*,'(/,a)')' Roothaan/Gradient algorithm'
+ CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
END SELECT
END DO
IF (DIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST)
END IF
ELSE
IF (SEMIDIRECT) THEN
IF (USEDISK) THEN
OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,BITYPE)
END IF
CALL DEALLOCATE_INTEGRALS
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,CBIVALUES)
END IF
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_relativistic
SUBROUTINE DRIVER_nonrelativistic
USE case_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic
USE scf_algorithms
IMPLICIT NONE
INTEGER :: NBAST
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
INTEGER :: INFO,I
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
LOGICAL :: RESUME
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=SUM(NBAS)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM
IF (INFO/=0) GOTO 1
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDOEFM(POEFM,PHI,NBAST)
! Creation of the list of the nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR)
IF (DIRECT) THEN
! Computation of the bielectronic integrals will be done "on the fly"
! storage of the list of nonzero bielectronic integrals in memory
ALLOCATE(BILIST(1:BINMBR,1:4))
OPEN(LUNIT,form='UNFORMATTED')
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
END DO
CLOSE(LUNIT,STATUS='DELETE')
ELSE
! Precomputation of the bielectronic integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC,1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
DO I=1,NBALG
SELECT CASE (ALG(I))
CASE (1)
WRITE(*,'(/,a)')' Roothaan''s algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (2)
WRITE(*,'(/,a)')' level-shifting algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (3)
WRITE(*,'(/,a)')' DIIS algorithm'
SELECT CASE (MODEL)
CASE (1)
CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
CASE (4)
WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)'
SELECT CASE (MODEL)
CASE (1)
CALL ODA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
CASE (2)
WRITE(*,*)' Not implemented yet!'
CASE (3)
WRITE(*,*)' Not implemented yet!'
END SELECT
+ CASE(6)
+ WRITE(*,*)' Roothaan/Gradient algorithm'
+ SELECT CASE (MODEL)
+ CASE (1)
+ CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+ CASE (2)
+ WRITE(*,*)' Not implemented yet!'
+ CASE (3)
+ WRITE(*,*)' Not implemented yet!'
+ END SELECT
+
END SELECT
END DO
IF (DIRECT) THEN
DEALLOCATE(BILIST)
ELSE
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
END IF
DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
WRITE(*,*)'(called from subroutine DRIVER)'
STOP
END SUBROUTINE DRIVER_nonrelativistic
SUBROUTINE DRIVER_boson_star
! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars)
USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters
USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions
USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants
INTEGER :: NBAST,ITER,I,J,INFO
INTEGER,TARGET :: RANK
INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS
DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF
DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG
DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC
TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI
LOGICAL :: NUMCONV
! boucle sur la temperature
INTEGER :: K
! test
! DOUBLE PRECISION :: RCOND
! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK
! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK
DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0
! Computation of the discretization basis
CALL FORMBASIS(PHI,NBAS)
NBAST=NBAS(1)
! Computations of the tensors relative to the metric
! - computation and assembly of the overlap matrix
WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix'
ALLOCATE(POM(1:NBAST*(NBAST+1)/2))
CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM
! tests
! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST))
! PA=POM
! CALL DSPTRF('U',NBAST,PA,IPIV,INFO)
! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO)
! DEALLOCATE(PA,WORK,IPIV,IWORK)
! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND
! tests
! - computation of the inverse of the overlap matrix
ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2))
PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM
! - computation of the square root of the overlap matrix
ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2))
PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM
! - computation of the inverse of the square root of the overlap matrix
ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2))
PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM
! - computation of the Cholesky factorization of the overlap matrix
ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2))
PCFOM=POM
CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM
IF (INFO/=0) GO TO 5
! Computation and assembly of the matrix of the free hamiltonian
WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix'
ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2))
CALL BUILDKPFM(POEFM,PHI,NBAST)
! Creation of the list of nonzero bielectronic integrals
WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals'
CALL BUILDBILIST(PHI,NBAS,BINMBR)
! Computation of the Coulomb integrals
WRITE(*,'(a)')'* Computation of the bielectronic integrals'
IF (USEDISK) THEN
ALLOCATE(BILIST(1:1,1:4))
OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(1,:)
WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
DEALLOCATE(BILIST)
CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT)
ELSE
ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR))
OPEN(LUNIT,form='UNFORMATTED')
!$OMP PARALLEL DO SCHEDULE(STATIC, 1)
DO I=1,BINMBR
READ(LUNIT)BILIST(I,:)
RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)))
IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done'
END DO
!$OMP END PARALLEL DO
CLOSE(LUNIT,STATUS='DELETE')
END IF
!
! SCF CYCLES
!
ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST))
ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2))
ALLOCATE(LAMBDA(1:NBAST))
ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2))
! Initialisation
CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
OPEN(33)
DO I=1,NBAST
write(33,*)EIG(I)
END DO
CLOSE(33)
RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM
PDM1=0.D0
LAMBDA=0.D0 ;
! IF (TEMPERATURE==0) LAMBDA(1)=MASS
LAMBDA(1)=MASS
ETOT1=0.D0
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
DO K=0,1000
! TEMPERATURE LOOP
TEMPERATURE=DBLE(K)*0.0001
ITER=0
! ROOTHAAN'S ALGORITHM LOOP
1 CONTINUE
ITER=ITER+1
WRITE(*,*)' '
WRITE(*,*)'# ITER =',ITER
! Assembly and diagonalization of the Fock matrix associated to the density matrix
PFM=POEFM+PTEFM
CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO)
IF (INFO/=0) GO TO 6
IF (TEMPERATURE>0.D0) THEN
! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix
MU_I=>EIG ; RANK_P=>RANK
MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16)
WRITE(*,*)'mu=',MU
WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU)
! Computation of the updated occupation numbers
DO I=1,NBAST
IF (MU-EIG(I)>0.D0) THEN
LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE)
RANK=I
ELSE
LAMBDA(I)=0.D0
END IF
! WRITE(*,*)'lambda_',I,'=',LAMBDA(I)
END DO
write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA)
END IF
! Assembly of the density matrix
PDM1=PDM ; PDM=0.D0
DO I=1,RANK
CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM)
END DO
! Computation of the energy associated to the density matrix
CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM)
PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI)
ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST)
WRITE(*,*)'E(D_n)=',ETOT
! Numerical convergence check
CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
IF (NUMCONV) THEN
! Convergence reached
GO TO 2
ELSE IF (ITER==MAXITR) THEN
! Maximum number of iterations reached without convergence
GO TO 3
ELSE
! Convergence not reached, increment
ETOT1=ETOT
GO TO 1
END IF
! MESSAGES
2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
WRITE(33,*)TEMPERATURE,ETOT,MU,RANK
! plot of the eigenfunction associated a pure state
IF (RANK==1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a pure state.'
OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE')
DO J=1,NBAST
WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\'
DO I=1,NBAST
IF (EIGVEC(I,J)>=0.D0) THEN
WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
ELSE
WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\'
END IF
END DO
WRITE(9,*)')'
END DO
CLOSE(9)
ELSE IF (RANK>1) THEN
WRITE(*,*)' '
WRITE(*,*)'The minimizer is achieved by a mixed state.'
END IF
GO TO 4
3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.'
OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
DO I=1,NBAST
WRITE(9,*)I,EIG(I)
END DO
CLOSE(9)
! GO TO 4
4 CONTINUE
END DO
DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1)
DEALLOCATE(PTTEFM,PTDM,PDMDIF)
IF (USEDISK) THEN
OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE')
ELSE
DEALLOCATE(BILIST,RBIVALUES)
END IF
GO TO 7
RETURN
5 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, &
&and the factorization could not be completed'
END IF
6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)'
7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI)
END SUBROUTINE DRIVER_boson_star
diff --git a/src/gradient.f90 b/src/gradient.f90
new file mode 100644
index 0000000..7b08241
--- /dev/null
+++ b/src/gradient.f90
@@ -0,0 +1,261 @@
+SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
+! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output
+ USE esa_mod
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION :: EPS
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
+ DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS
+ TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+
+ INTEGER :: ITER,LOON,INFO,I
+ DOUBLE PRECISION :: ETOT,ETOT1
+ DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM
+ LOGICAL :: NUMCONV
+
+! INITIALIZATION AND PRELIMINARIES
+ ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(PPM(1:NBAST*(NBAST+1)/2))
+
+ ITER=0
+ PDM=(0.D0,0.D0)
+ PTEFM=(0.D0,0.D0)
+ ETOT1=0.D0
+ OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
+ OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
+ OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
+
+! LOOP
+1 CONTINUE
+ ITER=ITER+1
+ WRITE(*,'(a)')' '
+ WRITE(*,'(a,i3)')'# ITER = ',ITER
+
+! Assembly and diagonalization of the Fock matrix
+ PFM=POEFM+PTEFM
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+! Assembly of the density matrix according to the aufbau principle
+ CALL CHECKORB(EIG,NBAST,LOON)
+ PDM1=PDM
+ CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1)
+! Computation of the energy associated to the density matrix
+ CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'E(D_n)=',ETOT
+! Numerical convergence check
+ CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ IF (NUMCONV) THEN
+! Convergence reached
+ GO TO 2
+ ELSE IF (ITER==MAXITR) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 3
+ ELSE
+! Convergence not reached, increment
+ ETOT1=ETOT
+ GO TO 1
+ END IF
+! MESSAGES
+2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,'(i4,e22.14)')I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 5
+3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,'(i4,e22.14)')I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 6
+4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
+5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
+ CLOSE(16) ; CLOSE(17) ; CLOSE(18)
+ STOP
+
+ ! Gradient algorithm
+6 WRITE(*,*) ' '
+ WRITE(*,*) 'Switching to gradient algorithm'
+ WRITE(*,*) ' '
+ ITER = 0
+7 ITER=ITER+1
+ WRITE(*,'(a)')' '
+ WRITE(*,'(a,i3)')'# ITER = ',ITER
+
+! Assembly and diagonalization of the Fock matrix
+ PFM=POEFM+PTEFM
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+
+ ! computation of the commutator
+ EPS = .1
+ PDM1 = PDM
+ ! CMT in ON basis = DF - Sm1 F D S
+ CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
+ MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
+ PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
+ UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
+
+ PPM = THETA(PDM,POEFM,NBAST,PHI,'D')
+ PDM = PPM
+
+! Computation of the energy associated to the density matrix
+ CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'E(D_n)=',ETOT
+ ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
+! Numerical convergence check
+ CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ IF (NUMCONV) THEN
+! Convergence reached
+ ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
+ GO TO 2
+ ELSE IF (ITER==200*MAXITR) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 5
+ ELSE
+! Convergence not reached, increment
+ ETOT1=ETOT
+ GO TO 7
+ END IF
+END SUBROUTINE GRADIENT_relativistic
+
+SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME)
+! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism).
+! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951.
+ USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions
+ USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output
+ IMPLICIT NONE
+ INTEGER,INTENT(IN) :: NBAST
+ DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC
+ DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM
+ DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS
+ TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI
+ DOUBLE PRECISION,INTENT(IN) :: TRSHLD
+ INTEGER,INTENT(IN) :: MAXITR
+ LOGICAL,INTENT(IN) :: RESUME
+
+ INTEGER :: ITER,INFO,I
+ DOUBLE PRECISION :: ETOT,ETOT1,EPS
+ DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1
+ LOGICAL :: NUMCONV
+
+
+! INITIALIZATION AND PRELIMINARIES
+ ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2))
+ ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2))
+
+ ITER=0
+ PDM=(0.D0,0.D0)
+ PTEFM=(0.D0,0.D0)
+ ETOT1=0.D0
+ OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write')
+ OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write')
+ OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write')
+
+! LOOP
+1 CONTINUE
+ ITER=ITER+1
+ WRITE(*,'(a)')' '
+ WRITE(*,'(a,i3)')'# ITER = ',ITER
+
+! Assembly and diagonalization of the Fock matrix
+ PFM=POEFM+PTEFM
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+! Assembly of the density matrix according to the aufbau principle
+ PDM1 = PDM
+ CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2)
+! Computation of the energy associated to the density matrix
+ CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'E(D_n)=',ETOT
+! Numerical convergence check
+ CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ IF (NUMCONV) THEN
+! Convergence reached
+ GO TO 2
+ ELSE IF (ITER==MAXITR) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 3
+ ELSE
+! Convergence not reached, increment
+ ETOT1=ETOT
+ GO TO 1
+ END IF
+! MESSAGES
+2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,'(i4,e22.14)')I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 5
+3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).'
+ OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE')
+ DO I=1,NBAST
+ WRITE(9,'(i4,e22.14)')I,EIG(I)
+ END DO
+ CLOSE(9)
+ GO TO 6
+4 WRITE(*,*)'(called from subroutine ROOTHAAN)'
+5 DEALLOCATE(PDM,PDM1,PTEFM,PFM)
+ CLOSE(16) ; CLOSE(17) ; CLOSE(18)
+ STOP
+
+ ! Gradient algorithm
+6 WRITE(*,*) ' '
+ WRITE(*,*) 'Switching to gradient algorithm'
+ WRITE(*,*) ' '
+ ITER = 0
+7 ITER=ITER+1
+ WRITE(*,'(a)')' '
+ WRITE(*,'(a,i3)')'# ITER = ',ITER
+
+! Assembly and diagonalization of the Fock matrix
+ PFM=POEFM+PTEFM
+ CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO)
+ IF (INFO/=0) GO TO 4
+
+ ! computation of the commutator
+ EPS = .05
+ PDM1 = PDM
+ ! CMT in ON basis = DF - Sm1 F D S
+ CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - &
+ MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST))
+ PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),&
+ UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST)
+
+! Computation of the energy associated to the density matrix
+ CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM)
+ ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST)
+ WRITE(*,*)'E(D_n)=',ETOT
+ ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
+! Numerical convergence check
+ CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV)
+ IF (NUMCONV) THEN
+! Convergence reached
+ ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT)
+ GO TO 2
+ ELSE IF (ITER==1000*MAXITR+200) THEN
+! Maximum number of iterations reached without convergence
+ GO TO 5
+ ELSE
+! Convergence not reached, increment
+ ETOT1=ETOT
+ GO TO 7
+ END IF
+END SUBROUTINE
|
antoine-levitt/ACCQUAREL
|
598cc593927dafadac44d0bd055e041f13fc1499
|
Fix typo in expokit wrappers
|
diff --git a/src/tools.f90 b/src/tools.f90
index 370176e..b2dc266 100644
--- a/src/tools.f90
+++ b/src/tools.f90
@@ -324,656 +324,656 @@ FUNCTION INVERSE_real(A,N) RESULT(INVA)
IF (INFO/=0) GOTO 1
CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_real
FUNCTION INVERSE_complex(A,N) RESULT(INVA)
! Function that computes the inverse of a square complex matrix.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N) :: A
DOUBLE COMPLEX,DIMENSION(N,N) :: INVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
INVA=A
CALL ZGETRF(N,N,INVA,N,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the factor U is exactly singular, and division by zero will &
&occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_complex
FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA)
! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: WORK
PINVA=PA
CALL DSPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_symmetric
FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA)
! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA
INTEGER :: INFO
INTEGER,DIMENSION(N) :: IPIV
DOUBLE COMPLEX,DIMENSION(N) :: WORK
PINVA=PA
CALL ZHPTRF('U',N,PINVA,IPIV,INFO)
IF (INFO/=0) GOTO 1
CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO)
IF (INFO/=0) GOTO 2
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization &
&has been completed, but the block diagonal matrix D is exactly singular, and division &
&by zero will occur if it is used to solve a system of equations'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; &
&the matrix is singular and its inverse could not be computed'
END IF
3 WRITE(*,*)'(called from function INVERSE)'
STOP
END FUNCTION INVERSE_hermitian
FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA)
! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_symmetric
FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA)
! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA
INTEGER :: INFO,I
INTEGER,DIMENSION(N) :: IPIV
DOUBLE PRECISION,DIMENSION(N) :: EIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M
PSQRA=PA
CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GOTO 1
FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I)
PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N)
RETURN
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, &
&'off-diagonal elements of an intermediate tridiagonal form did not converge to zero'
END IF
WRITE(*,*)'(called from function SQUARE_ROOT)'
STOP
END FUNCTION SQUARE_ROOT_hermitian
FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE)
! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE PRECISION :: TRACE
INTEGER :: I
TRACE=0.D0
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_symmetric
FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE)
! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA
DOUBLE COMPLEX :: TRACE
INTEGER :: I
TRACE=(0.D0,0.D0)
DO I=1,N
TRACE=TRACE+PA((I+1)*I/2)
END DO
END FUNCTION TRACE_hermitian
FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square matrices A and B.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: TRACE
INTEGER :: I,J
TRACE=0.D0
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_real
FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE)
! Function that computes the trace of the product of two square complex matrices A and B.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J
TRACE=(0.D0,0.D0)
DO I=1,N
DO J=1,N
TRACE=TRACE+A(I,J)*B(J,I)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_complex
FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE PRECISION :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=0.D0
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*PB(IJ)
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+PA(JI)*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_symmetric
FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE)
! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB
DOUBLE COMPLEX :: TRACE
INTEGER :: I,J,IJ,JI
TRACE=(0.D0,0.D0)
DO J=1,N
DO I=1,J
IJ=I+(J-1)*J/2
TRACE=TRACE+PA(IJ)*CONJG(PB(IJ))
END DO
DO I=J+1,N
JI=J+(I-1)*I/2
TRACE=TRACE+CONJG(PA(JI))*PB(JI)
END DO
END DO
END FUNCTION TRACEOFPRODUCT_hermitian
FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE PRECISION :: FIP
INTEGER :: I,J
FIP=0.D0
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*B(I,J)
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_real
FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP)
! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B
DOUBLE COMPLEX :: FIP
INTEGER :: I,J
FIP=(0.D0,0.D0)
DO I=1,N
DO J=1,N
FIP=FIP+A(I,J)*CONJG(B(I,J))
END DO
END DO
END FUNCTION FROBENIUSINNERPRODUCT_complex
FUNCTION NORM_real(M,N,CHAR) RESULT (NORM)
! Function that computes the Frobenius or infinity norm of a square real matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANGE
IF (CHAR=='F') THEN
NORM=DLANGE('F',N,N,M,N,WORK)
ELSE IF (CHAR=='I') THEN
NORM=DLANGE('I',N,N,M,N,WORK)
ELSE
STOP'undefined matrix norm'
END IF
END FUNCTION NORM_real
FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM)
! Function that computes the Frobenius or infinity norm of a square complex matrix (i.e., $\|M\|_F=\sqrt{\sum_{i,j=1}^n|m_{ij}|^2}$).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANGE
IF (CHAR=='F') THEN
NORM=ZLANGE('F',N,N,M,N,WORK)
ELSE IF (CHAR=='I') THEN
NORM=ZLANGE('I',N,N,M,N,WORK)
ELSE
STOP'undefined matrix norm'
END IF
END FUNCTION NORM_complex
FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM)
! Function that returns the Frobenius norm, the infinity norm or the one norm of a symmetric matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: DLANSP
IF (CHAR=='F') THEN
NORM=DLANSP('F','U',N,PM,WORK)
ELSE IF (CHAR=='I') THEN
NORM=DLANSP('I','U',N,PM,WORK)
ELSE IF (CHAR=='1') THEN
NORM=DLANSP('1','U',N,PM,WORK)
ELSE
STOP'Function NORM: undefined matrix norm.'
END IF
END FUNCTION NORM_symmetric
FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM)
! Function that returns the Frobenius norm, the infinity norm or the one norm of a hermitian matrix, which upper triangular part is stored in packed format.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM
CHARACTER(1),INTENT(IN) :: CHAR
DOUBLE PRECISION :: NORM
DOUBLE PRECISION,DIMENSION(N) :: WORK
DOUBLE PRECISION,EXTERNAL :: ZLANHP
IF (CHAR=='F') THEN
NORM=ZLANHP('F','U',N,PM,WORK)
ELSE IF (CHAR=='I') THEN
NORM=ZLANHP('I','U',N,PM,WORK)
ELSE IF (CHAR=='1') THEN
NORM=ZLANHP('1','U',N,PM,WORK)
ELSE
STOP'Function NORM: undefined matrix norm.'
END IF
END FUNCTION NORM_hermitian
SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's DSPGV subroutine.
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N) :: WORK
DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL DSPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_symmetric_prefactorized
SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO)
! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format.
! Note: it is a simplification of LAPACK's ZHPGV subroutine.
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB
DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG
DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC
INTEGER,INTENT(OUT) :: INFO
INTEGER :: I,NEIG
DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK
DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP
AP=PA ; BP=PCFB
! Transform problem to standard eigenvalue problem and solve
CALL ZHPGST(1,'U',N,AP,BP,INFO)
IF (INFO/=0) GO TO 1
CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO)
IF (INFO/=0) GO TO 2
! Backtransform eigenvectors to the original problem
NEIG=N
IF (INFO>0) NEIG=INFO-1
DO I=1,NEIG
CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1)
END DO
RETURN
! MESSAGES
1 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value'
END IF
GO TO 3
2 IF (INFO<0) THEN
WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value'
ELSE
WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements &
&of an intermediate tridiagonal form did not converge to zero'
END IF
3 WRITE(*,*)'(called from subroutine EIGENSOLVER)'
RETURN
END SUBROUTINE EIGENSOLVER_hermitian_prefactorized
FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE PRECISION,DIMENSION(N,N) :: C
DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_symmetric
FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C)
! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly).
INTEGER,INTENT(IN) :: N
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS
DOUBLE COMPLEX,DIMENSION(N,N) :: C
DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S
A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N)
C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A))
END FUNCTION COMMUTATOR_hermitian
function EXPONENTIAL_real(t,H,N) result(expH)
! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
! from http://fortranwiki.org/fortran/show/Expokit
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, intent(in) :: t
DOUBLE PRECISION, dimension(N,N), intent(in) :: H
DOUBLE PRECISION, dimension(N,N) :: expH
! Expokit variables
integer, parameter :: ideg = 6
- DOUBLE PRECISION, dimension(4*N + ideg + 1) :: wsp
+ DOUBLE PRECISION, dimension(4*N*N + ideg + 1) :: wsp
integer, dimension(N) :: iwsp
integer :: iexp, ns, iflag
call DGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
end function
-function EXPONENTIAL_complex(t, H,N) result(expH)
+function EXPONENTIAL_complex(t,H,N) result(expH)
! Calculate exp(t*H) for an N-by-N matrix H using Expokit.
! from http://fortranwiki.org/fortran/show/Expokit
INTEGER,INTENT(IN) :: N
DOUBLE PRECISION, intent(in) :: t
DOUBLE COMPLEX, dimension(N,N), intent(in) :: H
DOUBLE COMPLEX, dimension(N,N) :: expH
! Expokit variables
external :: ZGPADM
integer, parameter :: ideg = 6
DOUBLE COMPLEX, dimension(4*N*N + ideg + 1) :: wsp
integer, dimension(N) :: iwsp
integer :: iexp, ns, iflag
call ZGPADM(ideg, N, t, H, N, wsp, size(wsp,1), iwsp, iexp, ns, iflag)
expH = reshape(wsp(iexp:iexp+N*N-1), shape(expH))
end function
SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a symmetric matrix of size N*N stored in packed format.
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_symmetric
SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT)
! Subroutine that prints in the file LOGUNIT a hermitian matrix of size N*N stored in packed format.
INTEGER,INTENT(IN) :: N,LOGUNIT
DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT
INTEGER :: I,J,IJ
OPEN(UNIT=LOGUNIT)
WRITE(LOGUNIT,*)N
DO I=1,N
DO J=1,N
IF (J<I) THEN
WRITE(LOGUNIT,'(2I3,a6)')I,J,' x'
ELSE
WRITE(LOGUNIT,'(2I3,2E20.12)')I,J,PMAT(I+(J-1)*J/2)
END IF
END DO
END DO
CLOSE(LOGUNIT)
END SUBROUTINE PRINTMATRIX_hermitian
END MODULE
MODULE mathematical_functions
INTERFACE DFACT
MODULE PROCEDURE DOUBLE_FACTORIAL
END INTERFACE
CONTAINS
FUNCTION FACTORIAL(N) RESULT(FACT)
INTEGER,INTENT(IN) :: N
INTEGER :: FACT
INTEGER :: I
IF (N<0) THEN
STOP'Function FACTORIAL: the factorial is undefined for negative integers.'
ELSE
FACT=1
IF (N>1) THEN
DO I=2,N
FACT=FACT*I
END DO
END IF
END IF
END FUNCTION FACTORIAL
FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT)
INTEGER,INTENT(IN) :: N
INTEGER :: DFACT
INTEGER :: I
IF (N<-1) THEN
STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.'
ELSE
DFACT=1
IF (N>1) THEN
I=N
DO WHILE (I>1)
DFACT=DFACT*I
I=I-2
END DO
END IF
END IF
END FUNCTION DOUBLE_FACTORIAL
END MODULE
MODULE setup_tools
! name of the setup file
CHARACTER(100) :: SETUP_FILE
CONTAINS
SUBROUTINE SETUP_FILENAME
! Subroutine that retrieves the name of the setup file
CALL GETARG(1,SETUP_FILE)
IF (SETUP_FILE=='') SETUP_FILE='setup'
END SUBROUTINE SETUP_FILENAME
SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO)
! Subroutine that looks for a given text string in an open unit.
INTEGER,INTENT(IN) :: NUNIT
INTEGER,INTENT(OUT) :: INFO
CHARACTER(*),INTENT(IN) :: SUBSTRING
CHARACTER(80) :: STRING
INFO=0
1 READ(100,'(a)',ERR=2,END=2) STRING
IF (INDEX(STRING,SUBSTRING)==0) GOTO 1
RETURN
2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.'
INFO=1
END SUBROUTINE LOOKFOR
END MODULE
|
alvinj/JustWrite
|
24a370abcf344bf9740036a21890de737c7a0380
|
Quick update to the README file.
|
diff --git a/README b/README
index 53726dd..8bf1ad4 100644
--- a/README
+++ b/README
@@ -1,65 +1,76 @@
JustWrite - a Mac OS X "Full Screen Editor" application
June 20, 2010
INTRODUCTION
I created JustWrite as an experiment to see if I could create a full-screen,
plain text editor on Mac OS X using Java.
The idea to create a full-screen editor was inspired in part by an
application I wrote named WikiTeX, which lets me place a "curtain"
behind the editor to hide my desktop, and my Hyde application
(http://www.devdaily.com/hide-desktop-and-desktop-icons), whose only
purpose is to hide a Mac OS X desktop to let you focus on your
foreground application (whatever that foreground app might be).
+
LICENSE
JustWrite is Copyright 2010, Alvin Alexander, http://devdaily.com.
This software is released under the terms of the GNU GPL Version 3;
see the LICENSE file included with this software, or
http://www.gnu.org/licenses/gpl.html for more information.
+
LIBRARIES USED
JustWrite uses the following open source libraries:
* Quaqua (http://www.randelshofer.ch/quaqua/)
* Jgoodies (http://www.jgoodies.com/)
+
VERSION
There is no official version of this application yet.
+
BUILDING THE APPLICATION
You can just run "ant" from the "build" directory to get this build to run, BUT,
you will need Ant installed, and will need to properly install the jarbundler jar
file into your ant/lib folder. See the "Mac OS X JarBundler Ant Task"
project (http://informagen.com/JarBundler/) for more information on that.
Running the "ant" command from the build directory will create a complete build
of the JustWrite application, i.e., the JustWrite.app folder. This folder will
be created in the "release" directory of this project.
+
RUNNING THE APPLICATION
To run the application, you can just cd over to the "release" folder, and then
type this command:
open JustWrite.app
Or, if you prefer, you can double-click the application icon from the Mac Finder.
+
ABOUT THE ICON
Like everything else here, the current icon needs some work. The current icon is
a heavily modified version of an icon that I first found on the MouseRunner.com
website, and is released under the Creative Commons license. See
http://www.mouserunner.com/ for more information.
+MORE INFORMATION
+
+Imagen was created by Alvin Alexander of http://www.devdaily.com
+
+Please see the devdaily.com website for more information.
|
bjornstar/TumTaster
|
ff6642375ebf196c655df619307de2fdd703a04c
|
v1.0.2 - 2019-09-17
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b7cdd7..276d024 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,40 +1,43 @@
#@bjornstar/TumTaster Changelog
+## v1.0.2 - 2019-09-17
+* Add `build.sh` to generate zip file
+
## v1.0.1 - 2019-09-17
* Do not create or check in `package-lock.json`
## v1.0.0 - 2019-09-16
* Only request track and playlist details from soundcloud once per session per id
* Rename HISTORY.md to CHANGELOG.md
* Add scope to title in README and CHANGELOG
* Start linting using `eslint`
## v0.7.1 - 2017-09-13
* Tumblr changed audio player from `audio_player_container` to `native-audio-container`
* Tumblr removed postId from audio container dataset
* Removed unused `package.json` & `Info.plist`
* Fixed markdown in the changelog and readme
* Added paypal link to the readme
* Added dates and older releases to changelog
## v0.7.0 - 2015-06-21
* Made links to Tumblr, SoundCloud and Download for each track in the popup.
* The track that is playing is highlighted in the popup.
* Fixed an issue where posts wouldn't get their download links.
## v0.6.1 - 2014-11-18
* Fixed an issue where posts that reappeared would not get their download links reapplied
* Added this HISTORY file
## v0.6.0 - 2014-11-14
* Updated to work with https.
* Also makes a download link for each track in a soundcloud playlist.
* The audio player has had some love given to it, it should be friendlier to use now.
* Updates soundmanager2 version
* Added icons from fontawesome
## v0.4.8 - 2013-02-01
* Removed swf files and background.html
## v0.4.7 - 2012-08-01
* Tumblr changed their URL scheme for audio files so I fixed that, and began preparations for safari and opera versions ^^
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..0b0d3f9
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,7 @@
+VERSION=$1
+
+echo "Building TumTaster $VERSION"
+
+cd src
+zip ../TumTaster-$VERSION.zip ./* -r -9
+cd ..
diff --git a/src/data/defaults.js b/src/data/defaults.js
index d8bfea9..6dfdc56 100644
--- a/src/data/defaults.js
+++ b/src/data/defaults.js
@@ -1,19 +1,19 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
window.defaultSettings = {
- 'version': '1.0.0',
+ 'version': '1.0.2',
'shuffle': false,
'repeat': true,
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://www.tumblr.com/*',
'https://www.tumblr.com/*',
]
};
diff --git a/src/manifest.json b/src/manifest.json
index f71ec36..68e8eda 100644
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -1,42 +1,42 @@
{
"name": "TumTaster",
- "version": "1.0.0",
+ "version": "1.0.2",
"description": "Creates download links on Tumblr audio posts.",
"background": {
"scripts": [
"data/defaults.js",
"data/main.js",
"data/soundmanager2-nodebug-jsmin.js"
]
},
"browser_action": {
"default_icon": "data/images/Icon-16.png",
"default_popup": "data/popup/index.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [
"data/script.js"
],
"matches": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*"
],
"all_frames": true,
"run_at": "document_start"
} ],
"icons": {
"16": "data/images/Icon-16.png",
"32": "data/images/Icon-32.png",
"48": "data/images/Icon-48.png",
"64": "data/images/Icon-64.png",
"128": "data/images/Icon-128.png"
},
"manifest_version": 2,
"options_page": "data/options/index.html",
"permissions": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*",
"https://api.soundcloud.com/*"
]
}
|
bjornstar/TumTaster
|
ca49ec21b35ac38bbc6d23af4056cccfc1914acc
|
v1.0.1 - 2019-09-17
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e7aa19..3b7cdd7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,38 +1,40 @@
#@bjornstar/TumTaster Changelog
+## v1.0.1 - 2019-09-17
+* Do not create or check in `package-lock.json`
+
## v1.0.0 - 2019-09-16
* Only request track and playlist details from soundcloud once per session per id
* Rename HISTORY.md to CHANGELOG.md
* Add scope to title in README and CHANGELOG
* Start linting using `eslint`
-* Do not create or check in `package-lock.json`
## v0.7.1 - 2017-09-13
* Tumblr changed audio player from `audio_player_container` to `native-audio-container`
* Tumblr removed postId from audio container dataset
* Removed unused `package.json` & `Info.plist`
* Fixed markdown in the changelog and readme
* Added paypal link to the readme
* Added dates and older releases to changelog
## v0.7.0 - 2015-06-21
* Made links to Tumblr, SoundCloud and Download for each track in the popup.
* The track that is playing is highlighted in the popup.
* Fixed an issue where posts wouldn't get their download links.
## v0.6.1 - 2014-11-18
* Fixed an issue where posts that reappeared would not get their download links reapplied
* Added this HISTORY file
## v0.6.0 - 2014-11-14
* Updated to work with https.
* Also makes a download link for each track in a soundcloud playlist.
* The audio player has had some love given to it, it should be friendlier to use now.
* Updates soundmanager2 version
* Added icons from fontawesome
## v0.4.8 - 2013-02-01
* Removed swf files and background.html
## v0.4.7 - 2012-08-01
* Tumblr changed their URL scheme for audio files so I fixed that, and began preparations for safari and opera versions ^^
|
bjornstar/TumTaster
|
7d2bce2e2b28428aafb8217ebc279405f9f7629a
|
Do not create or check-in package-lock.json
|
diff --git a/.gitignore b/.gitignore
index 76fdcfd..6c778b6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,9 @@
*.nex
*.pem
*.safariextz
*.xpi
*.zip
.DS_Store
-src.safariextension
node_modules/
+package-lock.json
+src.safariextension
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 0000000..43c97e7
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1 @@
+package-lock=false
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed41f46..8e7aa19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,36 +1,38 @@
#@bjornstar/TumTaster Changelog
## v1.0.0 - 2019-09-16
* Only request track and playlist details from soundcloud once per session per id
* Rename HISTORY.md to CHANGELOG.md
* Add scope to title in README and CHANGELOG
+* Start linting using `eslint`
+* Do not create or check in `package-lock.json`
## v0.7.1 - 2017-09-13
* Tumblr changed audio player from `audio_player_container` to `native-audio-container`
* Tumblr removed postId from audio container dataset
* Removed unused `package.json` & `Info.plist`
* Fixed markdown in the changelog and readme
* Added paypal link to the readme
* Added dates and older releases to changelog
## v0.7.0 - 2015-06-21
* Made links to Tumblr, SoundCloud and Download for each track in the popup.
* The track that is playing is highlighted in the popup.
* Fixed an issue where posts wouldn't get their download links.
## v0.6.1 - 2014-11-18
* Fixed an issue where posts that reappeared would not get their download links reapplied
* Added this HISTORY file
## v0.6.0 - 2014-11-14
* Updated to work with https.
* Also makes a download link for each track in a soundcloud playlist.
* The audio player has had some love given to it, it should be friendlier to use now.
* Updates soundmanager2 version
* Added icons from fontawesome
## v0.4.8 - 2013-02-01
* Removed swf files and background.html
## v0.4.7 - 2012-08-01
* Tumblr changed their URL scheme for audio files so I fixed that, and began preparations for safari and opera versions ^^
|
bjornstar/TumTaster
|
a7df276de63ab44821229986536920551eabd2c6
|
v1.0.0 - 2019-09-16
|
diff --git a/.eslintignore b/.eslintignore
new file mode 100644
index 0000000..0e9b6cf
--- /dev/null
+++ b/.eslintignore
@@ -0,0 +1 @@
+src/data/soundmanager2-nodebug-jsmin.js
diff --git a/.eslintrc.json b/.eslintrc.json
new file mode 100644
index 0000000..3188d1f
--- /dev/null
+++ b/.eslintrc.json
@@ -0,0 +1,30 @@
+{
+ "env": {
+ "browser": true,
+ "es6": true
+ },
+ "extends": "eslint:recommended",
+ "parserOptions": {
+ "ecmaVersion": 2018,
+ "sourceType": "module"
+ },
+ "rules": {
+ "indent": [
+ "error",
+ "tab"
+ ],
+ "linebreak-style": [
+ "error",
+ "unix"
+ ],
+ "no-console": "off",
+ "quotes": [
+ "error",
+ "single"
+ ],
+ "semi": [
+ "error",
+ "always"
+ ]
+ }
+}
diff --git a/.gitignore b/.gitignore
index a3d1d50..76fdcfd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,8 @@
*.nex
*.pem
*.safariextz
*.xpi
*.zip
.DS_Store
src.safariextension
+node_modules/
diff --git a/HISTORY.md b/CHANGELOG.md
similarity index 84%
rename from HISTORY.md
rename to CHANGELOG.md
index cea7062..ed41f46 100644
--- a/HISTORY.md
+++ b/CHANGELOG.md
@@ -1,31 +1,36 @@
-# TumTaster Changelog
+#@bjornstar/TumTaster Changelog
+
+## v1.0.0 - 2019-09-16
+* Only request track and playlist details from soundcloud once per session per id
+* Rename HISTORY.md to CHANGELOG.md
+* Add scope to title in README and CHANGELOG
## v0.7.1 - 2017-09-13
* Tumblr changed audio player from `audio_player_container` to `native-audio-container`
* Tumblr removed postId from audio container dataset
* Removed unused `package.json` & `Info.plist`
* Fixed markdown in the changelog and readme
* Added paypal link to the readme
* Added dates and older releases to changelog
## v0.7.0 - 2015-06-21
* Made links to Tumblr, SoundCloud and Download for each track in the popup.
* The track that is playing is highlighted in the popup.
* Fixed an issue where posts wouldn't get their download links.
## v0.6.1 - 2014-11-18
* Fixed an issue where posts that reappeared would not get their download links reapplied
* Added this HISTORY file
## v0.6.0 - 2014-11-14
* Updated to work with https.
* Also makes a download link for each track in a soundcloud playlist.
* The audio player has had some love given to it, it should be friendlier to use now.
* Updates soundmanager2 version
* Added icons from fontawesome
## v0.4.8 - 2013-02-01
* Removed swf files and background.html
## v0.4.7 - 2012-08-01
* Tumblr changed their URL scheme for audio files so I fixed that, and began preparations for safari and opera versions ^^
diff --git a/README.md b/README.md
index a3f0672..75d53b4 100644
--- a/README.md
+++ b/README.md
@@ -1,14 +1,14 @@
-# TumTaster
+# @bjornstar/TumTaster
By [Bjorn Stromberg](http://bjornstar.com/about)
[TumTaster](http://tumtaster.bjornstar.com/) adds download links to audio posts and gives you a playlist of all the tracks that you've seen for easy access.
TumTaster uses [SoundManager2](http://www.schillmania.com/projects/soundmanager2) V2.97a.20140901 for managing MP3 playback and [FontAwesome](http://fortawesome.github.io/Font-Awesome/) v4.2.0 for icons.
TumTaster for Google Chrome can be installed here - https://chrome.google.com/webstore/detail/nanfbkacbckngfcklahdgfagjlghfbgm
This extension is open source and all source code can be found at [https://github.com/bjornstar/TumTaster](https://github.com/bjornstar/TumTaster).
If you'd like to show your appreciation for this extension, you can do so at [paypal.me/bjornstar](https://paypal.me/bjornstar)
*Disclaimer: TumTaster is neither affiliated with nor supported by [Tumblr](https://www.tumblr.com/) in any way.*
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..c6c914a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@bjornstar/tumtaster",
+ "version": "1.0.0",
+ "description": "Creates download links on Tumblr audio posts.",
+ "scripts": {
+ "test": "eslint src/data"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/bjornstar/TumTaster.git"
+ },
+ "keywords": [
+ "webextension",
+ "audio",
+ "mp3"
+ ],
+ "author": "Bjorn Stromberg <[email protected]>",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/bjornstar/TumTaster/issues"
+ },
+ "homepage": "https://github.com/bjornstar/TumTaster#readme",
+ "devDependencies": {
+ "eslint": "^5.1.0"
+ }
+}
diff --git a/src/data/defaults.js b/src/data/defaults.js
index 6cdc4a2..d8bfea9 100644
--- a/src/data/defaults.js
+++ b/src/data/defaults.js
@@ -1,19 +1,19 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
-var defaultSettings = {
- 'version': '0.7.1',
+window.defaultSettings = {
+ 'version': '1.0.0',
'shuffle': false,
'repeat': true,
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://www.tumblr.com/*',
'https://www.tumblr.com/*',
]
};
diff --git a/src/data/main.js b/src/data/main.js
index 5fec264..3a2dadb 100644
--- a/src/data/main.js
+++ b/src/data/main.js
@@ -1,199 +1,199 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
+'use strict';
-var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
+const API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
-var settings = defaultSettings;
+var settings = window.defaultSettings;
-var savedSettings = localStorage['settings'];
+const savedSettings = window.localStorage.getItem('settings');
try {
if (savedSettings) {
settings = JSON.parse(savedSettings);
}
} catch (e) {
console.error('Failed to parse settings: ', e);
}
-var ports = {};
+const ports = {};
var tracks = {};
+const urls = {};
-var scData = {};
+const soundcloudIds = [];
-var order = 0;
+let order = 0;
-function getDetails(url, cb) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url + '.json?client_id=' + API_KEY, true);
+function getDetails(url) {
+ urls[url] = urls[url] || new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', url + '.json?client_id=' + API_KEY, true);
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- var response;
- try {
- response = JSON.parse(xhr.responseText);
- } catch (e) {
- return cb(e);
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (xhr.status >= 400) {
+ reject(new Error(`Failed to getDetails: ${xhr.status} ${xhr.statusText}`));
+ }
+
+ try {
+ resolve(JSON.parse(xhr.responseText));
+ } catch (e) {
+ reject(e);
+ }
}
- cb(null, response);
- }
- }
+ };
+
+ xhr.send();
+ });
- xhr.send();
+ return urls[url];
}
function broadcast(msg) {
- for (var portId in ports) {
+ for (let portId in ports) {
ports[portId].postMessage(msg);
}
}
function addToLibrary(track, seenBefore) {
order += 1;
- var id = track.id;
+ const { id } = track;
track.order = order;
- broadcast({ track: track });
+ broadcast({ track });
if (!track.streamable || seenBefore) {
return;
}
function failOrFinish() {
- playnextsong(id);
+ window.playnextsong(id);
}
if (track.streamable) {
- soundManager.createSound({
- id: id,
+ window.soundManager.createSound({
+ id,
url: track.streamUrl,
onloadfailed: failOrFinish,
onfinish: failOrFinish
});
}
tracks[id] = track;
}
-function addSoundCloudTrack(post, details) {
- var track = {
- downloadUrl: details.uri + '/download?client_id=' + API_KEY,
- streamUrl: details.uri + '/stream?client_id=' + API_KEY,
- permalinkUrl: details.permalink_url,
-
- downloadable: details.downloadable,
- streamable: details.streamable,
-
- artist: details.user ? details.user.username : '',
- title: details.title,
- id: details.id,
-
- seen: post.seen,
- postId: post.postId,
- postUrl: post.dataset.postUrl
+function addSoundCloudTrack({ dataset: { postUrl }, postId, seen }, { downloadable, id, permalink_url, streamable, title, uri, user }) {
+ const track = {
+ artist: user ? user.username : '',
+ downloadable,
+ downloadUrl: `${uri}/download?client_id=${API_KEY}`,
+ id,
+ permalinkUrl: permalink_url,
+ postId,
+ postUrl,
+ seen,
+ streamUrl: `${uri}/stream?client_id=${API_KEY}`,
+ streamable,
+ title
};
- var seenBefore = scData.hasOwnProperty(track.id);
- scData[track.id] = details;
-
- addToLibrary(track, seenBefore);
+ addToLibrary(track, soundcloudIds.includes(id));
}
-var addPosts = {
+const addPosts = {
tumblr: function (post) {
post.downloadUrl = post.baseUrl + '?play_key=' + post.postKey;
post.streamUrl = post.downloadUrl;
post.downloadable = true;
post.streamable = true;
post.id = post.postId;
post.postUrl = post.dataset.postUrl;
addToLibrary(post);
},
soundcloud: function (post) {
- getDetails(post.baseUrl, function (e, details) {
- if (e) {
- return console.error(error);
- }
-
- details = details || {};
-
+ getDetails(post.baseUrl).then(details => {
switch (details.kind) {
case 'track':
return addSoundCloudTrack(post, details);
case 'playlist':
- for (var i = 0; i < details.tracks.length; i += 1) {
+ for (let i = 0; i < details.tracks.length; i += 1) {
addSoundCloudTrack(post, details.tracks[i]);
}
break;
default:
console.error('I don\'t know how to handle', details);
}
- });
+ }).catch(console.error);
}
-}
+};
function messageHandler(port, message) {
if (message === 'getSettings') {
return port.postMessage({ settings: settings});
}
if (message.hasOwnProperty('post')) {
- var post = message.post;
+ const post = message.post;
addPosts[post.type](post);
}
}
function connectHandler(port) {
ports[port.portId_] = port;
port.onMessage.addListener(function onMessageHandler(message) {
messageHandler(port, message);
});
port.postMessage({ settings: settings });
port.onDisconnect.addListener(function onDisconnectHandler() {
disconnectHandler(port);
});
}
function disconnectHandler(port) {
delete ports[port.portId_];
}
-chrome.runtime.onConnect.addListener(connectHandler);
+window.chrome.runtime.onConnect.addListener(connectHandler);
+
+window.playnextsong = (lastSoundID) => {
+ const { soundManager } = window;
-function playnextsong(lastSoundID) {
if (!soundManager.soundIDs.length) {
return;
}
- var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
+ const currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
- var nextIndex = (currentIndex + 1) % soundManager.soundIDs.length;
+ const nextIndex = (currentIndex + 1) % soundManager.soundIDs.length;
- var nextSound = soundManager.getSoundById(soundManager.soundIDs[nextIndex]);
+ const nextSound = soundManager.getSoundById(soundManager.soundIDs[nextIndex]);
nextSound.play();
-}
+};
+
+window.playprevsong = (lastSoundID) => {
+ const { soundManager } = window;
-function playprevsong(lastSoundID) {
if (!soundManager.soundIDs.length) {
return;
}
- var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
+ const currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
- var prevIndex = (currentIndex - 1) % soundManager.soundIDs.length;
+ const prevIndex = (currentIndex - 1) % soundManager.soundIDs.length;
- var prevSound = soundManager.getSoundById(soundManager.soundIDs[prevIndex]);
+ const prevSound = soundManager.getSoundById(soundManager.soundIDs[prevIndex]);
prevSound.play();
-}
+};
document.addEventListener('DOMContentLoaded', function () {
- soundManager.setup({'preferFlash': false});
+ window.soundManager.setup({'preferFlash': false});
});
diff --git a/src/data/options/index.js b/src/data/options/index.js
index 7f4ad2c..d3adb0d 100644
--- a/src/data/options/index.js
+++ b/src/data/options/index.js
@@ -1,173 +1,174 @@
+'use strict';
+
var inputLast = 0;
document.addEventListener('DOMContentLoaded', function () {
var save_btn = document.getElementById('save_btn');
var reset_btn = document.getElementById('reset_btn');
var listWhiteAdd = document.getElementById('listWhiteAdd');
var listBlackAdd = document.getElementById('listBlackAdd');
var listSitesAdd = document.getElementById('listSitesAdd');
save_btn.addEventListener('click', saveOptions);
- reset_btn.addEventListener('click', function() { if (confirm('Are you sure you want to restore defaults?')) {eraseOptions()} });
+ reset_btn.addEventListener('click', function() { if (confirm('Are you sure you want to restore defaults?')) {eraseOptions();} });
listWhiteAdd.addEventListener('click', function(e) {
addInput('listWhite');
e.preventDefault();
e.stopPropagation();
}, false);
listBlackAdd.addEventListener('click', function(e) {
addInput('listBlack');
e.preventDefault();
e.stopPropagation();
}, false);
listSitesAdd.addEventListener('click', function(e) {
addInput('listSites');
e.preventDefault();
e.stopPropagation();
}, false);
loadOptions();
});
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
- settings = defaultSettings;
+ settings = window.defaultSettings;
} else {
settings = JSON.parse(settings);
}
var cbShuffle = document.getElementById('optionShuffle');
cbShuffle.checked = settings['shuffle'];
var cbRepeat = document.getElementById('optionRepeat');
cbRepeat.checked = settings['repeat'];
for (var itemBlack in settings['listBlack']) {
addInput('listBlack', settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput('listWhite', settings['listWhite'][itemWhite]);
}
for (var itemSites in settings['listSites']) {
addInput('listSites', settings['listSites'][itemSites]);
}
addInput('listBlack'); //prepare a blank input box.
addInput('listWhite'); //prepare a blank input box.
addInput('listSites'); //prepare a blank input box.
var version_div = document.getElementById('version_div');
- version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
+ version_div.innerHTML = 'v'+window.defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
+
+ var browser_span = document.getElementById('browser_span');
if (typeof opera != 'undefined') {
- var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = 'for Opera™';
}
if (typeof chrome != 'undefined') {
- var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = 'for Chrome™';
}
if (typeof safari != 'undefined') {
- var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = 'for Safari™';
}
}
function removeInput(optionWhich) {
var optionInput = document.getElementById(optionWhich);
if (!optionInput) {
return;
}
optionInput.parentNode.removeChild(optionInput);
}
function addInput(whichList, itemValue) {
var listDiv, listAdd, optionInput, currentLength, removeThis, optionAdd, optionImage, optionLinebreak, optionDiv;
if (itemValue === undefined) { //if we don't pass an itemValue, make it blank.
itemValue = '';
}
currentLength = inputLast++; //have unique DOM id's
listDiv = document.getElementById(whichList);
listAdd = document.getElementById(whichList + 'Add');
optionInput = document.createElement('input');
optionInput.value = itemValue;
optionInput.name = 'option' + whichList;
optionInput.id = 'option' + whichList + currentLength;
optionAdd = document.createElement('a');
optionAdd.href = '#';
optionAdd.addEventListener('click', function (e) {
removeThis = e.target;
while (removeThis.tagName !== 'DIV') {
removeThis = removeThis.parentNode;
}
if (removeThis.id.indexOf('_div') >= 0) {
removeInput(removeThis.id);
}
e.preventDefault();
e.stopPropagation();
}, false);
optionAdd.appendChild(document.createTextNode('\u00A0'));
optionImage = document.createElement('img');
optionImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
optionAdd.appendChild(optionImage);
optionAdd.appendChild(document.createTextNode('\u00A0'));
optionLinebreak = document.createElement('br');
optionDiv = document.createElement('div');
optionDiv.id = 'option' + whichList + currentLength + '_div';
optionDiv.appendChild(optionAdd);
optionDiv.appendChild(optionInput);
optionDiv.appendChild(optionLinebreak);
listDiv.insertBefore(optionDiv, listAdd);
}
function saveOptions() {
var settings = {};
var cbShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = cbShuffle.checked;
var cbRepeat = document.getElementById('optionRepeat');
settings['repeat'] = cbRepeat.checked;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != '') {
if (garbages[i].name.indexOf('listWhite') !== -1) {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.indexOf('listBlack') !== -1) {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.indexOf('listSites') !== -1) {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
//location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
diff --git a/src/data/popup/index.js b/src/data/popup/index.js
index 83d7541..e1f6165 100644
--- a/src/data/popup/index.js
+++ b/src/data/popup/index.js
@@ -1,351 +1,353 @@
-var bg = chrome.extension.getBackgroundPage();
+'use strict';
+
+var bg = window.chrome.extension.getBackgroundPage();
var tracks = bg.tracks;
var sm = bg.soundManager;
var divLoading, divPosition, divPosition2, nowplaying, playlist, currentSound, currentTrack;
var buttons = {};
var shuffleMode = bg.settings.shuffle;
function getPlayingSound() {
if (currentSound && currentSound.playState === 1) {
return currentSound;
}
- for (sound in sm.sounds) {
+ for (let sound in sm.sounds) {
if (sm.sounds[sound].playState === 1) {
currentSound = sm.sounds[sound];
return currentSound;
}
}
}
var shuffleSort = {
true: function (array) {
var n = array.length;
while (n--) {
var i = Math.floor(n * Math.random());
var tmp = array[i];
array[i] = array[n];
array[n] = tmp;
}
return array;
},
false: function (array) {
return array.sort(function (a, b) { return tracks[a].order - tracks[b].order; });
}
};
function toggleShuffle() {
shuffleMode = !shuffleMode;
shuffleSort[shuffleMode](sm.soundIDs);
}
var skipDirections = {
forward: bg.playnextsong,
backward: bg.playprevsong
};
function skip(direction) {
var sound = getPlayingSound();
var soundId;
if (sound) {
sound.stop();
soundId = sound.sID;
}
skipDirections[direction](soundId);
}
function togglePause() {
var sound = getPlayingSound();
if (sound) {
return !!sound.togglePause().paused;
}
skip('forward');
}
function toggleDisplay(elm, isVisible) {
if (isVisible) {
- elm.className = elm.className.replace(' hidden', '')
+ elm.className = elm.className.replace(' hidden', '');
} else if (!/hidden/.test(elm.className)) {
elm.className += ' hidden';
}
}
function getTrackDisplayName(track) {
- display = [];
+ const display = [];
if (track.artist) {
display.push(track.artist);
}
if (track.title) {
display.push(track.title);
}
if (!display.length) {
display.push([track.type, track.id]);
}
return display.join(' - ');
}
-function remove(id) {
+window.remove = (id) => {
sm.destroySound(id);
var elmTrack = document.getElementById(id);
playlist.removeChild(elmTrack);
-}
+};
-function play(soundId) {
+window.play = (soundId) => {
sm.stopAll();
var sound = sm.getSoundById(soundId);
if (sound) {
sound.play();
}
-}
+};
-var updateScheduled, updateTracks, trackSlots = [];
+var updateScheduled, trackSlots = [];
function setIsPlaying(track, isPlaying) {
for (var i = 0; i < trackSlots.length; i += 1) {
if (trackSlots[i].track === track) {
return trackSlots[i].isPlaying(isPlaying);
}
}
}
-var nowPlayingScheduled, scheduleNowPlaying;
+var nowPlayingScheduled;
function updateNowPlaying() {
nowPlayingScheduled = null;
var sound = getPlayingSound();
if (!sound) {
return scheduleNowPlaying();
}
var bytesLoaded = sound.bytesLoaded;
var bytesTotal = sound.bytesTotal;
var position = sound.position;
var durationEstimate = sound.durationEstimate;
if (bytesTotal) {
divLoading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
}
divPosition.style.left = (100 * position / durationEstimate) + '%';
divPosition2.style.width = (100 * position / durationEstimate) + '%';
if (currentTrack !== tracks[sound.sID]) {
setIsPlaying(currentTrack, false);
currentTrack = tracks[sound.sID];
nowplaying.textContent = getTrackDisplayName(currentTrack);
setIsPlaying(currentTrack, true);
}
scheduleNowPlaying();
}
function scheduleNowPlaying() {
nowPlayingScheduled = nowPlayingScheduled || requestAnimationFrame(updateNowPlaying);
}
var playIcons = {
true: 'fa-pause',
false: 'fa-play'
};
var modeIcons = {
true: 'fa-random',
false: 'fa-retweet'
};
function scheduleUpdate() {
updateScheduled = updateScheduled || requestAnimationFrame(updateTracks);
}
function TrackSlot(elmParent) {
var that = this;
var liTrack = document.createElement('LI');
var spanTrack = document.createElement('SPAN');
spanTrack.className = 'clickable trackname';
var spanRemove = document.createElement('SPAN');
spanRemove.className = 'remove clickable fa fa-remove fa-2x';
var aTumblr = document.createElement('A');
aTumblr.className = 'clickable fa fa-tumblr fa-2x';
aTumblr.target = '_new';
var aSoundCloud = document.createElement('A');
aSoundCloud.className = 'clickable fa fa-soundcloud fa-2x';
aSoundCloud.target = '_new';
var aDownload = document.createElement('A');
aDownload.className = 'clickable fa fa-download fa-2x';
aDownload.target = '_new';
this.destroy = function () {
elmParent.removeChild(liTrack);
};
this.isPlaying = function (isPlaying) {
if (!isPlaying) {
liTrack.className = liTrack.className.replace(' isplaying', '');
} else if (!/isplaying/.test(liTrack.className)) {
liTrack.className += ' isplaying';
}
};
this.play = function () {
sm.stopAll();
if (that.sound) {
that.sound.play();
}
};
this.remove = function () {
if (that.sound.playState === 1) {
sm.stopAll();
- skip('forward')
+ skip('forward');
}
sm.destroySound(that.sound.sID);
scheduleUpdate();
};
this.update = function (id) {
that.sound = sm.getSoundById(id);
that.track = tracks[id];
liTrack.id = that.id = id;
spanTrack.textContent = getTrackDisplayName(that.track);
aTumblr.href = that.track.postUrl;
aSoundCloud.href = that.track.permalinkUrl;
aDownload.href = that.track.downloadUrl;
toggleDisplay(aSoundCloud, that.track.permalinkUrl);
toggleDisplay(aDownload, that.track.downloadable);
- }
+ };
spanTrack.addEventListener('click', function (e) {
that.play();
e.preventDefault();
e.stopPropagation();
}, false);
spanRemove.addEventListener('click', function (e) {
- that.remove()
+ that.remove();
e.preventDefault();
e.stopPropagation();
}, false);
liTrack.appendChild(aTumblr);
liTrack.appendChild(aSoundCloud);
liTrack.appendChild(aDownload);
liTrack.appendChild(spanTrack);
liTrack.appendChild(spanRemove);
elmParent.appendChild(liTrack);
}
function updateTracks() {
updateScheduled = null;
while (trackSlots.length < sm.soundIDs.length) {
trackSlots.push(new TrackSlot(playlist));
}
while (trackSlots.length > sm.soundIDs.length) {
trackSlots.pop().destroy();
}
for (var i = 0; i < sm.soundIDs.length; i += 1) {
var id = sm.soundIDs[i];
trackSlots[i].update(id);
}
}
function onOpen() {
divLoading = document.getElementById('loading');
divPosition = document.getElementById('position');
divPosition2 = document.getElementById('position2');
nowplaying = document.getElementById('nowplaying');
playlist = document.getElementById('playlist');
buttons.prev = document.getElementById('prev');
buttons.play = document.getElementById('play');
buttons.next = document.getElementById('next');
buttons.mode = document.getElementById('mode');
buttons.prev.addEventListener('click', function (e) {
skip('backward');
e.preventDefault();
e.stopPropagation();
}, false);
function updatePlayButton(playing) {
buttons.play.className = buttons.play.className.replace(playIcons[playing], playIcons[!playing]);
}
buttons.play.addEventListener('click', function (e) {
var playing = togglePause();
updatePlayButton(playing);
e.preventDefault();
e.stopPropagation();
}, false);
buttons.next.addEventListener('click', function (e) {
skip('forward');
e.preventDefault();
e.stopPropagation();
}, false);
function updateModeButton() {
buttons.mode.className = buttons.mode.className.replace(modeIcons[!shuffleMode], modeIcons[shuffleMode]);
}
buttons.mode.addEventListener('click', function (e) {
toggleShuffle();
updateModeButton();
scheduleUpdate();
e.preventDefault();
e.stopPropagation();
}, false);
var sound = getPlayingSound();
if (sound && sound.playState === 1) {
updatePlayButton(false);
}
updateModeButton();
scheduleUpdate();
scheduleNowPlaying();
}
document.addEventListener('DOMContentLoaded', onOpen);
diff --git a/src/data/script.js b/src/data/script.js
index 46cb035..aa453ee 100644
--- a/src/data/script.js
+++ b/src/data/script.js
@@ -1,259 +1,263 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
+'use strict';
+
var settings, started;
function addLink(track) {
var elmPost = document.getElementById('post_' + track.postId);
if (!elmPost) {
console.error('couldn\'t find post:', track.postId);
return;
}
var elmFooter = elmPost.querySelector('.post_footer');
if (!elmFooter) {
console.error('couldn\'t find footer:', track.postId);
return;
}
var divDownload = elmFooter.querySelector('.tumtaster');
if (divDownload) {
return;
}
divDownload = document.createElement('DIV');
divDownload.className = 'tumtaster';
var aDownload = document.createElement('A');
aDownload.href = track.downloadUrl;
aDownload.textContent = 'Download';
if (!track.downloadable) {
aDownload.style.setProperty('text-decoration', 'line-through');
}
divDownload.appendChild(aDownload);
elmFooter.insertBefore(divDownload, elmFooter.children[1]);
}
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
addLink(message.track);
}
}
-var port = chrome.runtime.connect();
+var port = window.chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, '(.*?)');
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var posts = {};
-function makeTumblrLink(dataset, postId) {
+function makeTumblrLink(dataset, audioDataset) {
+ const { postId } = dataset;
+ const { artist, postKey, streamUrl, track } = audioDataset;
+
var post = {
- artist: dataset.artist,
- baseUrl: dataset.streamUrl,
- dataset: dataset,
- postId: postId,
- postKey: dataset.postKey,
+ artist,
+ baseUrl: streamUrl,
+ dataset,
+ postId,
+ postKey,
seen: Date.now(),
- title: dataset.track,
+ title: track,
type: 'tumblr'
};
if (!posts[postId]) {
posts[postId] = post;
}
- port.postMessage({ post: post });
+ port.postMessage({ post });
}
function makeSoundCloudLink(dataset, url) {
- var postId = dataset.postId;
+ const postId = dataset.postId;
- var qs = url.split('?')[1];
- var chunks = qs.split('&');
+ const qs = url.split('?')[1];
+ const chunks = qs.split('&');
- var url;
+ var baseUrl;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
- url = decodeURIComponent(chunks[i].substring(4));
+ baseUrl = decodeURIComponent(chunks[i].substring(4));
break;
}
}
var post = {
- baseUrl: url,
- dataset: dataset,
- postId: postId,
+ baseUrl,
+ dataset,
+ postId,
seen: Date.now(),
type: 'soundcloud'
};
if (!posts[postId]) {
posts[postId] = post;
}
- port.postMessage({ post: post });
+ port.postMessage({ post });
}
function extractPermalink(post) {
- permalink = post.querySelector('.post_permalink') || {};
+ const permalink = post.querySelector('.post_permalink') || {};
return permalink.href;
}
function extractAudioData(post) {
var postId = post.dataset.postId;
if (!postId) {
return;
}
post.dataset.postUrl = extractPermalink(post);
var soundcloud = post.querySelector('.soundcloud_audio_player');
if (soundcloud) {
return makeSoundCloudLink(post.dataset, soundcloud.src);
}
var tumblr = post.querySelector('.audio_player_container, .native-audio-container');
if (tumblr) {
- tumblr.dataset.postUrl = post.dataset.postUrl;
- return makeTumblrLink(tumblr.dataset, postId);
+ return makeTumblrLink(post.dataset, tumblr.dataset);
}
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target.parentNode);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var cssRules = [];
cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
cssRules.push(
'@keyframes nodeInserted {' +
' from { clip: rect(1px, auto, auto, auto); }' +
' to { clip: rect(0px, auto, auto, auto); }' +
'}'
);
cssRules.push(
'.post_container .post {' +
' animation-duration: 1ms;' +
' animation-name: nodeInserted;' +
'}'
);
addGlobalStyle('tastyWires', cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
if (!checkurl(location.href, settings['listSites'])) {
port.disconnect();
return;
}
started = true;
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
document.onreadystatechange = startTasting;
document.addEventListener('DOMContentLoaded', startTasting);
startTasting();
diff --git a/src/manifest.json b/src/manifest.json
index 5d9f3b6..f71ec36 100644
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -1,42 +1,42 @@
{
"name": "TumTaster",
- "version": "0.7.1",
+ "version": "1.0.0",
"description": "Creates download links on Tumblr audio posts.",
"background": {
"scripts": [
"data/defaults.js",
"data/main.js",
"data/soundmanager2-nodebug-jsmin.js"
]
},
"browser_action": {
"default_icon": "data/images/Icon-16.png",
"default_popup": "data/popup/index.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [
"data/script.js"
],
"matches": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*"
],
"all_frames": true,
"run_at": "document_start"
} ],
"icons": {
"16": "data/images/Icon-16.png",
"32": "data/images/Icon-32.png",
"48": "data/images/Icon-48.png",
"64": "data/images/Icon-64.png",
"128": "data/images/Icon-128.png"
},
"manifest_version": 2,
"options_page": "data/options/index.html",
"permissions": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*",
"https://api.soundcloud.com/*"
]
-}
\ No newline at end of file
+}
|
bjornstar/TumTaster
|
3dd22746c8881fa7895611f7f33b3d06d9084a42
|
v0.7.1 - 2017-09-13
|
diff --git a/HISTORY.md b/HISTORY.md
index af49111..cea7062 100644
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -1,17 +1,31 @@
-#TumTaster Changelog
+# TumTaster Changelog
-##v0.7.0
- * Made links to Tumblr, SoundCloud and Download for each track in the popup.
- * The track that is playing is highlighted in the popup.
- * Fixed an issue where posts wouldn't get their download links.
+## v0.7.1 - 2017-09-13
+* Tumblr changed audio player from `audio_player_container` to `native-audio-container`
+* Tumblr removed postId from audio container dataset
+* Removed unused `package.json` & `Info.plist`
+* Fixed markdown in the changelog and readme
+* Added paypal link to the readme
+* Added dates and older releases to changelog
-##v0.6.1
- * Fixed an issue where posts that reappeared would not get their download links reapplied
- * Added this HISTORY file
+## v0.7.0 - 2015-06-21
+* Made links to Tumblr, SoundCloud and Download for each track in the popup.
+* The track that is playing is highlighted in the popup.
+* Fixed an issue where posts wouldn't get their download links.
-##v0.6.0
- * Updated to work with https.
- * Also makes a download link for each track in a soundcloud playlist.
- * The audio player has had some love given to it, it should be friendlier to use now.
- * Updates soundmanager2 version
- * Added icons from fontawesome
+## v0.6.1 - 2014-11-18
+* Fixed an issue where posts that reappeared would not get their download links reapplied
+* Added this HISTORY file
+
+## v0.6.0 - 2014-11-14
+* Updated to work with https.
+* Also makes a download link for each track in a soundcloud playlist.
+* The audio player has had some love given to it, it should be friendlier to use now.
+* Updates soundmanager2 version
+* Added icons from fontawesome
+
+## v0.4.8 - 2013-02-01
+* Removed swf files and background.html
+
+## v0.4.7 - 2012-08-01
+* Tumblr changed their URL scheme for audio files so I fixed that, and began preparations for safari and opera versions ^^
diff --git a/README.md b/README.md
index dda4663..a3f0672 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,14 @@
-#TumTaster
+# TumTaster
By [Bjorn Stromberg](http://bjornstar.com/about)
[TumTaster](http://tumtaster.bjornstar.com/) adds download links to audio posts and gives you a playlist of all the tracks that you've seen for easy access.
TumTaster uses [SoundManager2](http://www.schillmania.com/projects/soundmanager2) V2.97a.20140901 for managing MP3 playback and [FontAwesome](http://fortawesome.github.io/Font-Awesome/) v4.2.0 for icons.
TumTaster for Google Chrome can be installed here - https://chrome.google.com/webstore/detail/nanfbkacbckngfcklahdgfagjlghfbgm
This extension is open source and all source code can be found at [https://github.com/bjornstar/TumTaster](https://github.com/bjornstar/TumTaster).
+If you'd like to show your appreciation for this extension, you can do so at [paypal.me/bjornstar](https://paypal.me/bjornstar)
+
*Disclaimer: TumTaster is neither affiliated with nor supported by [Tumblr](https://www.tumblr.com/) in any way.*
diff --git a/src/Info.plist b/src/Info.plist
deleted file mode 100644
index 0940cb2..0000000
--- a/src/Info.plist
+++ /dev/null
@@ -1,87 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>Author</key>
- <string>Bjorn Stromberg</string>
- <key>Builder Version</key>
- <string>10600.1.25</string>
- <key>CFBundleDisplayName</key>
- <string>TumTaster</string>
- <key>CFBundleIdentifier</key>
- <string>com.bjornstar.safari.tumtaster</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundleShortVersionString</key>
- <string>0.7.0</string>
- <key>CFBundleVersion</key>
- <string>1</string>
- <key>Chrome</key>
- <dict>
- <key>Global Page</key>
- <string>index.html</string>
- <key>Toolbar Items</key>
- <array>
- <dict>
- <key>Command</key>
- <string>popup</string>
- <key>Identifier</key>
- <string>TumTaster Toolbar Button</string>
- <key>Image</key>
- <string>data/images/Icon-64.png</string>
- <key>Label</key>
- <string>TumTaster</string>
- <key>Tool Tip</key>
- <string>Click me to play some music</string>
- </dict>
- </array>
- </dict>
- <key>Content</key>
- <dict>
- <key>Blacklist</key>
- <array>
- <string>http://www.tumblr.com/uploads/*</string>
- <string>https://www.tumblr.com/uploads/*</string>
- </array>
- <key>Scripts</key>
- <dict>
- <key>Start</key>
- <array>
- <string>data/script.js</string>
- </array>
- </dict>
- <key>Whitelist</key>
- <array>
- <string>http://www.tumblr.com/*</string>
- <string>https://www.tumblr.com/*</string>
- <string>safari-extension://com.bjornstar.safari.tumtaster-4GANG9K96D/*</string>
- </array>
- </dict>
- <key>Description</key>
- <string>TumTaster creates download links on Tumblr audio posts</string>
- <key>DeveloperIdentifier</key>
- <string>4GANG9K96D</string>
- <key>ExtensionInfoDictionaryVersion</key>
- <string>1.0</string>
- <key>Permissions</key>
- <dict>
- <key>Website Access</key>
- <dict>
- <key>Allowed Domains</key>
- <array>
- <string>com.bjornstar.safari.tumtaster-4GANG9K96D</string>
- <string>www.tumblr.com</string>
- <string>api.soundcloud.com</string>
- </array>
- <key>Include Secure Pages</key>
- <true/>
- <key>Level</key>
- <string>Some</string>
- </dict>
- </dict>
- <key>Update Manifest URL</key>
- <string>http://tumtaster.bjornstar.com/update.plist</string>
- <key>Website</key>
- <string>http://tumtaster.bjornstar.com</string>
-</dict>
-</plist>
diff --git a/src/data/defaults.js b/src/data/defaults.js
index 3b26fb1..6cdc4a2 100644
--- a/src/data/defaults.js
+++ b/src/data/defaults.js
@@ -1,19 +1,19 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var defaultSettings = {
- 'version': '0.7.0',
+ 'version': '0.7.1',
'shuffle': false,
'repeat': true,
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://www.tumblr.com/*',
'https://www.tumblr.com/*',
]
};
diff --git a/src/data/script.js b/src/data/script.js
index 3eba3a6..46cb035 100644
--- a/src/data/script.js
+++ b/src/data/script.js
@@ -1,261 +1,259 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var settings, started;
function addLink(track) {
var elmPost = document.getElementById('post_' + track.postId);
if (!elmPost) {
console.error('couldn\'t find post:', track.postId);
return;
}
var elmFooter = elmPost.querySelector('.post_footer');
if (!elmFooter) {
console.error('couldn\'t find footer:', track.postId);
return;
}
var divDownload = elmFooter.querySelector('.tumtaster');
if (divDownload) {
return;
}
divDownload = document.createElement('DIV');
divDownload.className = 'tumtaster';
var aDownload = document.createElement('A');
aDownload.href = track.downloadUrl;
aDownload.textContent = 'Download';
if (!track.downloadable) {
aDownload.style.setProperty('text-decoration', 'line-through');
}
divDownload.appendChild(aDownload);
elmFooter.insertBefore(divDownload, elmFooter.children[1]);
}
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
addLink(message.track);
}
}
var port = chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, '(.*?)');
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var posts = {};
-function makeTumblrLink(dataset) {
- var postId = dataset.postId;
-
+function makeTumblrLink(dataset, postId) {
var post = {
artist: dataset.artist,
baseUrl: dataset.streamUrl,
dataset: dataset,
postId: postId,
postKey: dataset.postKey,
seen: Date.now(),
title: dataset.track,
type: 'tumblr'
};
if (!posts[postId]) {
posts[postId] = post;
}
port.postMessage({ post: post });
}
function makeSoundCloudLink(dataset, url) {
var postId = dataset.postId;
var qs = url.split('?')[1];
var chunks = qs.split('&');
var url;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
url = decodeURIComponent(chunks[i].substring(4));
break;
}
}
var post = {
baseUrl: url,
dataset: dataset,
postId: postId,
seen: Date.now(),
type: 'soundcloud'
};
if (!posts[postId]) {
posts[postId] = post;
}
port.postMessage({ post: post });
}
function extractPermalink(post) {
permalink = post.querySelector('.post_permalink') || {};
return permalink.href;
}
function extractAudioData(post) {
var postId = post.dataset.postId;
if (!postId) {
return;
}
post.dataset.postUrl = extractPermalink(post);
var soundcloud = post.querySelector('.soundcloud_audio_player');
if (soundcloud) {
return makeSoundCloudLink(post.dataset, soundcloud.src);
}
- var tumblr = post.querySelector('.audio_player_container');
+ var tumblr = post.querySelector('.audio_player_container, .native-audio-container');
if (tumblr) {
tumblr.dataset.postUrl = post.dataset.postUrl;
- return makeTumblrLink(tumblr.dataset);
+ return makeTumblrLink(tumblr.dataset, postId);
}
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target.parentNode);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var cssRules = [];
cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
cssRules.push(
'@keyframes nodeInserted {' +
' from { clip: rect(1px, auto, auto, auto); }' +
' to { clip: rect(0px, auto, auto, auto); }' +
'}'
);
cssRules.push(
'.post_container .post {' +
' animation-duration: 1ms;' +
' animation-name: nodeInserted;' +
'}'
);
addGlobalStyle('tastyWires', cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
if (!checkurl(location.href, settings['listSites'])) {
port.disconnect();
return;
}
started = true;
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
document.onreadystatechange = startTasting;
document.addEventListener('DOMContentLoaded', startTasting);
startTasting();
diff --git a/src/manifest.json b/src/manifest.json
index 6392483..5d9f3b6 100644
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -1,42 +1,42 @@
{
"name": "TumTaster",
- "version": "0.7.0",
+ "version": "0.7.1",
"description": "Creates download links on Tumblr audio posts.",
"background": {
"scripts": [
"data/defaults.js",
"data/main.js",
"data/soundmanager2-nodebug-jsmin.js"
]
},
"browser_action": {
"default_icon": "data/images/Icon-16.png",
"default_popup": "data/popup/index.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [
"data/script.js"
],
"matches": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*"
],
"all_frames": true,
"run_at": "document_start"
} ],
"icons": {
"16": "data/images/Icon-16.png",
"32": "data/images/Icon-32.png",
"48": "data/images/Icon-48.png",
"64": "data/images/Icon-64.png",
"128": "data/images/Icon-128.png"
},
"manifest_version": 2,
"options_page": "data/options/index.html",
"permissions": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*",
"https://api.soundcloud.com/*"
]
}
\ No newline at end of file
diff --git a/src/package.json b/src/package.json
deleted file mode 100644
index 2fbddd5..0000000
--- a/src/package.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "name": "tumtaster",
- "license": "MPL 2.0",
- "author": "Bjorn Stromberg",
- "version": "0.7.0",
- "fullName": "TumTaster",
- "id": "jid1-W5guVoyeUR0uBg",
- "description": "Creates download links on Tumblr audio posts",
- "homepage": "http://tumtaster.bjornstar.com",
- "icon": "data/images/Icon-48.png",
- "icon64": "data/images/Icon-64.png",
- "lib": "data"
-}
\ No newline at end of file
|
bjornstar/TumTaster
|
047dad3e9e1edd47e64726f3fb1a9dac632fdd99
|
v0.7.0 - Add links to Tumblr, SoundCloud, and Download for each track in the popup.
|
diff --git a/HISTORY.md b/HISTORY.md
index 486503f..af49111 100644
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -1,12 +1,17 @@
#TumTaster Changelog
+##v0.7.0
+ * Made links to Tumblr, SoundCloud and Download for each track in the popup.
+ * The track that is playing is highlighted in the popup.
+ * Fixed an issue where posts wouldn't get their download links.
+
##v0.6.1
* Fixed an issue where posts that reappeared would not get their download links reapplied
* Added this HISTORY file
##v0.6.0
* Updated to work with https.
* Also makes a download link for each track in a soundcloud playlist.
* The audio player has had some love given to it, it should be friendlier to use now.
* Updates soundmanager2 version
* Added icons from fontawesome
diff --git a/src/Info.plist b/src/Info.plist
index 8865ab7..0940cb2 100644
--- a/src/Info.plist
+++ b/src/Info.plist
@@ -1,87 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Author</key>
<string>Bjorn Stromberg</string>
<key>Builder Version</key>
<string>10600.1.25</string>
<key>CFBundleDisplayName</key>
<string>TumTaster</string>
<key>CFBundleIdentifier</key>
<string>com.bjornstar.safari.tumtaster</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleShortVersionString</key>
- <string>0.6.1</string>
+ <string>0.7.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>Chrome</key>
<dict>
<key>Global Page</key>
<string>index.html</string>
<key>Toolbar Items</key>
<array>
<dict>
<key>Command</key>
<string>popup</string>
<key>Identifier</key>
<string>TumTaster Toolbar Button</string>
<key>Image</key>
<string>data/images/Icon-64.png</string>
<key>Label</key>
<string>TumTaster</string>
<key>Tool Tip</key>
<string>Click me to play some music</string>
</dict>
</array>
</dict>
<key>Content</key>
<dict>
<key>Blacklist</key>
<array>
<string>http://www.tumblr.com/uploads/*</string>
<string>https://www.tumblr.com/uploads/*</string>
</array>
<key>Scripts</key>
<dict>
<key>Start</key>
<array>
<string>data/script.js</string>
</array>
</dict>
<key>Whitelist</key>
<array>
<string>http://www.tumblr.com/*</string>
<string>https://www.tumblr.com/*</string>
<string>safari-extension://com.bjornstar.safari.tumtaster-4GANG9K96D/*</string>
</array>
</dict>
<key>Description</key>
<string>TumTaster creates download links on Tumblr audio posts</string>
<key>DeveloperIdentifier</key>
<string>4GANG9K96D</string>
<key>ExtensionInfoDictionaryVersion</key>
<string>1.0</string>
<key>Permissions</key>
<dict>
<key>Website Access</key>
<dict>
<key>Allowed Domains</key>
<array>
<string>com.bjornstar.safari.tumtaster-4GANG9K96D</string>
<string>www.tumblr.com</string>
<string>api.soundcloud.com</string>
</array>
<key>Include Secure Pages</key>
<true/>
<key>Level</key>
<string>Some</string>
</dict>
</dict>
<key>Update Manifest URL</key>
<string>http://tumtaster.bjornstar.com/update.plist</string>
<key>Website</key>
<string>http://tumtaster.bjornstar.com</string>
</dict>
</plist>
diff --git a/src/data/css/popup.css b/src/data/css/popup.css
index 834bb27..eede9c2 100644
--- a/src/data/css/popup.css
+++ b/src/data/css/popup.css
@@ -1,178 +1,209 @@
html {
color: black;
font-family: arial, helvetica, sans-serif;
margin: 0;
padding: 0;
background-color: #36465d;
- min-width: 400px;
+ min-width: 600px;
+ font-size: 18px;
}
h1 {
color: black;
}
ol {
background-attachment: scroll;
background-clip: border-box;
background-color: #36465d;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
color: #444;
display: block;
list-style-type: none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li {
background-color: white;
- border-bottom-color: #BBB;
- border-bottom-left-radius: 10px;
- border-bottom-right-radius: 10px;
- border-bottom-style: solid;
- border-bottom-width: 2px;
- border-top-left-radius: 10px;
- border-top-right-radius: 10px;
+ border-radius: 3px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
+li:hover {
+ background: rgba(255, 255, 255, 0.9);
+}
+
+a {
+ text-decoration: none;
+ color: #444;
+ margin-right: 8px;
+}
+
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span {
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
#heading {
width: 100%;
height: 64px;
}
#heading h1 {
color: white;
float: left;
line-height: 32px;
vertical-align: absmiddle;
margin-left: 10px;
}
div#statistics {
position: absolute;
bottom: 0%;
}
#controls{
text-align: center;
width: 100%;
color: white;
}
#controls i {
- margin: 20px;
+ margin: 0px 20px;
}
#statusbar{
position: relative;
height: 12px;
background-color: #CDD568;
border: 2px solid #EAF839;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
overflow: hidden;
margin-top: 4px;
}
.remove {
position: absolute;
right: 8px;
top: 8px;
+ color: #CCC;
+}
+
+.remove:hover {
+ color: #444;
}
.position, .position2, .loading {
position: absolute;
left: 0px;
bottom: 0px;
height: 12px;
}
.position {
background-color: #3B440F;
border-right: 2px solid #3B440F;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
width: 20px;
}
.position2 {
background-color: #EAF839;
}
.loading {
background-color: #BBC552;
}
.clickable {
cursor: hand;
+}
+
+.trackname {
+ font-size:18px;
+}
+
+.hidden {
+ display: none !important;
+}
+
+.isplaying {
+ background-color: #CDD568;
+ border: solid 1px #BBC552;
+}
+
+.isplaying:hover {
+ background-color: rgba(187, 197, 82, 0.9);
+}
+
+.isplaying .remove {
+ color: #444;
}
\ No newline at end of file
diff --git a/src/data/defaults.js b/src/data/defaults.js
index 807fdd2..3b26fb1 100644
--- a/src/data/defaults.js
+++ b/src/data/defaults.js
@@ -1,19 +1,19 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var defaultSettings = {
- 'version': '0.6.1',
+ 'version': '0.7.0',
'shuffle': false,
'repeat': true,
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://www.tumblr.com/*',
'https://www.tumblr.com/*',
]
};
diff --git a/src/data/main.js b/src/data/main.js
index 019d9fd..5fec264 100644
--- a/src/data/main.js
+++ b/src/data/main.js
@@ -1,196 +1,199 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
var settings = defaultSettings;
var savedSettings = localStorage['settings'];
try {
if (savedSettings) {
settings = JSON.parse(savedSettings);
}
} catch (e) {
console.error('Failed to parse settings: ', e);
}
var ports = {};
var tracks = {};
var scData = {};
var order = 0;
function getDetails(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '.json?client_id=' + API_KEY, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
return cb(e);
}
cb(null, response);
}
}
xhr.send();
}
function broadcast(msg) {
for (var portId in ports) {
ports[portId].postMessage(msg);
}
}
function addToLibrary(track, seenBefore) {
order += 1;
var id = track.id;
track.order = order;
broadcast({ track: track });
if (!track.streamable || seenBefore) {
return;
}
function failOrFinish() {
playnextsong(id);
}
if (track.streamable) {
soundManager.createSound({
id: id,
url: track.streamUrl,
onloadfailed: failOrFinish,
onfinish: failOrFinish
});
}
tracks[id] = track;
}
function addSoundCloudTrack(post, details) {
var track = {
downloadUrl: details.uri + '/download?client_id=' + API_KEY,
streamUrl: details.uri + '/stream?client_id=' + API_KEY,
+ permalinkUrl: details.permalink_url,
downloadable: details.downloadable,
streamable: details.streamable,
artist: details.user ? details.user.username : '',
title: details.title,
id: details.id,
seen: post.seen,
- postId: post.postId
+ postId: post.postId,
+ postUrl: post.dataset.postUrl
};
var seenBefore = scData.hasOwnProperty(track.id);
scData[track.id] = details;
addToLibrary(track, seenBefore);
}
var addPosts = {
tumblr: function (post) {
post.downloadUrl = post.baseUrl + '?play_key=' + post.postKey;
post.streamUrl = post.downloadUrl;
post.downloadable = true;
post.streamable = true;
post.id = post.postId;
+ post.postUrl = post.dataset.postUrl;
addToLibrary(post);
},
soundcloud: function (post) {
getDetails(post.baseUrl, function (e, details) {
if (e) {
return console.error(error);
}
details = details || {};
switch (details.kind) {
case 'track':
return addSoundCloudTrack(post, details);
case 'playlist':
for (var i = 0; i < details.tracks.length; i += 1) {
addSoundCloudTrack(post, details.tracks[i]);
}
break;
default:
console.error('I don\'t know how to handle', details);
}
});
}
}
function messageHandler(port, message) {
if (message === 'getSettings') {
return port.postMessage({ settings: settings});
}
if (message.hasOwnProperty('post')) {
var post = message.post;
addPosts[post.type](post);
}
}
function connectHandler(port) {
ports[port.portId_] = port;
port.onMessage.addListener(function onMessageHandler(message) {
messageHandler(port, message);
});
port.postMessage({ settings: settings });
port.onDisconnect.addListener(function onDisconnectHandler() {
disconnectHandler(port);
});
}
function disconnectHandler(port) {
delete ports[port.portId_];
}
chrome.runtime.onConnect.addListener(connectHandler);
function playnextsong(lastSoundID) {
if (!soundManager.soundIDs.length) {
return;
}
var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
var nextIndex = (currentIndex + 1) % soundManager.soundIDs.length;
var nextSound = soundManager.getSoundById(soundManager.soundIDs[nextIndex]);
nextSound.play();
}
function playprevsong(lastSoundID) {
if (!soundManager.soundIDs.length) {
return;
}
var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
var prevIndex = (currentIndex - 1) % soundManager.soundIDs.length;
var prevSound = soundManager.getSoundById(soundManager.soundIDs[prevIndex]);
prevSound.play();
}
document.addEventListener('DOMContentLoaded', function () {
soundManager.setup({'preferFlash': false});
});
diff --git a/src/data/popup/index.html b/src/data/popup/index.html
index b2b8035..b35a251 100644
--- a/src/data/popup/index.html
+++ b/src/data/popup/index.html
@@ -1,27 +1,27 @@
<html>
<head>
<link href="../css/popup.css" rel="stylesheet" type="text/css">
<link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script src="index.js" type="text/javascript"></script>
</head>
<body>
<div id="heading"><img src="../images/Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
<div id="statistics"><span> </span></div>
<div id="nowplayingdiv"><span id="nowplaying"> </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
<p id="controls">
- <i id="prev" class="fa fa-fast-backward fa-4x clickable"></i>
- <i id="play" class="fa fa-play fa-4x clickable"></i>
- <i id="next" class="fa fa-fast-forward fa-4x clickable"></i>
+ <i id="prev" class="fa fa-fast-backward fa-2x clickable"></i>
+ <i id="play" class="fa fa-play fa-2x clickable"></i>
+ <i id="next" class="fa fa-fast-forward fa-2x clickable"></i>
<i id="mode" class="fa fa-random fa-2x clickable"></i>
</p>
<ol id="playlist" class="playlist"></ol>
</body>
</html>
\ No newline at end of file
diff --git a/src/data/popup/index.js b/src/data/popup/index.js
index a649a1b..83d7541 100644
--- a/src/data/popup/index.js
+++ b/src/data/popup/index.js
@@ -1,301 +1,351 @@
var bg = chrome.extension.getBackgroundPage();
var tracks = bg.tracks;
var sm = bg.soundManager;
var divLoading, divPosition, divPosition2, nowplaying, playlist, currentSound, currentTrack;
var buttons = {};
var shuffleMode = bg.settings.shuffle;
function getPlayingSound() {
if (currentSound && currentSound.playState === 1) {
return currentSound;
}
for (sound in sm.sounds) {
if (sm.sounds[sound].playState === 1) {
currentSound = sm.sounds[sound];
return currentSound;
}
}
}
var shuffleSort = {
true: function (array) {
var n = array.length;
while (n--) {
var i = Math.floor(n * Math.random());
var tmp = array[i];
array[i] = array[n];
array[n] = tmp;
}
return array;
},
false: function (array) {
return array.sort(function (a, b) { return tracks[a].order - tracks[b].order; });
}
};
function toggleShuffle() {
shuffleMode = !shuffleMode;
shuffleSort[shuffleMode](sm.soundIDs);
}
var skipDirections = {
forward: bg.playnextsong,
backward: bg.playprevsong
};
function skip(direction) {
var sound = getPlayingSound();
var soundId;
if (sound) {
sound.stop();
soundId = sound.sID;
}
skipDirections[direction](soundId);
}
function togglePause() {
var sound = getPlayingSound();
if (sound) {
return !!sound.togglePause().paused;
}
skip('forward');
}
+function toggleDisplay(elm, isVisible) {
+ if (isVisible) {
+ elm.className = elm.className.replace(' hidden', '')
+ } else if (!/hidden/.test(elm.className)) {
+ elm.className += ' hidden';
+ }
+}
+
function getTrackDisplayName(track) {
display = [];
if (track.artist) {
display.push(track.artist);
}
if (track.title) {
display.push(track.title);
}
if (!display.length) {
display.push([track.type, track.id]);
}
return display.join(' - ');
}
function remove(id) {
sm.destroySound(id);
var elmTrack = document.getElementById(id);
playlist.removeChild(elmTrack);
}
function play(soundId) {
sm.stopAll();
var sound = sm.getSoundById(soundId);
if (sound) {
sound.play();
}
}
+var updateScheduled, updateTracks, trackSlots = [];
+
+function setIsPlaying(track, isPlaying) {
+ for (var i = 0; i < trackSlots.length; i += 1) {
+ if (trackSlots[i].track === track) {
+ return trackSlots[i].isPlaying(isPlaying);
+ }
+ }
+}
+
var nowPlayingScheduled, scheduleNowPlaying;
function updateNowPlaying() {
nowPlayingScheduled = null;
var sound = getPlayingSound();
if (!sound) {
return scheduleNowPlaying();
}
var bytesLoaded = sound.bytesLoaded;
var bytesTotal = sound.bytesTotal;
var position = sound.position;
var durationEstimate = sound.durationEstimate;
if (bytesTotal) {
divLoading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
}
divPosition.style.left = (100 * position / durationEstimate) + '%';
divPosition2.style.width = (100 * position / durationEstimate) + '%';
if (currentTrack !== tracks[sound.sID]) {
+ setIsPlaying(currentTrack, false);
+
currentTrack = tracks[sound.sID];
nowplaying.textContent = getTrackDisplayName(currentTrack);
+
+ setIsPlaying(currentTrack, true);
}
scheduleNowPlaying();
}
function scheduleNowPlaying() {
nowPlayingScheduled = nowPlayingScheduled || requestAnimationFrame(updateNowPlaying);
}
var playIcons = {
true: 'fa-pause',
false: 'fa-play'
};
var modeIcons = {
true: 'fa-random',
false: 'fa-retweet'
};
-var updateScheduled, updateTracks, trackSlots = [];
-
function scheduleUpdate() {
updateScheduled = updateScheduled || requestAnimationFrame(updateTracks);
}
function TrackSlot(elmParent) {
var that = this;
var liTrack = document.createElement('LI');
var spanTrack = document.createElement('SPAN');
- spanTrack.className = 'clickable';
+ spanTrack.className = 'clickable trackname';
var spanRemove = document.createElement('SPAN');
- spanRemove.className = 'remove clickable fa fa-remove';
+ spanRemove.className = 'remove clickable fa fa-remove fa-2x';
+
+ var aTumblr = document.createElement('A');
+ aTumblr.className = 'clickable fa fa-tumblr fa-2x';
+ aTumblr.target = '_new';
+
+ var aSoundCloud = document.createElement('A');
+ aSoundCloud.className = 'clickable fa fa-soundcloud fa-2x';
+ aSoundCloud.target = '_new';
+
+ var aDownload = document.createElement('A');
+ aDownload.className = 'clickable fa fa-download fa-2x';
+ aDownload.target = '_new';
this.destroy = function () {
elmParent.removeChild(liTrack);
- }
+ };
+
+ this.isPlaying = function (isPlaying) {
+ if (!isPlaying) {
+ liTrack.className = liTrack.className.replace(' isplaying', '');
+ } else if (!/isplaying/.test(liTrack.className)) {
+ liTrack.className += ' isplaying';
+ }
+ };
this.play = function () {
sm.stopAll();
if (that.sound) {
that.sound.play();
}
};
this.remove = function () {
if (that.sound.playState === 1) {
sm.stopAll();
skip('forward')
}
sm.destroySound(that.sound.sID);
scheduleUpdate();
};
this.update = function (id) {
that.sound = sm.getSoundById(id);
that.track = tracks[id];
liTrack.id = that.id = id;
spanTrack.textContent = getTrackDisplayName(that.track);
+
+ aTumblr.href = that.track.postUrl;
+ aSoundCloud.href = that.track.permalinkUrl;
+ aDownload.href = that.track.downloadUrl;
+
+ toggleDisplay(aSoundCloud, that.track.permalinkUrl);
+ toggleDisplay(aDownload, that.track.downloadable);
}
spanTrack.addEventListener('click', function (e) {
that.play();
e.preventDefault();
e.stopPropagation();
}, false);
spanRemove.addEventListener('click', function (e) {
that.remove()
e.preventDefault();
e.stopPropagation();
}, false);
+ liTrack.appendChild(aTumblr);
+ liTrack.appendChild(aSoundCloud);
+ liTrack.appendChild(aDownload);
liTrack.appendChild(spanTrack);
liTrack.appendChild(spanRemove);
elmParent.appendChild(liTrack);
}
function updateTracks() {
updateScheduled = null;
while (trackSlots.length < sm.soundIDs.length) {
trackSlots.push(new TrackSlot(playlist));
}
while (trackSlots.length > sm.soundIDs.length) {
trackSlots.pop().destroy();
}
for (var i = 0; i < sm.soundIDs.length; i += 1) {
var id = sm.soundIDs[i];
trackSlots[i].update(id);
}
}
function onOpen() {
divLoading = document.getElementById('loading');
divPosition = document.getElementById('position');
divPosition2 = document.getElementById('position2');
nowplaying = document.getElementById('nowplaying');
playlist = document.getElementById('playlist');
buttons.prev = document.getElementById('prev');
buttons.play = document.getElementById('play');
buttons.next = document.getElementById('next');
buttons.mode = document.getElementById('mode');
buttons.prev.addEventListener('click', function (e) {
skip('backward');
e.preventDefault();
e.stopPropagation();
}, false);
function updatePlayButton(playing) {
buttons.play.className = buttons.play.className.replace(playIcons[playing], playIcons[!playing]);
}
buttons.play.addEventListener('click', function (e) {
var playing = togglePause();
updatePlayButton(playing);
e.preventDefault();
e.stopPropagation();
}, false);
buttons.next.addEventListener('click', function (e) {
skip('forward');
e.preventDefault();
e.stopPropagation();
}, false);
function updateModeButton() {
buttons.mode.className = buttons.mode.className.replace(modeIcons[!shuffleMode], modeIcons[shuffleMode]);
}
buttons.mode.addEventListener('click', function (e) {
toggleShuffle();
updateModeButton();
scheduleUpdate();
e.preventDefault();
e.stopPropagation();
}, false);
var sound = getPlayingSound();
if (sound && sound.playState === 1) {
updatePlayButton(false);
}
updateModeButton();
scheduleUpdate();
scheduleNowPlaying();
}
document.addEventListener('DOMContentLoaded', onOpen);
diff --git a/src/data/script.js b/src/data/script.js
index 51766d1..3eba3a6 100644
--- a/src/data/script.js
+++ b/src/data/script.js
@@ -1,280 +1,261 @@
// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var settings, started;
function addLink(track) {
var elmPost = document.getElementById('post_' + track.postId);
if (!elmPost) {
console.error('couldn\'t find post:', track.postId);
return;
}
var elmFooter = elmPost.querySelector('.post_footer');
if (!elmFooter) {
console.error('couldn\'t find footer:', track.postId);
return;
}
var divDownload = elmFooter.querySelector('.tumtaster');
if (divDownload) {
return;
}
divDownload = document.createElement('DIV');
divDownload.className = 'tumtaster';
var aDownload = document.createElement('A');
aDownload.href = track.downloadUrl;
aDownload.textContent = 'Download';
if (!track.downloadable) {
aDownload.style.setProperty('text-decoration', 'line-through');
}
divDownload.appendChild(aDownload);
elmFooter.insertBefore(divDownload, elmFooter.children[1]);
}
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
addLink(message.track);
}
}
var port = chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, '(.*?)');
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var posts = {};
function makeTumblrLink(dataset) {
var postId = dataset.postId;
var post = {
artist: dataset.artist,
baseUrl: dataset.streamUrl,
dataset: dataset,
postId: postId,
postKey: dataset.postKey,
seen: Date.now(),
title: dataset.track,
type: 'tumblr'
};
if (!posts[postId]) {
posts[postId] = post;
}
port.postMessage({ post: post });
}
function makeSoundCloudLink(dataset, url) {
var postId = dataset.postId;
var qs = url.split('?')[1];
var chunks = qs.split('&');
var url;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
url = decodeURIComponent(chunks[i].substring(4));
break;
}
}
var post = {
baseUrl: url,
dataset: dataset,
postId: postId,
seen: Date.now(),
type: 'soundcloud'
};
if (!posts[postId]) {
posts[postId] = post;
}
port.postMessage({ post: post });
}
+function extractPermalink(post) {
+ permalink = post.querySelector('.post_permalink') || {};
+ return permalink.href;
+}
+
function extractAudioData(post) {
var postId = post.dataset.postId;
if (!postId) {
return;
}
+ post.dataset.postUrl = extractPermalink(post);
+
var soundcloud = post.querySelector('.soundcloud_audio_player');
if (soundcloud) {
return makeSoundCloudLink(post.dataset, soundcloud.src);
}
var tumblr = post.querySelector('.audio_player_container');
if (tumblr) {
+ tumblr.dataset.postUrl = post.dataset.postUrl;
return makeTumblrLink(tumblr.dataset);
}
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target.parentNode);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var cssRules = [];
cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
- document.addEventListener('MSAnimationStart', handleNodeInserted, false);
- document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
- document.addEventListener('OAnimationStart', handleNodeInserted, false);
-
- cssRules[0] = '@keyframes nodeInserted {';
- cssRules[0] += ' from { clip: rect(1px, auto, auto, auto); }';
- cssRules[0] += ' to { clip: rect(0px, auto, auto, auto); }';
- cssRules[0] += '}';
-
- cssRules[1] = '@-moz-keyframes nodeInserted {';
- cssRules[1] += ' from { clip: rect(1px, auto, auto, auto); }';
- cssRules[1] += ' to { clip: rect(0px, auto, auto, auto); }';
- cssRules[1] += '}';
-
- cssRules[2] = '@-webkit-keyframes nodeInserted {';
- cssRules[2] += ' from { clip: rect(1px, auto, auto, auto); }';
- cssRules[2] += ' to { clip: rect(0px, auto, auto, auto); }';
- cssRules[2] += '}';
-
- cssRules[3] = '@-ms-keyframes nodeInserted {';
- cssRules[3] += ' from { clip: rect(1px, auto, auto, auto); }';
- cssRules[3] += ' to { clip: rect(0px, auto, auto, auto); }';
- cssRules[3] += '}';
-
- cssRules[4] = '@-o-keyframes nodeInserted {';
- cssRules[4] += ' from { clip: rect(1px, auto, auto, auto); }';
- cssRules[4] += ' to { clip: rect(0px, auto, auto, auto); }';
- cssRules[4] += '}';
-
- cssRules[5] = '.post_container div.post, li.post {';
- cssRules[5] += ' animation-duration: 1ms;';
- cssRules[5] += ' -o-animation-duration: 1ms;';
- cssRules[5] += ' -ms-animation-duration: 1ms;';
- cssRules[5] += ' -moz-animation-duration: 1ms;';
- cssRules[5] += ' -webkit-animation-duration: 1ms;';
- cssRules[5] += ' animation-name: nodeInserted;';
- cssRules[5] += ' -o-animation-name: nodeInserted;';
- cssRules[5] += ' -ms-animation-name: nodeInserted;';
- cssRules[5] += ' -moz-animation-name: nodeInserted;';
- cssRules[5] += ' -webkit-animation-name: nodeInserted;';
- cssRules[5] += '}';
+
+ cssRules.push(
+ '@keyframes nodeInserted {' +
+ ' from { clip: rect(1px, auto, auto, auto); }' +
+ ' to { clip: rect(0px, auto, auto, auto); }' +
+ '}'
+ );
+
+ cssRules.push(
+ '.post_container .post {' +
+ ' animation-duration: 1ms;' +
+ ' animation-name: nodeInserted;' +
+ '}'
+ );
addGlobalStyle('tastyWires', cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
if (!checkurl(location.href, settings['listSites'])) {
port.disconnect();
return;
}
started = true;
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
document.onreadystatechange = startTasting;
document.addEventListener('DOMContentLoaded', startTasting);
-startTasting();
\ No newline at end of file
+startTasting();
diff --git a/src/manifest.json b/src/manifest.json
index eaf2db8..6392483 100644
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -1,42 +1,42 @@
{
"name": "TumTaster",
- "version": "0.6.1",
+ "version": "0.7.0",
"description": "Creates download links on Tumblr audio posts.",
"background": {
"scripts": [
"data/defaults.js",
"data/main.js",
"data/soundmanager2-nodebug-jsmin.js"
]
},
"browser_action": {
"default_icon": "data/images/Icon-16.png",
"default_popup": "data/popup/index.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [
"data/script.js"
],
"matches": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*"
],
"all_frames": true,
"run_at": "document_start"
} ],
"icons": {
"16": "data/images/Icon-16.png",
"32": "data/images/Icon-32.png",
"48": "data/images/Icon-48.png",
"64": "data/images/Icon-64.png",
"128": "data/images/Icon-128.png"
},
"manifest_version": 2,
"options_page": "data/options/index.html",
"permissions": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*",
"https://api.soundcloud.com/*"
]
}
\ No newline at end of file
diff --git a/src/package.json b/src/package.json
index b98fb81..2fbddd5 100644
--- a/src/package.json
+++ b/src/package.json
@@ -1,13 +1,13 @@
{
"name": "tumtaster",
"license": "MPL 2.0",
"author": "Bjorn Stromberg",
- "version": "0.6.1",
+ "version": "0.7.0",
"fullName": "TumTaster",
"id": "jid1-W5guVoyeUR0uBg",
"description": "Creates download links on Tumblr audio posts",
"homepage": "http://tumtaster.bjornstar.com",
"icon": "data/images/Icon-48.png",
"icon64": "data/images/Icon-64.png",
"lib": "data"
}
\ No newline at end of file
|
bjornstar/TumTaster
|
b87180c9043de85226155cd204da4ae9e97bcbac
|
* Fixed an issue where posts that reappeared would not get their download links reapplied * Added this HISTORY file
|
diff --git a/HISTORY.md b/HISTORY.md
index 0cb79a4..486503f 100644
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -1,13 +1,12 @@
#TumTaster Changelog
##v0.6.1
-* Fixed an issue where posts that reappeared would not get their download links reapplied
-* Added this HISTORY file
+ * Fixed an issue where posts that reappeared would not get their download links reapplied
+ * Added this HISTORY file
##v0.6.0
-* Updated to work with the SSL dashboard
-* Reorganized files so that all the actual extension files are in src
-* Now handles soundcloud playlists, pulling out links for each track
-* Works on the search page as well as the dashboard
-* Added fontawesome for iconography in popup
-* Extracts track information and displays properly in popup.
+ * Updated to work with https.
+ * Also makes a download link for each track in a soundcloud playlist.
+ * The audio player has had some love given to it, it should be friendlier to use now.
+ * Updates soundmanager2 version
+ * Added icons from fontawesome
diff --git a/src/data/defaults.js b/src/data/defaults.js
index cb4151c..807fdd2 100644
--- a/src/data/defaults.js
+++ b/src/data/defaults.js
@@ -1,19 +1,19 @@
-// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
+// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var defaultSettings = {
- 'version': '0.6.0',
+ 'version': '0.6.1',
'shuffle': false,
'repeat': true,
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://www.tumblr.com/*',
'https://www.tumblr.com/*',
]
};
diff --git a/src/data/main.js b/src/data/main.js
index 3d329e1..019d9fd 100644
--- a/src/data/main.js
+++ b/src/data/main.js
@@ -1,196 +1,196 @@
-// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
+// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
var settings = defaultSettings;
var savedSettings = localStorage['settings'];
try {
if (savedSettings) {
settings = JSON.parse(savedSettings);
}
} catch (e) {
console.error('Failed to parse settings: ', e);
}
var ports = {};
var tracks = {};
var scData = {};
var order = 0;
function getDetails(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '.json?client_id=' + API_KEY, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
return cb(e);
}
cb(null, response);
}
}
xhr.send();
}
function broadcast(msg) {
for (var portId in ports) {
ports[portId].postMessage(msg);
}
}
function addToLibrary(track, seenBefore) {
order += 1;
var id = track.id;
track.order = order;
broadcast({ track: track });
if (!track.streamable || seenBefore) {
return;
}
function failOrFinish() {
playnextsong(id);
}
if (track.streamable) {
soundManager.createSound({
id: id,
url: track.streamUrl,
onloadfailed: failOrFinish,
onfinish: failOrFinish
});
}
tracks[id] = track;
}
function addSoundCloudTrack(post, details) {
var track = {
downloadUrl: details.uri + '/download?client_id=' + API_KEY,
streamUrl: details.uri + '/stream?client_id=' + API_KEY,
downloadable: details.downloadable,
streamable: details.streamable,
artist: details.user ? details.user.username : '',
title: details.title,
id: details.id,
seen: post.seen,
postId: post.postId
};
var seenBefore = scData.hasOwnProperty(track.id);
scData[track.id] = details;
addToLibrary(track, seenBefore);
}
var addPosts = {
tumblr: function (post) {
post.downloadUrl = post.baseUrl + '?play_key=' + post.postKey;
post.streamUrl = post.downloadUrl;
post.downloadable = true;
post.streamable = true;
post.id = post.postId;
addToLibrary(post);
},
soundcloud: function (post) {
getDetails(post.baseUrl, function (e, details) {
if (e) {
return console.error(error);
}
details = details || {};
switch (details.kind) {
case 'track':
return addSoundCloudTrack(post, details);
case 'playlist':
for (var i = 0; i < details.tracks.length; i += 1) {
addSoundCloudTrack(post, details.tracks[i]);
}
break;
default:
console.error('I don\'t know how to handle', details);
}
});
}
}
function messageHandler(port, message) {
if (message === 'getSettings') {
return port.postMessage({ settings: settings});
}
if (message.hasOwnProperty('post')) {
var post = message.post;
addPosts[post.type](post);
}
}
function connectHandler(port) {
ports[port.portId_] = port;
port.onMessage.addListener(function onMessageHandler(message) {
messageHandler(port, message);
});
port.postMessage({ settings: settings });
port.onDisconnect.addListener(function onDisconnectHandler() {
disconnectHandler(port);
});
}
function disconnectHandler(port) {
delete ports[port.portId_];
}
chrome.runtime.onConnect.addListener(connectHandler);
function playnextsong(lastSoundID) {
if (!soundManager.soundIDs.length) {
return;
}
var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
var nextIndex = (currentIndex + 1) % soundManager.soundIDs.length;
var nextSound = soundManager.getSoundById(soundManager.soundIDs[nextIndex]);
nextSound.play();
}
function playprevsong(lastSoundID) {
if (!soundManager.soundIDs.length) {
return;
}
var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
var prevIndex = (currentIndex - 1) % soundManager.soundIDs.length;
var prevSound = soundManager.getSoundById(soundManager.soundIDs[prevIndex]);
prevSound.play();
}
document.addEventListener('DOMContentLoaded', function () {
soundManager.setup({'preferFlash': false});
});
|
bjornstar/TumTaster
|
e3771ed5d08f03fe64b6d215b5737494fec53cd4
|
* Fixed an issue where posts that reappeared would not get their download links reapplied * Added this HISTORY file
|
diff --git a/HISTORY.md b/HISTORY.md
new file mode 100644
index 0000000..0cb79a4
--- /dev/null
+++ b/HISTORY.md
@@ -0,0 +1,13 @@
+#TumTaster Changelog
+
+##v0.6.1
+* Fixed an issue where posts that reappeared would not get their download links reapplied
+* Added this HISTORY file
+
+##v0.6.0
+* Updated to work with the SSL dashboard
+* Reorganized files so that all the actual extension files are in src
+* Now handles soundcloud playlists, pulling out links for each track
+* Works on the search page as well as the dashboard
+* Added fontawesome for iconography in popup
+* Extracts track information and displays properly in popup.
diff --git a/src/Info.plist b/src/Info.plist
index 7c540d5..8865ab7 100644
--- a/src/Info.plist
+++ b/src/Info.plist
@@ -1,87 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Author</key>
<string>Bjorn Stromberg</string>
<key>Builder Version</key>
<string>10600.1.25</string>
<key>CFBundleDisplayName</key>
<string>TumTaster</string>
<key>CFBundleIdentifier</key>
<string>com.bjornstar.safari.tumtaster</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleShortVersionString</key>
- <string>0.6.0</string>
+ <string>0.6.1</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>Chrome</key>
<dict>
<key>Global Page</key>
<string>index.html</string>
<key>Toolbar Items</key>
<array>
<dict>
<key>Command</key>
<string>popup</string>
<key>Identifier</key>
<string>TumTaster Toolbar Button</string>
<key>Image</key>
<string>data/images/Icon-64.png</string>
<key>Label</key>
<string>TumTaster</string>
<key>Tool Tip</key>
<string>Click me to play some music</string>
</dict>
</array>
</dict>
<key>Content</key>
<dict>
<key>Blacklist</key>
<array>
<string>http://www.tumblr.com/uploads/*</string>
<string>https://www.tumblr.com/uploads/*</string>
</array>
<key>Scripts</key>
<dict>
<key>Start</key>
<array>
<string>data/script.js</string>
</array>
</dict>
<key>Whitelist</key>
<array>
<string>http://www.tumblr.com/*</string>
<string>https://www.tumblr.com/*</string>
<string>safari-extension://com.bjornstar.safari.tumtaster-4GANG9K96D/*</string>
</array>
</dict>
<key>Description</key>
<string>TumTaster creates download links on Tumblr audio posts</string>
<key>DeveloperIdentifier</key>
<string>4GANG9K96D</string>
<key>ExtensionInfoDictionaryVersion</key>
<string>1.0</string>
<key>Permissions</key>
<dict>
<key>Website Access</key>
<dict>
<key>Allowed Domains</key>
<array>
<string>com.bjornstar.safari.tumtaster-4GANG9K96D</string>
<string>www.tumblr.com</string>
<string>api.soundcloud.com</string>
</array>
<key>Include Secure Pages</key>
<true/>
<key>Level</key>
<string>Some</string>
</dict>
</dict>
<key>Update Manifest URL</key>
<string>http://tumtaster.bjornstar.com/update.plist</string>
<key>Website</key>
<string>http://tumtaster.bjornstar.com</string>
</dict>
</plist>
diff --git a/src/data/options/index.js b/src/data/options/index.js
index fcf8727..7f4ad2c 100644
--- a/src/data/options/index.js
+++ b/src/data/options/index.js
@@ -1,174 +1,173 @@
var inputLast = 0;
document.addEventListener('DOMContentLoaded', function () {
var save_btn = document.getElementById('save_btn');
var reset_btn = document.getElementById('reset_btn');
var listWhiteAdd = document.getElementById('listWhiteAdd');
var listBlackAdd = document.getElementById('listBlackAdd');
var listSitesAdd = document.getElementById('listSitesAdd');
save_btn.addEventListener('click', saveOptions);
reset_btn.addEventListener('click', function() { if (confirm('Are you sure you want to restore defaults?')) {eraseOptions()} });
listWhiteAdd.addEventListener('click', function(e) {
addInput('listWhite');
e.preventDefault();
e.stopPropagation();
}, false);
listBlackAdd.addEventListener('click', function(e) {
addInput('listBlack');
e.preventDefault();
e.stopPropagation();
}, false);
listSitesAdd.addEventListener('click', function(e) {
addInput('listSites');
e.preventDefault();
e.stopPropagation();
}, false);
loadOptions();
});
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
var cbShuffle = document.getElementById('optionShuffle');
cbShuffle.checked = settings['shuffle'];
var cbRepeat = document.getElementById('optionRepeat');
cbRepeat.checked = settings['repeat'];
for (var itemBlack in settings['listBlack']) {
addInput('listBlack', settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput('listWhite', settings['listWhite'][itemWhite]);
}
for (var itemSites in settings['listSites']) {
addInput('listSites', settings['listSites'][itemSites]);
}
addInput('listBlack'); //prepare a blank input box.
addInput('listWhite'); //prepare a blank input box.
addInput('listSites'); //prepare a blank input box.
var version_div = document.getElementById('version_div');
version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
if (typeof opera != 'undefined') {
var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = 'for Opera™';
}
if (typeof chrome != 'undefined') {
var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = 'for Chrome™';
}
if (typeof safari != 'undefined') {
var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = 'for Safari™';
}
}
function removeInput(optionWhich) {
var optionInput = document.getElementById(optionWhich);
if (!optionInput) {
return;
}
optionInput.parentNode.removeChild(optionInput);
}
function addInput(whichList, itemValue) {
var listDiv, listAdd, optionInput, currentLength, removeThis, optionAdd, optionImage, optionLinebreak, optionDiv;
if (itemValue === undefined) { //if we don't pass an itemValue, make it blank.
itemValue = '';
}
currentLength = inputLast++; //have unique DOM id's
listDiv = document.getElementById(whichList);
listAdd = document.getElementById(whichList + 'Add');
optionInput = document.createElement('input');
optionInput.value = itemValue;
optionInput.name = 'option' + whichList;
optionInput.id = 'option' + whichList + currentLength;
optionAdd = document.createElement('a');
optionAdd.href = '#';
optionAdd.addEventListener('click', function (e) {
removeThis = e.target;
while (removeThis.tagName !== 'DIV') {
removeThis = removeThis.parentNode;
}
if (removeThis.id.indexOf('_div') >= 0) {
removeInput(removeThis.id);
}
e.preventDefault();
e.stopPropagation();
}, false);
optionAdd.appendChild(document.createTextNode('\u00A0'));
optionImage = document.createElement('img');
optionImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
optionAdd.appendChild(optionImage);
optionAdd.appendChild(document.createTextNode('\u00A0'));
optionLinebreak = document.createElement('br');
optionDiv = document.createElement('div');
optionDiv.id = 'option' + whichList + currentLength + '_div';
optionDiv.appendChild(optionAdd);
optionDiv.appendChild(optionInput);
optionDiv.appendChild(optionLinebreak);
listDiv.insertBefore(optionDiv, listAdd);
}
function saveOptions() {
var settings = {};
var cbShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = cbShuffle.checked;
var cbRepeat = document.getElementById('optionRepeat');
settings['repeat'] = cbRepeat.checked;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != '') {
- console.log(garbages[i]);
if (garbages[i].name.indexOf('listWhite') !== -1) {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.indexOf('listBlack') !== -1) {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.indexOf('listSites') !== -1) {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
//location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
diff --git a/src/data/script.js b/src/data/script.js
index 3c631d6..51766d1 100644
--- a/src/data/script.js
+++ b/src/data/script.js
@@ -1,265 +1,280 @@
-// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
+// TumTaster -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var settings, started;
function addLink(track) {
- console.log(track);
var elmPost = document.getElementById('post_' + track.postId);
if (!elmPost) {
console.error('couldn\'t find post:', track.postId);
return;
}
var elmFooter = elmPost.querySelector('.post_footer');
if (!elmFooter) {
console.error('couldn\'t find footer:', track.postId);
return;
}
- var divDownload = document.createElement('DIV');
+ var divDownload = elmFooter.querySelector('.tumtaster');
+ if (divDownload) {
+ return;
+ }
+
+ divDownload = document.createElement('DIV');
divDownload.className = 'tumtaster';
var aDownload = document.createElement('A');
aDownload.href = track.downloadUrl;
aDownload.textContent = 'Download';
if (!track.downloadable) {
aDownload.style.setProperty('text-decoration', 'line-through');
}
divDownload.appendChild(aDownload);
elmFooter.insertBefore(divDownload, elmFooter.children[1]);
}
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
addLink(message.track);
}
}
var port = chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, '(.*?)');
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var posts = {};
function makeTumblrLink(dataset) {
var postId = dataset.postId;
- posts[postId] = {
- postId: postId,
+ var post = {
+ artist: dataset.artist,
baseUrl: dataset.streamUrl,
+ dataset: dataset,
+ postId: postId,
postKey: dataset.postKey,
- artist: dataset.artist,
seen: Date.now(),
title: dataset.track,
type: 'tumblr'
};
- port.postMessage({ post: posts[postId] });
+ if (!posts[postId]) {
+ posts[postId] = post;
+ }
+
+ port.postMessage({ post: post });
}
function makeSoundCloudLink(dataset, url) {
+ var postId = dataset.postId;
+
var qs = url.split('?')[1];
var chunks = qs.split('&');
var url;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
url = decodeURIComponent(chunks[i].substring(4));
break;
}
}
- var postId = dataset.postId;
-
- posts[postId] = {
- postId: postId,
+ var post = {
baseUrl: url,
+ dataset: dataset,
+ postId: postId,
seen: Date.now(),
type: 'soundcloud'
};
- port.postMessage({ post: posts[postId] });
+ if (!posts[postId]) {
+ posts[postId] = post;
+ }
+
+ port.postMessage({ post: post });
}
function extractAudioData(post) {
var postId = post.dataset.postId;
- if (!postId || posts[postId]) {
+
+ if (!postId) {
return;
}
var soundcloud = post.querySelector('.soundcloud_audio_player');
if (soundcloud) {
return makeSoundCloudLink(post.dataset, soundcloud.src);
}
var tumblr = post.querySelector('.audio_player_container');
if (tumblr) {
return makeTumblrLink(tumblr.dataset);
}
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target.parentNode);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var cssRules = [];
cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
cssRules[0] = '@keyframes nodeInserted {';
cssRules[0] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[0] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[0] += '}';
cssRules[1] = '@-moz-keyframes nodeInserted {';
cssRules[1] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[1] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[1] += '}';
cssRules[2] = '@-webkit-keyframes nodeInserted {';
cssRules[2] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[2] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[2] += '}';
cssRules[3] = '@-ms-keyframes nodeInserted {';
cssRules[3] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[3] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[3] += '}';
cssRules[4] = '@-o-keyframes nodeInserted {';
cssRules[4] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[4] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[4] += '}';
cssRules[5] = '.post_container div.post, li.post {';
cssRules[5] += ' animation-duration: 1ms;';
cssRules[5] += ' -o-animation-duration: 1ms;';
cssRules[5] += ' -ms-animation-duration: 1ms;';
cssRules[5] += ' -moz-animation-duration: 1ms;';
cssRules[5] += ' -webkit-animation-duration: 1ms;';
cssRules[5] += ' animation-name: nodeInserted;';
cssRules[5] += ' -o-animation-name: nodeInserted;';
cssRules[5] += ' -ms-animation-name: nodeInserted;';
cssRules[5] += ' -moz-animation-name: nodeInserted;';
cssRules[5] += ' -webkit-animation-name: nodeInserted;';
cssRules[5] += '}';
addGlobalStyle('tastyWires', cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
if (!checkurl(location.href, settings['listSites'])) {
port.disconnect();
return;
}
started = true;
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
document.onreadystatechange = startTasting;
document.addEventListener('DOMContentLoaded', startTasting);
startTasting();
\ No newline at end of file
diff --git a/src/manifest.json b/src/manifest.json
index b1c0e72..eaf2db8 100644
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -1,42 +1,42 @@
{
"name": "TumTaster",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "Creates download links on Tumblr audio posts.",
"background": {
"scripts": [
"data/defaults.js",
"data/main.js",
"data/soundmanager2-nodebug-jsmin.js"
]
},
"browser_action": {
"default_icon": "data/images/Icon-16.png",
"default_popup": "data/popup/index.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [
"data/script.js"
],
"matches": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*"
],
"all_frames": true,
"run_at": "document_start"
} ],
"icons": {
"16": "data/images/Icon-16.png",
"32": "data/images/Icon-32.png",
"48": "data/images/Icon-48.png",
"64": "data/images/Icon-64.png",
"128": "data/images/Icon-128.png"
},
"manifest_version": 2,
"options_page": "data/options/index.html",
"permissions": [
"http://www.tumblr.com/*",
"https://www.tumblr.com/*",
"https://api.soundcloud.com/*"
]
}
\ No newline at end of file
diff --git a/src/package.json b/src/package.json
index a912998..b98fb81 100644
--- a/src/package.json
+++ b/src/package.json
@@ -1,13 +1,13 @@
{
"name": "tumtaster",
"license": "MPL 2.0",
"author": "Bjorn Stromberg",
- "version": "0.6.0",
+ "version": "0.6.1",
"fullName": "TumTaster",
"id": "jid1-W5guVoyeUR0uBg",
"description": "Creates download links on Tumblr audio posts",
"homepage": "http://tumtaster.bjornstar.com",
"icon": "data/images/Icon-48.png",
"icon64": "data/images/Icon-64.png",
"lib": "data"
}
\ No newline at end of file
|
bjornstar/TumTaster
|
39f320367d74092730b88e4e2fdb7f21b07b2ed1
|
v0.6.0 - The player mostly sorta works kinda
|
diff --git a/src/data/css/popup.css b/src/data/css/popup.css
index 525ade8..834bb27 100644
--- a/src/data/css/popup.css
+++ b/src/data/css/popup.css
@@ -1,181 +1,178 @@
html {
color: black;
font-family: arial, helvetica, sans-serif;
margin: 0;
padding: 0;
background-color: #36465d;
min-width: 400px;
}
h1 {
- color:black;
-}
-
-a {
- color:white;
- text-decoration:none;
+ color: black;
}
ol {
background-attachment: scroll;
background-clip: border-box;
- background-color: #2C4762;
+ background-color: #36465d;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
+ color: #444;
display: block;
list-style-type: none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
-li a {
- color:#444;
-}
-
li {
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span {
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
#heading {
width: 100%;
height: 64px;
}
#heading h1 {
color: white;
float: left;
line-height: 32px;
vertical-align: absmiddle;
margin-left: 10px;
}
div#statistics {
position: absolute;
bottom: 0%;
}
#controls{
text-align: center;
- width: 100%
+ width: 100%;
+ color: white;
}
-#controls a {
+#controls i {
margin: 20px;
}
#statusbar{
position: relative;
height: 12px;
background-color: #CDD568;
border: 2px solid #EAF839;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
overflow: hidden;
margin-top: 4px;
}
.remove {
position: absolute;
right: 8px;
top: 8px;
}
.position, .position2, .loading {
position: absolute;
left: 0px;
bottom: 0px;
height: 12px;
}
.position {
background-color: #3B440F;
border-right: 2px solid #3B440F;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
width: 20px;
}
.position2 {
background-color: #EAF839;
}
.loading {
background-color: #BBC552;
}
+
+.clickable {
+ cursor: hand;
+}
\ No newline at end of file
diff --git a/src/data/main.js b/src/data/main.js
index d8c8a46..3d329e1 100644
--- a/src/data/main.js
+++ b/src/data/main.js
@@ -1,193 +1,196 @@
// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
var settings = defaultSettings;
var savedSettings = localStorage['settings'];
try {
if (savedSettings) {
settings = JSON.parse(savedSettings);
}
} catch (e) {
console.error('Failed to parse settings: ', e);
}
var ports = {};
var tracks = {};
var scData = {};
+var order = 0;
+
function getDetails(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url + '.json?client_id=' + API_KEY, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
return cb(e);
}
cb(null, response);
}
}
xhr.send();
}
function broadcast(msg) {
for (var portId in ports) {
ports[portId].postMessage(msg);
}
}
function addToLibrary(track, seenBefore) {
+ order += 1;
+
var id = track.id;
+ track.order = order;
broadcast({ track: track });
if (!track.streamable || seenBefore) {
return;
}
function failOrFinish() {
playnextsong(id);
}
if (track.streamable) {
soundManager.createSound({
id: id,
url: track.streamUrl,
onloadfailed: failOrFinish,
onfinish: failOrFinish
});
}
tracks[id] = track;
}
function addSoundCloudTrack(post, details) {
var track = {
downloadUrl: details.uri + '/download?client_id=' + API_KEY,
streamUrl: details.uri + '/stream?client_id=' + API_KEY,
downloadable: details.downloadable,
streamable: details.streamable,
artist: details.user ? details.user.username : '',
title: details.title,
id: details.id,
+ seen: post.seen,
postId: post.postId
};
var seenBefore = scData.hasOwnProperty(track.id);
scData[track.id] = details;
addToLibrary(track, seenBefore);
}
var addPosts = {
tumblr: function (post) {
post.downloadUrl = post.baseUrl + '?play_key=' + post.postKey;
post.streamUrl = post.downloadUrl;
post.downloadable = true;
post.streamable = true;
post.id = post.postId;
addToLibrary(post);
},
soundcloud: function (post) {
getDetails(post.baseUrl, function (e, details) {
if (e) {
return console.error(error);
}
details = details || {};
- if (details.kind === 'track') {
+ switch (details.kind) {
+ case 'track':
return addSoundCloudTrack(post, details);
- }
-
- for (var i = 0; i < details.tracks.length; i += 1) {
- addSoundCloudTrack(post, details.tracks[i]);
+ case 'playlist':
+ for (var i = 0; i < details.tracks.length; i += 1) {
+ addSoundCloudTrack(post, details.tracks[i]);
+ }
+ break;
+ default:
+ console.error('I don\'t know how to handle', details);
}
});
}
}
function messageHandler(port, message) {
if (message === 'getSettings') {
return port.postMessage({ settings: settings});
}
if (message.hasOwnProperty('post')) {
var post = message.post;
addPosts[post.type](post);
}
}
function connectHandler(port) {
ports[port.portId_] = port;
port.onMessage.addListener(function onMessageHandler(message) {
messageHandler(port, message);
});
port.postMessage({ settings: settings });
port.onDisconnect.addListener(function onDisconnectHandler() {
disconnectHandler(port);
});
}
function disconnectHandler(port) {
delete ports[port.portId_];
}
chrome.runtime.onConnect.addListener(connectHandler);
-function playnextsong(previous_song) {
- var bad_idea = null;
- var first_song = null;
- var next_song = null;
- for (x in soundManager.sounds) {
- if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
- next_song = soundManager.sounds[x].sID;
- }
- bad_idea = soundManager.sounds[x].sID;
- if (first_song == null) {
- first_song = soundManager.sounds[x].sID;
- }
+function playnextsong(lastSoundID) {
+ if (!soundManager.soundIDs.length) {
+ return;
}
- if (settings['shuffle']) {
- var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- next_song = soundManager.soundIDs[s];
- }
+ var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
- if (settings['repeat'] && bad_idea == previous_song) {
- next_song = first_song;
- }
+ var nextIndex = (currentIndex + 1) % soundManager.soundIDs.length;
- if (next_song != null) {
- var soundNext = soundManager.getSoundById(next_song);
- soundNext.play();
- }
+ var nextSound = soundManager.getSoundById(soundManager.soundIDs[nextIndex]);
+
+ nextSound.play();
}
-function playrandomsong(previous_song) {
- var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
- mySoundObject.play();
+function playprevsong(lastSoundID) {
+ if (!soundManager.soundIDs.length) {
+ return;
+ }
+
+ var currentIndex = soundManager.soundIDs.indexOf(lastSoundID);
+
+ var prevIndex = (currentIndex - 1) % soundManager.soundIDs.length;
+
+ var prevSound = soundManager.getSoundById(soundManager.soundIDs[prevIndex]);
+
+ prevSound.play();
}
document.addEventListener('DOMContentLoaded', function () {
soundManager.setup({'preferFlash': false});
});
diff --git a/src/data/popup/index.html b/src/data/popup/index.html
index 9d19b77..b2b8035 100644
--- a/src/data/popup/index.html
+++ b/src/data/popup/index.html
@@ -1,27 +1,27 @@
<html>
<head>
<link href="../css/popup.css" rel="stylesheet" type="text/css">
<link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script src="index.js" type="text/javascript"></script>
</head>
<body>
<div id="heading"><img src="../images/Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
<div id="statistics"><span> </span></div>
<div id="nowplayingdiv"><span id="nowplaying"> </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
<p id="controls">
- <a id="prev" href="#"><i class="fa fa-fast-backward fa-4x"></i></a>
- <a id="play" href="#"><i class="fa fa-play fa-4x"></i></a>
- <a id="next" href="#"><i class="fa fa-fast-forward fa-4x"></i></a>
- <a id="mode" href="#"><i class="fa fa-random fa-4x"></i></a>
+ <i id="prev" class="fa fa-fast-backward fa-4x clickable"></i>
+ <i id="play" class="fa fa-play fa-4x clickable"></i>
+ <i id="next" class="fa fa-fast-forward fa-4x clickable"></i>
+ <i id="mode" class="fa fa-random fa-2x clickable"></i>
</p>
<ol id="playlist" class="playlist"></ol>
</body>
</html>
\ No newline at end of file
diff --git a/src/data/popup/index.js b/src/data/popup/index.js
index f7737cd..a649a1b 100644
--- a/src/data/popup/index.js
+++ b/src/data/popup/index.js
@@ -1,172 +1,301 @@
var bg = chrome.extension.getBackgroundPage();
+
var tracks = bg.tracks;
var sm = bg.soundManager;
-var div_loading, div_position, div_position2, nowplaying;
+var divLoading, divPosition, divPosition2, nowplaying, playlist, currentSound, currentTrack;
+var buttons = {};
+
+var shuffleMode = bg.settings.shuffle;
+
+function getPlayingSound() {
+ if (currentSound && currentSound.playState === 1) {
+ return currentSound;
+ }
-function getPlaying() {
for (sound in sm.sounds) {
- if (sm.sounds[sound].playState == 1) {
- return sm.sounds[sound];
+ if (sm.sounds[sound].playState === 1) {
+ currentSound = sm.sounds[sound];
+ return currentSound;
}
}
}
-function playPause() {
- var track = getPlaying();
+var shuffleSort = {
+ true: function (array) {
+ var n = array.length;
+ while (n--) {
+ var i = Math.floor(n * Math.random());
+ var tmp = array[i];
+ array[i] = array[n];
+ array[n] = tmp;
+ }
+ return array;
+ },
+ false: function (array) {
+ return array.sort(function (a, b) { return tracks[a].order - tracks[b].order; });
+ }
+};
+
+function toggleShuffle() {
+ shuffleMode = !shuffleMode;
- if (track) {
- sm.pauseAll();
- } else {
- sm.resumeAll();
+ shuffleSort[shuffleMode](sm.soundIDs);
+}
+
+var skipDirections = {
+ forward: bg.playnextsong,
+ backward: bg.playprevsong
+};
+
+function skip(direction) {
+ var sound = getPlayingSound();
+
+ var soundId;
+
+ if (sound) {
+ sound.stop();
+ soundId = sound.sID;
}
+
+ skipDirections[direction](soundId);
}
-document.addEventListener('DOMContentLoaded', function () {
- var prevLink = document.getElementById('prev');
- var playLink = document.getElementById('play');
- var nextLink = document.getElementById('next');
- var modeLink = document.getElementById('mode');
+function togglePause() {
+ var sound = getPlayingSound();
- prevLink.addEventListener('click', function(e) {
- prev();
- e.preventDefault();
- e.stopPropagation();
- }, false);
+ if (sound) {
+ return !!sound.togglePause().paused;
+ }
- playLink.addEventListener('click', function(e) {
- playPause();
- e.preventDefault();
- e.stopPropagation();
- }, false);
+ skip('forward');
+}
- nextLink.addEventListener('click', function(e) {
- playnextsong();
- e.preventDefault();
- e.stopPropagation();
- }, false);
+function getTrackDisplayName(track) {
+ display = [];
- modeLink.addEventListener('click', function(e) {
- playrandomsong();
- e.preventDefault();
- e.stopPropagation();
- }, false);
+ if (track.artist) {
+ display.push(track.artist);
+ }
- div_loading = document.getElementById('loading');
- div_position = document.getElementById('position');
- div_position2 = document.getElementById('position2');
- nowplaying = document.getElementById('nowplaying');
+ if (track.title) {
+ display.push(track.title);
+ }
- var playlist = document.getElementById('playlist');
+ if (!display.length) {
+ display.push([track.type, track.id]);
+ }
- for (var id in tracks) {
- var track = tracks[id];
+ return display.join(' - ');
+}
- var liSong = document.createElement('LI');
- var aSong = document.createElement('A');
+function remove(id) {
+ sm.destroySound(id);
- aSong.id = id;
- aSong.addEventListener('click', function(e) {
- play(null, e.target.id);
- e.preventDefault();
- e.stopPropagation();
- }, false);
- aSong.href = '#';
+ var elmTrack = document.getElementById(id);
+ playlist.removeChild(elmTrack);
+}
- var trackDisplay = id;
- if (track.artist && track.title) {
- trackDisplay = track.artist + ' - ' + track.title;
- }
+function play(soundId) {
+ sm.stopAll();
+
+ var sound = sm.getSoundById(soundId);
+ if (sound) {
+ sound.play();
+ }
+}
- aSong.textContent = trackDisplay;
+var nowPlayingScheduled, scheduleNowPlaying;
- var aRemove = document.createElement('A');
- aRemove.className = 'remove';
- aRemove.href = '#';
- aRemove.addEventListener('click', function(e) {
- remove(e.target.parentNode.previousSibling.id);
- e.preventDefault();
- e.stopPropagation();
- }, false);
+function updateNowPlaying() {
+ nowPlayingScheduled = null;
- var iRemove = document.createElement('I');
- iRemove.className = 'fa fa-remove'
+ var sound = getPlayingSound();
- aRemove.appendChild(iRemove);
- liSong.appendChild(aSong);
- liSong.appendChild(aRemove);
- playlist.appendChild(liSong);
+ if (!sound) {
+ return scheduleNowPlaying();
}
- updateStatus();
-});
+ var bytesLoaded = sound.bytesLoaded;
+ var bytesTotal = sound.bytesTotal;
+ var position = sound.position;
+ var durationEstimate = sound.durationEstimate;
-function remove(song_id) {
- sm.destroySound(song_id);
+ if (bytesTotal) {
+ divLoading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
+ }
- var song_li = document.getElementById(song_id);
- song_li.parentNode.parentNode.removeChild(song_li.parentNode);
+ divPosition.style.left = (100 * position / durationEstimate) + '%';
+ divPosition2.style.width = (100 * position / durationEstimate) + '%';
+
+ if (currentTrack !== tracks[sound.sID]) {
+ currentTrack = tracks[sound.sID];
+ nowplaying.textContent = getTrackDisplayName(currentTrack);
+ }
+
+ scheduleNowPlaying();
}
-function pause() {
- track = getPlaying();
- track.pause();
+function scheduleNowPlaying() {
+ nowPlayingScheduled = nowPlayingScheduled || requestAnimationFrame(updateNowPlaying);
}
-function play(song_url,post_url) {
- sm.stopAll();
+var playIcons = {
+ true: 'fa-pause',
+ false: 'fa-play'
+};
+
+var modeIcons = {
+ true: 'fa-random',
+ false: 'fa-retweet'
+};
+
+var updateScheduled, updateTracks, trackSlots = [];
- var sound = sm.getSoundById(post_url);
- sound.play();
+function scheduleUpdate() {
+ updateScheduled = updateScheduled || requestAnimationFrame(updateTracks);
}
-function playnextsong() {
- var track = getPlaying();
+function TrackSlot(elmParent) {
+ var that = this;
- var track_sID;
+ var liTrack = document.createElement('LI');
- if (track) {
- track.stop();
- track_sID = track.sID;
+ var spanTrack = document.createElement('SPAN');
+ spanTrack.className = 'clickable';
+
+ var spanRemove = document.createElement('SPAN');
+ spanRemove.className = 'remove clickable fa fa-remove';
+
+ this.destroy = function () {
+ elmParent.removeChild(liTrack);
}
- bg.playnextsong(track_sID);
+ this.play = function () {
+ sm.stopAll();
+
+ if (that.sound) {
+ that.sound.play();
+ }
+ };
+
+ this.remove = function () {
+ if (that.sound.playState === 1) {
+ sm.stopAll();
+ skip('forward')
+ }
+
+ sm.destroySound(that.sound.sID);
+
+ scheduleUpdate();
+ };
+
+ this.update = function (id) {
+ that.sound = sm.getSoundById(id);
+ that.track = tracks[id];
+
+ liTrack.id = that.id = id;
+ spanTrack.textContent = getTrackDisplayName(that.track);
+ }
+
+ spanTrack.addEventListener('click', function (e) {
+ that.play();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ spanRemove.addEventListener('click', function (e) {
+ that.remove()
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ liTrack.appendChild(spanTrack);
+ liTrack.appendChild(spanRemove);
+
+ elmParent.appendChild(liTrack);
}
-function playrandomsong() {
- var current_song = getPlaying();
- var current_song_sID;
- if (current_song) {
- current_song.stop();
- current_song_sID = current_song.sID;
+function updateTracks() {
+ updateScheduled = null;
+
+ while (trackSlots.length < sm.soundIDs.length) {
+ trackSlots.push(new TrackSlot(playlist));
+ }
+
+ while (trackSlots.length > sm.soundIDs.length) {
+ trackSlots.pop().destroy();
+ }
+
+ for (var i = 0; i < sm.soundIDs.length; i += 1) {
+ var id = sm.soundIDs[i];
+
+ trackSlots[i].update(id);
}
- bg.playrandomsong(current_song_sID);
}
-function updateStatus() {
- var track = getPlaying();
+function onOpen() {
+ divLoading = document.getElementById('loading');
+ divPosition = document.getElementById('position');
+ divPosition2 = document.getElementById('position2');
+
+ nowplaying = document.getElementById('nowplaying');
+ playlist = document.getElementById('playlist');
- if (track) {
- var bytesLoaded = track.bytesLoaded;
- var bytesTotal = track.bytesTotal;
- var position = track.position;
- var durationEstimate = track.durationEstimate;
+ buttons.prev = document.getElementById('prev');
+ buttons.play = document.getElementById('play');
+ buttons.next = document.getElementById('next');
+ buttons.mode = document.getElementById('mode');
- if (bytesTotal) {
- div_loading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
- }
+ buttons.prev.addEventListener('click', function (e) {
+ skip('backward');
+
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
- div_position.style.left = (100 * position / durationEstimate) + '%';
- div_position2.style.width = (100 * position / durationEstimate) + '%';
+ function updatePlayButton(playing) {
+ buttons.play.className = buttons.play.className.replace(playIcons[playing], playIcons[!playing]);
}
- if (track && nowplaying.textContent !== track.id) {
- var trackDisplay = track.id;
- if (tracks[track.id].artist && tracks[track.id].track) {
- trackDisplay = tracks[track.id].artist + ' - ' + tracks[track.id].track;
- }
- nowplaying.textContent = trackDisplay;
+ buttons.play.addEventListener('click', function (e) {
+ var playing = togglePause();
+
+ updatePlayButton(playing);
+
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ buttons.next.addEventListener('click', function (e) {
+ skip('forward');
+
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ function updateModeButton() {
+ buttons.mode.className = buttons.mode.className.replace(modeIcons[!shuffleMode], modeIcons[shuffleMode]);
+ }
+
+ buttons.mode.addEventListener('click', function (e) {
+ toggleShuffle();
+ updateModeButton();
+ scheduleUpdate();
+
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ var sound = getPlayingSound();
+ if (sound && sound.playState === 1) {
+ updatePlayButton(false);
}
- requestAnimationFrame(updateStatus);
-}
\ No newline at end of file
+ updateModeButton();
+
+ scheduleUpdate();
+ scheduleNowPlaying();
+}
+
+document.addEventListener('DOMContentLoaded', onOpen);
diff --git a/src/data/script.js b/src/data/script.js
index 5f9bf2c..3c631d6 100644
--- a/src/data/script.js
+++ b/src/data/script.js
@@ -1,260 +1,265 @@
// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var settings, started;
function addLink(track) {
+ console.log(track);
var elmPost = document.getElementById('post_' + track.postId);
if (!elmPost) {
+ console.error('couldn\'t find post:', track.postId);
return;
}
var elmFooter = elmPost.querySelector('.post_footer');
if (!elmFooter) {
+ console.error('couldn\'t find footer:', track.postId);
return;
}
var divDownload = document.createElement('DIV');
divDownload.className = 'tumtaster';
var aDownload = document.createElement('A');
aDownload.href = track.downloadUrl;
aDownload.textContent = 'Download';
if (!track.downloadable) {
aDownload.style.setProperty('text-decoration', 'line-through');
}
divDownload.appendChild(aDownload);
elmFooter.insertBefore(divDownload, elmFooter.children[1]);
}
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
addLink(message.track);
}
}
var port = chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, '(.*?)');
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var posts = {};
function makeTumblrLink(dataset) {
var postId = dataset.postId;
posts[postId] = {
postId: postId,
baseUrl: dataset.streamUrl,
postKey: dataset.postKey,
artist: dataset.artist,
+ seen: Date.now(),
title: dataset.track,
type: 'tumblr'
};
port.postMessage({ post: posts[postId] });
}
function makeSoundCloudLink(dataset, url) {
var qs = url.split('?')[1];
var chunks = qs.split('&');
var url;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
url = decodeURIComponent(chunks[i].substring(4));
break;
}
}
var postId = dataset.postId;
posts[postId] = {
postId: postId,
baseUrl: url,
+ seen: Date.now(),
type: 'soundcloud'
};
port.postMessage({ post: posts[postId] });
}
function extractAudioData(post) {
var postId = post.dataset.postId;
if (!postId || posts[postId]) {
return;
}
var soundcloud = post.querySelector('.soundcloud_audio_player');
if (soundcloud) {
return makeSoundCloudLink(post.dataset, soundcloud.src);
}
var tumblr = post.querySelector('.audio_player_container');
if (tumblr) {
return makeTumblrLink(tumblr.dataset);
}
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target.parentNode);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var cssRules = [];
cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
cssRules[0] = '@keyframes nodeInserted {';
cssRules[0] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[0] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[0] += '}';
cssRules[1] = '@-moz-keyframes nodeInserted {';
cssRules[1] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[1] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[1] += '}';
cssRules[2] = '@-webkit-keyframes nodeInserted {';
cssRules[2] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[2] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[2] += '}';
cssRules[3] = '@-ms-keyframes nodeInserted {';
cssRules[3] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[3] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[3] += '}';
cssRules[4] = '@-o-keyframes nodeInserted {';
cssRules[4] += ' from { clip: rect(1px, auto, auto, auto); }';
cssRules[4] += ' to { clip: rect(0px, auto, auto, auto); }';
cssRules[4] += '}';
cssRules[5] = '.post_container div.post, li.post {';
cssRules[5] += ' animation-duration: 1ms;';
cssRules[5] += ' -o-animation-duration: 1ms;';
cssRules[5] += ' -ms-animation-duration: 1ms;';
cssRules[5] += ' -moz-animation-duration: 1ms;';
cssRules[5] += ' -webkit-animation-duration: 1ms;';
cssRules[5] += ' animation-name: nodeInserted;';
cssRules[5] += ' -o-animation-name: nodeInserted;';
cssRules[5] += ' -ms-animation-name: nodeInserted;';
cssRules[5] += ' -moz-animation-name: nodeInserted;';
cssRules[5] += ' -webkit-animation-name: nodeInserted;';
cssRules[5] += '}';
addGlobalStyle('tastyWires', cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
if (!checkurl(location.href, settings['listSites'])) {
port.disconnect();
return;
}
started = true;
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
document.onreadystatechange = startTasting;
document.addEventListener('DOMContentLoaded', startTasting);
startTasting();
\ No newline at end of file
|
bjornstar/TumTaster
|
da978c4e107fd9ed02a7d9ab08e5e8b3419288cb
|
v0.6.0 - We even support SoundCloud playlists
|
diff --git a/.gitignore b/.gitignore
index e43b0f9..a3d1d50 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,7 @@
+*.nex
+*.pem
+*.safariextz
+*.xpi
+*.zip
.DS_Store
+src.safariextension
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..77af83a
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Bjorn Stromberg <[email protected]>
+
+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.
diff --git a/README b/README
deleted file mode 100644
index f27ffad..0000000
--- a/README
+++ /dev/null
@@ -1,8 +0,0 @@
-TumTaster v0.5.0 -- http://tumtaster.bjornstar.com
-By Bjorn Stromberg (@bjornstar)
-
-TumTaster adds download links to posts and also keeps a playlist of all the tracks that you've seen. As of v0.5.0 it also tries to read soundcloud tracks. Unfortunately, most soundcloud tracks cannot be downloaded through their API.
-
-TumTaster uses SoundManager2 for managing MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
-
-TumTaster for Google Chrome can be installed here - https://chrome.google.com/webstore/detail/nanfbkacbckngfcklahdgfagjlghfbgm
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..dda4663
--- /dev/null
+++ b/README.md
@@ -0,0 +1,12 @@
+#TumTaster
+By [Bjorn Stromberg](http://bjornstar.com/about)
+
+[TumTaster](http://tumtaster.bjornstar.com/) adds download links to audio posts and gives you a playlist of all the tracks that you've seen for easy access.
+
+TumTaster uses [SoundManager2](http://www.schillmania.com/projects/soundmanager2) V2.97a.20140901 for managing MP3 playback and [FontAwesome](http://fortawesome.github.io/Font-Awesome/) v4.2.0 for icons.
+
+TumTaster for Google Chrome can be installed here - https://chrome.google.com/webstore/detail/nanfbkacbckngfcklahdgfagjlghfbgm
+
+This extension is open source and all source code can be found at [https://github.com/bjornstar/TumTaster](https://github.com/bjornstar/TumTaster).
+
+*Disclaimer: TumTaster is neither affiliated with nor supported by [Tumblr](https://www.tumblr.com/) in any way.*
diff --git a/data/background.js b/data/background.js
deleted file mode 100644
index 8bdea3a..0000000
--- a/data/background.js
+++ /dev/null
@@ -1,113 +0,0 @@
-var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
-
-var settings = defaultSettings;
-
-try {
- settings = JSON.parse(localStorage["settings"]);
-} catch (e) {
-
-}
-
-var ports = {};
-var tracks = {};
-
-function addTrack(newTrack) {
- var id = newTrack.postId;
- var url = newTrack.streamUrl;
-
- if (newTrack.postKey) {
- url = url + '?play_key=' + newTrack.postKey;
- }
-
- if (newTrack.type === 'soundcloud') {
- url = url + '/download?client_id=' + API_KEY;
- }
-
- newTrack.downloadUrl = url;
-
- soundManager.createSound({
- id: id,
- url: url,
- onloadfailed: function(){playnextsong(newTrack.postId)},
- onfinish: function(){playnextsong(newTrack.postId)}
- });
-
- tracks[id] = newTrack;
-
- broadcast({ track: newTrack });
-}
-
-function broadcast(msg) {
- for (var portId in ports) {
- ports[portId].postMessage(msg);
- }
-}
-
-function messageHandler(port, message) {
- if (message === 'getSettings') {
- return port.postMessage({ settings: settings});
- }
-
- if (message.hasOwnProperty('track')) {
- addTrack(message.track);
- }
-}
-
-function connectHandler(port) {
- ports[port.portId_] = port;
-
- port.onMessage.addListener(function onMessageHandler(message) {
- messageHandler(port, message);
- });
-
- port.postMessage({ settings: settings });
-
- port.onDisconnect.addListener(function onDisconnectHandler() {
- disconnectHandler(port);
- });
-}
-
-function disconnectHandler(port) {
- delete ports[port.portId_];
-}
-
-chrome.runtime.onConnect.addListener(connectHandler);
-
-function playnextsong(previous_song) {
- var bad_idea = null;
- var first_song = null;
- var next_song = null;
- for (x in soundManager.sounds) {
- if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
- next_song = soundManager.sounds[x].sID;
- }
- bad_idea = soundManager.sounds[x].sID;
- if (first_song == null) {
- first_song = soundManager.sounds[x].sID;
- }
- }
-
- if (settings["shuffle"]) {
- var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- next_song = soundManager.soundIDs[s];
- }
-
- if (settings["repeat"] && bad_idea == previous_song) {
- next_song = first_song;
- }
-
- if (next_song != null) {
- var soundNext = soundManager.getSoundById(next_song);
- soundNext.play();
- }
-}
-
-function playrandomsong(previous_song) {
- var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
- mySoundObject.play();
-}
-
-document.addEventListener("DOMContentLoaded", function () {
- soundManager.setup({"preferFlash": false});
-});
\ No newline at end of file
diff --git a/data/defaults.js b/data/defaults.js
deleted file mode 100644
index 482e50a..0000000
--- a/data/defaults.js
+++ /dev/null
@@ -1,16 +0,0 @@
-var defaultSettings = { //initialize default values.
- 'version': '0.5.0',
- 'shuffle': false,
- 'repeat': true,
- 'listBlack': [
- 'beatles'
- ],
- 'listWhite': [
- 'bjorn',
- 'beck'
- ],
- 'listSites': [
- 'http://*.tumblr.com/*',
- 'http://bjornstar.com/*'
- ]
-};
\ No newline at end of file
diff --git a/data/options.html b/data/options.html
deleted file mode 100644
index b3c9740..0000000
--- a/data/options.html
+++ /dev/null
@@ -1,105 +0,0 @@
-<html>
- <head>
- <title>Options for TumTaster</title>
- <style type="text/css">
- html{
- color:black;
- font-family:arial,helvetica,sans-serif;
- margin:0;
- padding:10px 30px 30px 10px;
- background-color:#2C4762;
- background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
- background-repeat:repeat-x;
- color:#4F545A;
- width:640px;
- }
- h1{
- color:black;
- }
- h2{
- margin:0;
- }
- p{
- margin:0;
- }
- a{
- color:#4F545A;
- text-decoration:none;
- }
- #content{
- background: white;
- display: block;
- margin: 0px;
- outline-color: #444;
- outline-style: none;
- outline-width: 0px;
- padding-bottom: 5px;
- padding-left: 30px;
- padding-right: 30px;
- padding-top: 5px;
- width: 570px;
- -webkit-border-radius: 10px;
- -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .46);
- }
- #repeat_div,#player_div{
- margin-bottom:25px;
- }
- #listBlack,#listWhite{
- float:left;
- width:240px;
- margin-bottom:25px;
- }
- #listSites{
- clear:left;
- width:540px;
- }
- #listSites input{
- width:400px;
- }
- #version_div{
- color:#A8B1BA;
- font: 11px 'Lucida Grande',Verdana,sans-serif;
- text-align:right;
- }
- #browser_span{
- color:#A8B1BA;
- font: 11px 'Lucida Grande',Verdana,sans-serif;
- vertical-align:top;
- }
- </style>
- <script src="defaults.js" type="text/javascript"></script>
- <script src="options.js" type="text/javascript"></script>
- </head>
- <body>
- <div id="content">
- <img style="float:left;" src="Icon-64.png">
- <h1 style="line-height:32px;height:32px;margin-top:16px;">TumTaster Options <span id="browser_span"> </span></h1>
-
- <div id="shuffle_div">
- <input type="checkbox" id="optionShuffle" name="optionShuffle" /> <label for="optionShuffle"> Shuffle</label>
- </div>
- <div id="repeat_div">
- <input type="checkbox" id="optionRepeat" name="optionRepeat" /> <label for="optionRepeat"> Repeat</label>
- </div>
- <div id="listBlack">
- <h2>Black List</h2>
- <p>Do not add music with these words:</p>
- <a href="#" id="listBlackAdd">add</a><br />
- </div>
- <div id="listWhite">
- <h2>White List</h2>
- <p>Always add music with these words:</p>
- <a href="#" id="listWhiteAdd">add</a><br />
- </div>
- <div id="listSites">
- <h2>Site List</h2>
- <p>Run TumTaster on these sites:</p>
- <a href="#" id="listSitesAdd">add</a><br />
- </div>
- <br />
- <input id="save_btn" type="button" value="Save" />
- <input id="reset_btn" type="button" value="Restore default" />
- <div id="version_div"> </div>
- </div>
- </body>
-</html>
\ No newline at end of file
diff --git a/data/options.js b/data/options.js
deleted file mode 100644
index 7b75a51..0000000
--- a/data/options.js
+++ /dev/null
@@ -1,144 +0,0 @@
-document.addEventListener("DOMContentLoaded", function () {
- var save_btn = document.getElementById("save_btn");
- var reset_btn = document.getElementById("reset_btn");
- var listWhiteAdd = document.getElementById("listWhiteAdd");
- var listBlackAdd = document.getElementById("listBlackAdd");
- var listSitesAdd = document.getElementById("listSitesAdd");
-
- save_btn.addEventListener("click", saveOptions);
- reset_btn.addEventListener("click", function() { if (confirm("Are you sure you want to restore defaults?")) {eraseOptions()} });
-
- listWhiteAdd.addEventListener("click", function(e) {
- addInput("White");
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- listBlackAdd.addEventListener("click", function(e) {
- addInput("Black");
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- listSitesAdd.addEventListener("click", function(e) {
- addInput("Sites");
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- loadOptions();
-});
-
-function loadOptions() {
- var settings = localStorage['settings'];
-
- if (settings == undefined) {
- settings = defaultSettings;
- } else {
- settings = JSON.parse(settings);
- }
-
- var cbShuffle = document.getElementById("optionShuffle");
- cbShuffle.checked = settings['shuffle'];
-
- var cbRepeat = document.getElementById("optionRepeat");
- cbRepeat.checked = settings['repeat'];
-
- for (var itemBlack in settings['listBlack']) {
- addInput("Black", settings['listBlack'][itemBlack]);
- }
-
- for (var itemWhite in settings['listWhite']) {
- addInput("White", settings['listWhite'][itemWhite]);
- }
-
- for (var itemSites in settings['listSites']) {
- addInput("Sites", settings['listSites'][itemSites]);
- }
-
- addInput("Black"); //prepare a blank input box.
- addInput("White"); //prepare a blank input box.
- addInput("Sites"); //prepare a blank input box.
-
- var version_div = document.getElementById('version_div');
- version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
-
- if (typeof opera != 'undefined') {
- var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Opera™";
- }
-
- if (typeof chrome != 'undefined') {
- var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Chrome™";
- }
-
- if (typeof safari != 'undefined') {
- var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Safari™";
- }
-}
-
-function addInput(whichList, itemValue) {
- if (itemValue == undefined) {
- itemValue = "";
- }
-
- var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
- var listDiv = document.getElementById('list'+whichList);
- var listAdd = document.getElementById('list'+whichList+'Add');
-
- garbageInput = document.createElement('input');
- garbageInput.value = itemValue;
- garbageInput.name = 'option'+whichList;
- garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
- garbageAdd = document.createElement('a');
- garbageAdd.href = "#";
- garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
- garbageAdd.innerHTML = '<img src="'+PNGremove+'" /> ';
- garbageLinebreak = document.createElement('br');
- listDiv.insertBefore(garbageAdd,listAdd);
- listDiv.insertBefore(garbageInput,listAdd);
- listDiv.insertBefore(garbageLinebreak,listAdd);
-}
-
-function removeInput(garbageWhich) {
- var garbageInput = document.getElementById(garbageWhich);
- garbageInput.parentNode.removeChild(garbageInput.previousSibling);
- garbageInput.parentNode.removeChild(garbageInput.nextSibling);
- garbageInput.parentNode.removeChild(garbageInput);
-}
-
-function saveOptions() {
- var settings = {};
-
- var cbShuffle = document.getElementById('optionShuffle');
- settings['shuffle'] = cbShuffle.checked;
-
- var cbRepeat = document.getElementById('optionRepeat');
- settings['repeat'] = cbRepeat.checked;
-
- settings['listWhite'] = [];
- settings['listBlack'] = [];
- settings['listSites'] = [];
-
- var garbages = document.getElementsByTagName('input');
- for (var i = 0; i< garbages.length; i++) {
- if (garbages[i].value != "") {
- if (garbages[i].name.substring(0,11) == "optionWhite") {
- settings['listWhite'].push(garbages[i].value);
- } else if (garbages[i].name.substring(0,11) == "optionBlack") {
- settings['listBlack'].push(garbages[i].value);
- } else if (garbages[i].name.substring(0,11) == "optionSites") {
- settings['listSites'].push(garbages[i].value);
- }
- }
- }
- localStorage['settings'] = JSON.stringify(settings);
- location.reload();
-}
-
-function eraseOptions() {
- localStorage.removeItem('settings');
- location.reload();
-}
diff --git a/data/popup.html b/data/popup.html
deleted file mode 100644
index ef34cca..0000000
--- a/data/popup.html
+++ /dev/null
@@ -1,195 +0,0 @@
-<html>
-<head>
-<style type="text/css">
- html{
- color:black;
- font-family:arial,helvetica,sans-serif;
- margin:0;
- padding:0;
- background-color:#2C4762;
- background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
- background-repeat:repeat-x;
- min-width:400px;
- }
- h1{
- color:black;
- }
- a{
- color:white;
- text-decoration:none;
- }
- ol{
- background-attachment: scroll;
- background-clip: border-box;
- background-color: #2C4762;
- background-image: none;
- background-origin: padding-box;
- border-bottom-left-radius: 15px;
- border-bottom-right-radius: 15px;
- border-top-left-radius: 15px;
- border-top-right-radius: 15px;
- display: block;
- list-style-type:none;
- margin-bottom: 0px;
- margin-left: 0px;
- margin-right: 0px;
- margin-top: 0px;
- outline-color: #444;
- outline-style: none;
- outline-width: 0px;
- padding-bottom: 20px;
- padding-left: 20px;
- padding-right: 20px;
- padding-top: 20px;
- }
- li a{
- color:#444;
- }
- li{
- background-color: white;
- border-bottom-color: #BBB;
- border-bottom-left-radius: 10px;
- border-bottom-right-radius: 10px;
- border-bottom-style: solid;
- border-bottom-width: 2px;
- border-top-left-radius: 10px;
- border-top-right-radius: 10px;
- display: list-item;
- margin-bottom: 10px;
- margin-left: 0px;
- margin-right: 0px;
- margin-top: 0px;
- outline-color: #444;
- outline-style: none;
- outline-width: 0px;
- padding-bottom: 15px;
- padding-left: 20px;
- padding-right: 20px;
- padding-top: 15px;
- position: relative;
- word-wrap: break-word;
- }
- #nowplayingdiv {
- background-attachment: scroll;
- background-clip: border-box;
- background-color: #BBC552;
- background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
- background-origin: padding-box;
- border-bottom-left-radius: 3px;
- border-bottom-right-radius: 3px;
- border-top-left-radius: 3px;
- border-top-right-radius: 3px;
- color: #C4CDD6;
- display: block;
- font-family: 'Lucida Grande', Verdana, sans-serif;
- font-size: 13px;
- font-style: normal;
- font-variant: normal;
- font-weight: normal;
- line-height: normal;
- outline-color: #C4CDD6;
- outline-style: none;
- outline-width: 0px;
- padding-bottom: 9px;
- padding-left: 10px;
- padding-right: 10px;
- padding-top: 8px;
- position: relative;
- clear: left;
- }
- #nowplayingdiv span{
- color: #3B440F;
- cursor: auto;
- display: inline;
- height: 0px;
- outline-color: #3B440F;
- outline-style: none;
- outline-width: 0px;
- text-decoration: none;
- width: 0px;
- }
- #heading {
- width:100%;
- height:64px;
- }
- #heading h1{
- color: white;
- float: left;
- line-height:32px;
- vertical-align:absmiddle;
- margin-left:10px;
- }
- div#statistics{
- position:absolute;
- bottom:0%;
- }
- #controls{
- text-align:center;
- }
- #statusbar{
- position:relative;
- height:12px;
- background-color:#CDD568;
- border:2px solid #eaf839;
- border-radius:2px;
- -moz-border-radius:2px;
- -webkit-border-radius:2px;
- overflow:hidden;
- margin-top:4px;
- }
-
- .remove{
- position:absolute;
- right:8px;
- top:8px;
- }
-
- .position, .position2, .loading{
- position:absolute;
- left:0px;
- bottom:0px;
- height:12px;
- }
-
- .position{
- background-color: #3B440F;
- border-right:2px solid #3B440F;
- border-radius:2px;
- -moz-border-radius:2px;
- -webkit-border-radius:2px;
- width:20px;
- }
-
- .position2{
- background-color:#eaf839;
- }
-
- .loading {
- background-color:#BBC552;
- }
-</style>
-<script src="popup.js" type="text/javascript"></script>
-</head>
-<body>
-<div id="heading"><img src="Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
-<div id="statistics"><span> </span></div>
-<div id="nowplayingdiv"><span id="nowplaying"> </span>
-<div id="statusbar">
-<div id="loading" class="loading"> </div>
-<div id="position2" class="position2"> </div>
-<div id="position" class="position"> </div>
-</div>
-</div>
-
-<p id="controls">
-<a id="stop" href="#">■</a>
-<a id="pause" href="#">❙ ❙</a>
-<a id="play" href="#">▶</a>
-<a id="next" href="#">▶▶</a>
-<a id="random" href="#">Random</a></p>
-
-<ol id="playlist" class="playlist">
-</ol>
-
-</body>
-</html>
\ No newline at end of file
diff --git a/data/soundmanager2.js b/data/soundmanager2.js
deleted file mode 100644
index dcf7402..0000000
--- a/data/soundmanager2.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/** @license
- *
- * SoundManager 2: JavaScript Sound for the Web
- * ----------------------------------------------
- * http://schillmania.com/projects/soundmanager2/
- *
- * Copyright (c) 2007, Scott Schiller. All rights reserved.
- * Code provided under the BSD License:
- * http://schillmania.com/projects/soundmanager2/license.txt
- *
- * V2.97a.20131201
- */
-(function(g,k){function U(U,ka){function V(b){return c.preferFlash&&v&&!c.ignoreFlash&&c.flash[b]!==k&&c.flash[b]}function q(b){return function(c){var d=this._s;return!d||!d._a?null:b.call(this,c)}}this.setupOptions={url:U||null,flashVersion:8,debugMode:!0,debugFlash:!1,useConsole:!0,consoleOnly:!0,waitForWindowLoad:!1,bgColor:"#ffffff",useHighPerformance:!1,flashPollingInterval:null,html5PollingInterval:null,flashLoadTimeout:1E3,wmode:null,allowScriptAccess:"always",useFlashBlock:!1,useHTML5Audio:!0,
-html5Test:/^(probably|maybe)$/i,preferFlash:!1,noSWFCache:!1,idPrefix:"sound"};this.defaultOptions={autoLoad:!1,autoPlay:!1,from:null,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onposition:null,onstop:null,onfailure:null,onfinish:null,multiShot:!0,multiShotEvents:!1,position:null,pan:0,stream:!0,to:null,type:null,usePolicyFile:!1,volume:100};this.flash9Options={isMovieStar:null,usePeakData:!1,useWaveformData:!1,useEQData:!1,onbufferchange:null,
-ondataerror:null};this.movieStarOptions={bufferTime:3,serverURL:null,onconnect:null,duration:null};this.audioFormats={mp3:{type:['audio/mpeg; codecs\x3d"mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:!0},mp4:{related:["aac","m4a","m4b"],type:['audio/mp4; codecs\x3d"mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:!1},ogg:{type:["audio/ogg; codecs\x3dvorbis"],required:!1},opus:{type:["audio/ogg; codecs\x3dopus","audio/opus"],required:!1},
-wav:{type:['audio/wav; codecs\x3d"1"',"audio/wav","audio/wave","audio/x-wav"],required:!1}};this.movieID="sm2-container";this.id=ka||"sm2movie";this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.versionNumber="V2.97a.20131201";this.altURL=this.movieURL=this.version=null;this.enabled=this.swfLoaded=!1;this.oMC=null;this.sounds={};this.soundIDs=[];this.didFlashBlock=this.muted=!1;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.features=
-{buffering:!1,peakData:!1,waveformData:!1,eqData:!1,movieStar:!1};this.sandbox={};this.html5={usingFlash:null};this.flash={};this.ignoreFlash=this.html5Only=!1;var Ja,c=this,Ka=null,l=null,W,s=navigator.userAgent,La=g.location.href.toString(),n=document,la,Ma,ma,m,x=[],K=!1,L=!1,p=!1,y=!1,na=!1,M,w,oa,X,pa,D,E,F,Na,qa,ra,Y,sa,Z,ta,G,ua,N,va,$,H,Oa,wa,Pa,xa,Qa,O=null,ya=null,P,za,I,aa,ba,r,Q=!1,Aa=!1,Ra,Sa,Ta,ca=0,R=null,da,Ua=[],S,u=null,Va,ea,T,z,fa,Ba,Wa,t,fb=Array.prototype.slice,A=!1,Ca,v,Da,
-Xa,B,ga,Ya=0,ha=s.match(/(ipad|iphone|ipod)/i),Za=s.match(/android/i),C=s.match(/msie/i),gb=s.match(/webkit/i),ia=s.match(/safari/i)&&!s.match(/chrome/i),Ea=s.match(/opera/i),Fa=s.match(/(mobile|pre\/|xoom)/i)||ha||Za,$a=!La.match(/usehtml5audio/i)&&!La.match(/sm2\-ignorebadua/i)&&ia&&!s.match(/silk/i)&&s.match(/OS X 10_6_([3-7])/i),Ga=n.hasFocus!==k?n.hasFocus():null,ja=ia&&(n.hasFocus===k||!n.hasFocus()),ab=!ja,bb=/(mp3|mp4|mpa|m4a|m4b)/i,Ha=n.location?n.location.protocol.match(/http/i):null,cb=
-!Ha?"http://":"",db=/^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|m4b|mp4v|3gp|3g2)\s*(?:$|;)/i,eb="mpeg4 aac flv mov mp4 m4v f4v m4a m4b mp4v 3gp 3g2".split(" "),hb=RegExp("\\.("+eb.join("|")+")(\\?.*)?$","i");this.mimePattern=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.useAltURL=!Ha;var Ia;try{Ia=Audio!==k&&(Ea&&opera!==k&&10>opera.version()?new Audio(null):new Audio).canPlayType!==k}catch(ib){Ia=!1}this.hasHTML5=Ia;this.setup=function(b){var e=!c.url;b!==k&&p&&u&&c.ok();oa(b);b&&
-(e&&(N&&b.url!==k)&&c.beginDelayedInit(),!N&&(b.url!==k&&"complete"===n.readyState)&&setTimeout(G,1));return c};this.supported=this.ok=function(){return u?p&&!y:c.useHTML5Audio&&c.hasHTML5};this.getMovie=function(b){return W(b)||n[b]||g[b]};this.createSound=function(b,e){function d(){a=aa(a);c.sounds[a.id]=new Ja(a);c.soundIDs.push(a.id);return c.sounds[a.id]}var a,f=null;if(!p||!c.ok())return!1;e!==k&&(b={id:b,url:e});a=w(b);a.url=da(a.url);void 0===a.id&&(a.id=c.setupOptions.idPrefix+Ya++);if(r(a.id,
-!0))return c.sounds[a.id];if(ea(a))f=d(),f._setup_html5(a);else{if(c.html5Only||c.html5.usingFlash&&a.url&&a.url.match(/data\:/i))return d();8<m&&null===a.isMovieStar&&(a.isMovieStar=!(!a.serverURL&&!(a.type&&a.type.match(db)||a.url&&a.url.match(hb))));a=ba(a,void 0);f=d();8===m?l._createSound(a.id,a.loops||1,a.usePolicyFile):(l._createSound(a.id,a.url,a.usePeakData,a.useWaveformData,a.useEQData,a.isMovieStar,a.isMovieStar?a.bufferTime:!1,a.loops||1,a.serverURL,a.duration||null,a.autoPlay,!0,a.autoLoad,
-a.usePolicyFile),a.serverURL||(f.connected=!0,a.onconnect&&a.onconnect.apply(f)));!a.serverURL&&(a.autoLoad||a.autoPlay)&&f.load(a)}!a.serverURL&&a.autoPlay&&f.play();return f};this.destroySound=function(b,e){if(!r(b))return!1;var d=c.sounds[b],a;d._iO={};d.stop();d.unload();for(a=0;a<c.soundIDs.length;a++)if(c.soundIDs[a]===b){c.soundIDs.splice(a,1);break}e||d.destruct(!0);delete c.sounds[b];return!0};this.load=function(b,e){return!r(b)?!1:c.sounds[b].load(e)};this.unload=function(b){return!r(b)?
-!1:c.sounds[b].unload()};this.onposition=this.onPosition=function(b,e,d,a){return!r(b)?!1:c.sounds[b].onposition(e,d,a)};this.clearOnPosition=function(b,e,d){return!r(b)?!1:c.sounds[b].clearOnPosition(e,d)};this.start=this.play=function(b,e){var d=null,a=e&&!(e instanceof Object);if(!p||!c.ok())return!1;if(r(b,a))a&&(e={url:e});else{if(!a)return!1;a&&(e={url:e});e&&e.url&&(e.id=b,d=c.createSound(e).play())}null===d&&(d=c.sounds[b].play(e));return d};this.setPosition=function(b,e){return!r(b)?!1:c.sounds[b].setPosition(e)};
-this.stop=function(b){return!r(b)?!1:c.sounds[b].stop()};this.stopAll=function(){for(var b in c.sounds)c.sounds.hasOwnProperty(b)&&c.sounds[b].stop()};this.pause=function(b){return!r(b)?!1:c.sounds[b].pause()};this.pauseAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].pause()};this.resume=function(b){return!r(b)?!1:c.sounds[b].resume()};this.resumeAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].resume()};this.togglePause=function(b){return!r(b)?
-!1:c.sounds[b].togglePause()};this.setPan=function(b,e){return!r(b)?!1:c.sounds[b].setPan(e)};this.setVolume=function(b,e){return!r(b)?!1:c.sounds[b].setVolume(e)};this.mute=function(b){var e=0;b instanceof String&&(b=null);if(b)return!r(b)?!1:c.sounds[b].mute();for(e=c.soundIDs.length-1;0<=e;e--)c.sounds[c.soundIDs[e]].mute();return c.muted=!0};this.muteAll=function(){c.mute()};this.unmute=function(b){b instanceof String&&(b=null);if(b)return!r(b)?!1:c.sounds[b].unmute();for(b=c.soundIDs.length-
-1;0<=b;b--)c.sounds[c.soundIDs[b]].unmute();c.muted=!1;return!0};this.unmuteAll=function(){c.unmute()};this.toggleMute=function(b){return!r(b)?!1:c.sounds[b].toggleMute()};this.getMemoryUse=function(){var b=0;l&&8!==m&&(b=parseInt(l._getMemoryUse(),10));return b};this.disable=function(b){var e;b===k&&(b=!1);if(y)return!1;y=!0;for(e=c.soundIDs.length-1;0<=e;e--)Pa(c.sounds[c.soundIDs[e]]);M(b);t.remove(g,"load",E);return!0};this.canPlayMIME=function(b){var e;c.hasHTML5&&(e=T({type:b}));!e&&u&&(e=b&&
-c.ok()?!!(8<m&&b.match(db)||b.match(c.mimePattern)):null);return e};this.canPlayURL=function(b){var e;c.hasHTML5&&(e=T({url:b}));!e&&u&&(e=b&&c.ok()?!!b.match(c.filePattern):null);return e};this.canPlayLink=function(b){return b.type!==k&&b.type&&c.canPlayMIME(b.type)?!0:c.canPlayURL(b.href)};this.getSoundById=function(b,e){return!b?null:c.sounds[b]};this.onready=function(b,c){if("function"===typeof b)c||(c=g),pa("onready",b,c),D();else throw P("needFunction","onready");return!0};this.ontimeout=function(b,
-c){if("function"===typeof b)c||(c=g),pa("ontimeout",b,c),D({type:"ontimeout"});else throw P("needFunction","ontimeout");return!0};this._wD=this._writeDebug=function(b,c){return!0};this._debug=function(){};this.reboot=function(b,e){var d,a,f;for(d=c.soundIDs.length-1;0<=d;d--)c.sounds[c.soundIDs[d]].destruct();if(l)try{C&&(ya=l.innerHTML),O=l.parentNode.removeChild(l)}catch(k){}ya=O=u=l=null;c.enabled=N=p=Q=Aa=K=L=y=A=c.swfLoaded=!1;c.soundIDs=[];c.sounds={};Ya=0;if(b)x=[];else for(d in x)if(x.hasOwnProperty(d)){a=
-0;for(f=x[d].length;a<f;a++)x[d][a].fired=!1}c.html5={usingFlash:null};c.flash={};c.html5Only=!1;c.ignoreFlash=!1;g.setTimeout(function(){ta();e||c.beginDelayedInit()},20);return c};this.reset=function(){return c.reboot(!0,!0)};this.getMoviePercent=function(){return l&&"PercentLoaded"in l?l.PercentLoaded():null};this.beginDelayedInit=function(){na=!0;G();setTimeout(function(){if(Aa)return!1;$();Z();return Aa=!0},20);F()};this.destruct=function(){c.disable(!0)};Ja=function(b){var e,d,a=this,f,h,J,
-g,n,q,s=!1,p=[],u=0,x,y,v=null,z;d=e=null;this.sID=this.id=b.id;this.url=b.url;this._iO=this.instanceOptions=this.options=w(b);this.pan=this.options.pan;this.volume=this.options.volume;this.isHTML5=!1;this._a=null;z=this.url?!1:!0;this.id3={};this._debug=function(){};this.load=function(b){var e=null,d;b!==k?a._iO=w(b,a.options):(b=a.options,a._iO=b,v&&v!==a.url&&(a._iO.url=a.url,a.url=null));a._iO.url||(a._iO.url=a.url);a._iO.url=da(a._iO.url);d=a.instanceOptions=a._iO;if(!d.url&&!a.url)return a;
-if(d.url===a.url&&0!==a.readyState&&2!==a.readyState)return 3===a.readyState&&d.onload&&ga(a,function(){d.onload.apply(a,[!!a.duration])}),a;a.loaded=!1;a.readyState=1;a.playState=0;a.id3={};if(ea(d))e=a._setup_html5(d),e._called_load||(a._html5_canplay=!1,a.url!==d.url&&(a._a.src=d.url,a.setPosition(0)),a._a.autobuffer="auto",a._a.preload="auto",a._a._called_load=!0);else{if(c.html5Only||a._iO.url&&a._iO.url.match(/data\:/i))return a;try{a.isHTML5=!1,a._iO=ba(aa(d)),d=a._iO,8===m?l._load(a.id,d.url,
-d.stream,d.autoPlay,d.usePolicyFile):l._load(a.id,d.url,!!d.stream,!!d.autoPlay,d.loops||1,!!d.autoLoad,d.usePolicyFile)}catch(f){H({type:"SMSOUND_LOAD_JS_EXCEPTION",fatal:!0})}}a.url=d.url;return a};this.unload=function(){0!==a.readyState&&(a.isHTML5?(g(),a._a&&(a._a.pause(),v=fa(a._a))):8===m?l._unload(a.id,"about:blank"):l._unload(a.id),f());return a};this.destruct=function(b){a.isHTML5?(g(),a._a&&(a._a.pause(),fa(a._a),A||J(),a._a._s=null,a._a=null)):(a._iO.onfailure=null,l._destroySound(a.id));
-b||c.destroySound(a.id,!0)};this.start=this.play=function(b,e){var d,f,h,g,J;f=!0;f=null;e=e===k?!0:e;b||(b={});a.url&&(a._iO.url=a.url);a._iO=w(a._iO,a.options);a._iO=w(b,a._iO);a._iO.url=da(a._iO.url);a.instanceOptions=a._iO;if(!a.isHTML5&&a._iO.serverURL&&!a.connected)return a.getAutoPlay()||a.setAutoPlay(!0),a;ea(a._iO)&&(a._setup_html5(a._iO),n());1===a.playState&&!a.paused&&(d=a._iO.multiShot,d||(a.isHTML5&&a.setPosition(a._iO.position),f=a));if(null!==f)return f;b.url&&b.url!==a.url&&(!a.readyState&&
-!a.isHTML5&&8===m&&z?z=!1:a.load(a._iO));a.loaded||(0===a.readyState?(!a.isHTML5&&!c.html5Only?(a._iO.autoPlay=!0,a.load(a._iO)):a.isHTML5?a.load(a._iO):f=a,a.instanceOptions=a._iO):2===a.readyState&&(f=a));if(null!==f)return f;!a.isHTML5&&(9===m&&0<a.position&&a.position===a.duration)&&(b.position=0);if(a.paused&&0<=a.position&&(!a._iO.serverURL||0<a.position))a.resume();else{a._iO=w(b,a._iO);if(null!==a._iO.from&&null!==a._iO.to&&0===a.instanceCount&&0===a.playState&&!a._iO.serverURL){d=function(){a._iO=
-w(b,a._iO);a.play(a._iO)};if(a.isHTML5&&!a._html5_canplay)a.load({_oncanplay:d}),f=!1;else if(!a.isHTML5&&!a.loaded&&(!a.readyState||2!==a.readyState))a.load({onload:d}),f=!1;if(null!==f)return f;a._iO=y()}(!a.instanceCount||a._iO.multiShotEvents||a.isHTML5&&a._iO.multiShot&&!A||!a.isHTML5&&8<m&&!a.getAutoPlay())&&a.instanceCount++;a._iO.onposition&&0===a.playState&&q(a);a.playState=1;a.paused=!1;a.position=a._iO.position!==k&&!isNaN(a._iO.position)?a._iO.position:0;a.isHTML5||(a._iO=ba(aa(a._iO)));
-a._iO.onplay&&e&&(a._iO.onplay.apply(a),s=!0);a.setVolume(a._iO.volume,!0);a.setPan(a._iO.pan,!0);a.isHTML5?2>a.instanceCount?(n(),f=a._setup_html5(),a.setPosition(a._iO.position),f.play()):(h=new Audio(a._iO.url),g=function(){t.remove(h,"ended",g);a._onfinish(a);fa(h);h=null},J=function(){t.remove(h,"canplay",J);try{h.currentTime=a._iO.position/1E3}catch(b){}h.play()},t.add(h,"ended",g),void 0!==a._iO.volume&&(h.volume=Math.max(0,Math.min(1,a._iO.volume/100))),a.muted&&(h.muted=!0),a._iO.position?
-t.add(h,"canplay",J):h.play()):(f=l._start(a.id,a._iO.loops||1,9===m?a.position:a.position/1E3,a._iO.multiShot||!1),9===m&&!f&&a._iO.onplayerror&&a._iO.onplayerror.apply(a))}return a};this.stop=function(b){var c=a._iO;1===a.playState&&(a._onbufferchange(0),a._resetOnPosition(0),a.paused=!1,a.isHTML5||(a.playState=0),x(),c.to&&a.clearOnPosition(c.to),a.isHTML5?a._a&&(b=a.position,a.setPosition(0),a.position=b,a._a.pause(),a.playState=0,a._onTimer(),g()):(l._stop(a.id,b),c.serverURL&&a.unload()),a.instanceCount=
-0,a._iO={},c.onstop&&c.onstop.apply(a));return a};this.setAutoPlay=function(b){a._iO.autoPlay=b;a.isHTML5||(l._setAutoPlay(a.id,b),b&&!a.instanceCount&&1===a.readyState&&a.instanceCount++)};this.getAutoPlay=function(){return a._iO.autoPlay};this.setPosition=function(b){b===k&&(b=0);var c=a.isHTML5?Math.max(b,0):Math.min(a.duration||a._iO.duration,Math.max(b,0));a.position=c;b=a.position/1E3;a._resetOnPosition(a.position);a._iO.position=c;if(a.isHTML5){if(a._a){if(a._html5_canplay){if(a._a.currentTime!==
-b)try{a._a.currentTime=b,(0===a.playState||a.paused)&&a._a.pause()}catch(e){}}else if(b)return a;a.paused&&a._onTimer(!0)}}else b=9===m?a.position:b,a.readyState&&2!==a.readyState&&l._setPosition(a.id,b,a.paused||!a.playState,a._iO.multiShot);return a};this.pause=function(b){if(a.paused||0===a.playState&&1!==a.readyState)return a;a.paused=!0;a.isHTML5?(a._setup_html5().pause(),g()):(b||b===k)&&l._pause(a.id,a._iO.multiShot);a._iO.onpause&&a._iO.onpause.apply(a);return a};this.resume=function(){var b=
-a._iO;if(!a.paused)return a;a.paused=!1;a.playState=1;a.isHTML5?(a._setup_html5().play(),n()):(b.isMovieStar&&!b.serverURL&&a.setPosition(a.position),l._pause(a.id,b.multiShot));!s&&b.onplay?(b.onplay.apply(a),s=!0):b.onresume&&b.onresume.apply(a);return a};this.togglePause=function(){if(0===a.playState)return a.play({position:9===m&&!a.isHTML5?a.position:a.position/1E3}),a;a.paused?a.resume():a.pause();return a};this.setPan=function(b,c){b===k&&(b=0);c===k&&(c=!1);a.isHTML5||l._setPan(a.id,b);a._iO.pan=
-b;c||(a.pan=b,a.options.pan=b);return a};this.setVolume=function(b,e){b===k&&(b=100);e===k&&(e=!1);a.isHTML5?a._a&&(c.muted&&!a.muted&&(a.muted=!0,a._a.muted=!0),a._a.volume=Math.max(0,Math.min(1,b/100))):l._setVolume(a.id,c.muted&&!a.muted||a.muted?0:b);a._iO.volume=b;e||(a.volume=b,a.options.volume=b);return a};this.mute=function(){a.muted=!0;a.isHTML5?a._a&&(a._a.muted=!0):l._setVolume(a.id,0);return a};this.unmute=function(){a.muted=!1;var b=a._iO.volume!==k;a.isHTML5?a._a&&(a._a.muted=!1):l._setVolume(a.id,
-b?a._iO.volume:a.options.volume);return a};this.toggleMute=function(){return a.muted?a.unmute():a.mute()};this.onposition=this.onPosition=function(b,c,e){p.push({position:parseInt(b,10),method:c,scope:e!==k?e:a,fired:!1});return a};this.clearOnPosition=function(a,b){var c;a=parseInt(a,10);if(isNaN(a))return!1;for(c=0;c<p.length;c++)if(a===p[c].position&&(!b||b===p[c].method))p[c].fired&&u--,p.splice(c,1)};this._processOnPosition=function(){var b,c;b=p.length;if(!b||!a.playState||u>=b)return!1;for(b-=
-1;0<=b;b--)c=p[b],!c.fired&&a.position>=c.position&&(c.fired=!0,u++,c.method.apply(c.scope,[c.position]));return!0};this._resetOnPosition=function(a){var b,c;b=p.length;if(!b)return!1;for(b-=1;0<=b;b--)c=p[b],c.fired&&a<=c.position&&(c.fired=!1,u--);return!0};y=function(){var b=a._iO,c=b.from,e=b.to,d,f;f=function(){a.clearOnPosition(e,f);a.stop()};d=function(){if(null!==e&&!isNaN(e))a.onPosition(e,f)};null!==c&&!isNaN(c)&&(b.position=c,b.multiShot=!1,d());return b};q=function(){var b,c=a._iO.onposition;
-if(c)for(b in c)if(c.hasOwnProperty(b))a.onPosition(parseInt(b,10),c[b])};x=function(){var b,c=a._iO.onposition;if(c)for(b in c)c.hasOwnProperty(b)&&a.clearOnPosition(parseInt(b,10))};n=function(){a.isHTML5&&Ra(a)};g=function(){a.isHTML5&&Sa(a)};f=function(b){b||(p=[],u=0);s=!1;a._hasTimer=null;a._a=null;a._html5_canplay=!1;a.bytesLoaded=null;a.bytesTotal=null;a.duration=a._iO&&a._iO.duration?a._iO.duration:null;a.durationEstimate=null;a.buffered=[];a.eqData=[];a.eqData.left=[];a.eqData.right=[];
-a.failures=0;a.isBuffering=!1;a.instanceOptions={};a.instanceCount=0;a.loaded=!1;a.metadata={};a.readyState=0;a.muted=!1;a.paused=!1;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.playState=0;a.position=null;a.id3={}};f();this._onTimer=function(b){var c,f=!1,h={};if(a._hasTimer||b){if(a._a&&(b||(0<a.playState||1===a.readyState)&&!a.paused))c=a._get_html5_duration(),c!==e&&(e=c,a.duration=c,f=!0),a.durationEstimate=a.duration,c=1E3*a._a.currentTime||0,c!==d&&(d=c,f=!0),(f||b)&&a._whileplaying(c,
-h,h,h,h);return f}};this._get_html5_duration=function(){var b=a._iO;return(b=a._a&&a._a.duration?1E3*a._a.duration:b&&b.duration?b.duration:null)&&!isNaN(b)&&Infinity!==b?b:null};this._apply_loop=function(a,b){a.loop=1<b?"loop":""};this._setup_html5=function(b){b=w(a._iO,b);var c=A?Ka:a._a,e=decodeURI(b.url),d;A?e===decodeURI(Ca)&&(d=!0):e===decodeURI(v)&&(d=!0);if(c){if(c._s)if(A)c._s&&(c._s.playState&&!d)&&c._s.stop();else if(!A&&e===decodeURI(v))return a._apply_loop(c,b.loops),c;d||(v&&f(!1),c.src=
-b.url,Ca=v=a.url=b.url,c._called_load=!1)}else b.autoLoad||b.autoPlay?(a._a=new Audio(b.url),a._a.load()):a._a=Ea&&10>opera.version()?new Audio(null):new Audio,c=a._a,c._called_load=!1,A&&(Ka=c);a.isHTML5=!0;a._a=c;c._s=a;h();a._apply_loop(c,b.loops);b.autoLoad||b.autoPlay?a.load():(c.autobuffer=!1,c.preload="auto");return c};h=function(){if(a._a._added_events)return!1;var b;a._a._added_events=!0;for(b in B)B.hasOwnProperty(b)&&a._a&&a._a.addEventListener(b,B[b],!1);return!0};J=function(){var b;a._a._added_events=
-!1;for(b in B)B.hasOwnProperty(b)&&a._a&&a._a.removeEventListener(b,B[b],!1)};this._onload=function(b){var c=!!b||!a.isHTML5&&8===m&&a.duration;a.loaded=c;a.readyState=c?3:2;a._onbufferchange(0);a._iO.onload&&ga(a,function(){a._iO.onload.apply(a,[c])});return!0};this._onbufferchange=function(b){if(0===a.playState||b&&a.isBuffering||!b&&!a.isBuffering)return!1;a.isBuffering=1===b;a._iO.onbufferchange&&a._iO.onbufferchange.apply(a);return!0};this._onsuspend=function(){a._iO.onsuspend&&a._iO.onsuspend.apply(a);
-return!0};this._onfailure=function(b,c,e){a.failures++;if(a._iO.onfailure&&1===a.failures)a._iO.onfailure(a,b,c,e)};this._onfinish=function(){var b=a._iO.onfinish;a._onbufferchange(0);a._resetOnPosition(0);a.instanceCount&&(a.instanceCount--,a.instanceCount||(x(),a.playState=0,a.paused=!1,a.instanceCount=0,a.instanceOptions={},a._iO={},g(),a.isHTML5&&(a.position=0)),(!a.instanceCount||a._iO.multiShotEvents)&&b&&ga(a,function(){b.apply(a)}))};this._whileloading=function(b,c,e,d){var f=a._iO;a.bytesLoaded=
-b;a.bytesTotal=c;a.duration=Math.floor(e);a.bufferLength=d;a.durationEstimate=!a.isHTML5&&!f.isMovieStar?f.duration?a.duration>f.duration?a.duration:f.duration:parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10):a.duration;a.isHTML5||(a.buffered=[{start:0,end:a.duration}]);(3!==a.readyState||a.isHTML5)&&f.whileloading&&f.whileloading.apply(a)};this._whileplaying=function(b,c,e,d,f){var h=a._iO;if(isNaN(b)||null===b)return!1;a.position=Math.max(0,b);a._processOnPosition();!a.isHTML5&&8<m&&(h.usePeakData&&
-(c!==k&&c)&&(a.peakData={left:c.leftPeak,right:c.rightPeak}),h.useWaveformData&&(e!==k&&e)&&(a.waveformData={left:e.split(","),right:d.split(",")}),h.useEQData&&(f!==k&&f&&f.leftEQ)&&(b=f.leftEQ.split(","),a.eqData=b,a.eqData.left=b,f.rightEQ!==k&&f.rightEQ&&(a.eqData.right=f.rightEQ.split(","))));1===a.playState&&(!a.isHTML5&&(8===m&&!a.position&&a.isBuffering)&&a._onbufferchange(0),h.whileplaying&&h.whileplaying.apply(a));return!0};this._oncaptiondata=function(b){a.captiondata=b;a._iO.oncaptiondata&&
-a._iO.oncaptiondata.apply(a,[b])};this._onmetadata=function(b,c){var e={},d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.metadata=e;a._iO.onmetadata&&a._iO.onmetadata.apply(a)};this._onid3=function(b,c){var e=[],d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.id3=w(a.id3,e);a._iO.onid3&&a._iO.onid3.apply(a)};this._onconnect=function(b){b=1===b;if(a.connected=b)a.failures=0,r(a.id)&&(a.getAutoPlay()?a.play(k,a.getAutoPlay()):a._iO.autoLoad&&a.load()),a._iO.onconnect&&a._iO.onconnect.apply(a,[b])};this._ondataerror=
-function(b){0<a.playState&&a._iO.ondataerror&&a._iO.ondataerror.apply(a)}};va=function(){return n.body||n.getElementsByTagName("div")[0]};W=function(b){return n.getElementById(b)};w=function(b,e){var d=b||{},a,f;a=e===k?c.defaultOptions:e;for(f in a)a.hasOwnProperty(f)&&d[f]===k&&(d[f]="object"!==typeof a[f]||null===a[f]?a[f]:w(d[f],a[f]));return d};ga=function(b,c){!b.isHTML5&&8===m?g.setTimeout(c,0):c()};X={onready:1,ontimeout:1,defaultOptions:1,flash9Options:1,movieStarOptions:1};oa=function(b,
-e){var d,a=!0,f=e!==k,h=c.setupOptions;for(d in b)if(b.hasOwnProperty(d))if("object"!==typeof b[d]||null===b[d]||b[d]instanceof Array||b[d]instanceof RegExp)f&&X[e]!==k?c[e][d]=b[d]:h[d]!==k?(c.setupOptions[d]=b[d],c[d]=b[d]):X[d]===k?a=!1:c[d]instanceof Function?c[d].apply(c,b[d]instanceof Array?b[d]:[b[d]]):c[d]=b[d];else if(X[d]===k)a=!1;else return oa(b[d],d);return a};t=function(){function b(a){a=fb.call(a);var b=a.length;d?(a[1]="on"+a[1],3<b&&a.pop()):3===b&&a.push(!1);return a}function c(b,
-e){var k=b.shift(),g=[a[e]];if(d)k[g](b[0],b[1]);else k[g].apply(k,b)}var d=g.attachEvent,a={add:d?"attachEvent":"addEventListener",remove:d?"detachEvent":"removeEventListener"};return{add:function(){c(b(arguments),"add")},remove:function(){c(b(arguments),"remove")}}}();B={abort:q(function(){}),canplay:q(function(){var b=this._s,c;if(b._html5_canplay)return!0;b._html5_canplay=!0;b._onbufferchange(0);c=b._iO.position!==k&&!isNaN(b._iO.position)?b._iO.position/1E3:null;if(b.position&&this.currentTime!==
-c)try{this.currentTime=c}catch(d){}b._iO._oncanplay&&b._iO._oncanplay()}),canplaythrough:q(function(){var b=this._s;b.loaded||(b._onbufferchange(0),b._whileloading(b.bytesLoaded,b.bytesTotal,b._get_html5_duration()),b._onload(!0))}),ended:q(function(){this._s._onfinish()}),error:q(function(){this._s._onload(!1)}),loadeddata:q(function(){var b=this._s;!b._loaded&&!ia&&(b.duration=b._get_html5_duration())}),loadedmetadata:q(function(){}),loadstart:q(function(){this._s._onbufferchange(1)}),play:q(function(){this._s._onbufferchange(0)}),
-playing:q(function(){this._s._onbufferchange(0)}),progress:q(function(b){var c=this._s,d,a,f=0,f=b.target.buffered;d=b.loaded||0;var h=b.total||1;c.buffered=[];if(f&&f.length){d=0;for(a=f.length;d<a;d++)c.buffered.push({start:1E3*f.start(d),end:1E3*f.end(d)});f=1E3*(f.end(0)-f.start(0));d=Math.min(1,f/(1E3*b.target.duration))}isNaN(d)||(c._onbufferchange(0),c._whileloading(d,h,c._get_html5_duration()),d&&(h&&d===h)&&B.canplaythrough.call(this,b))}),ratechange:q(function(){}),suspend:q(function(b){var c=
-this._s;B.progress.call(this,b);c._onsuspend()}),stalled:q(function(){}),timeupdate:q(function(){this._s._onTimer()}),waiting:q(function(){this._s._onbufferchange(1)})};ea=function(b){return!b||!b.type&&!b.url&&!b.serverURL?!1:b.serverURL||b.type&&V(b.type)?!1:b.type?T({type:b.type}):T({url:b.url})||c.html5Only||b.url.match(/data\:/i)};fa=function(b){var e;b&&(e=ia?"about:blank":c.html5.canPlayType("audio/wav")?"data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w\x3d\x3d":
-"about:blank",b.src=e,void 0!==b._called_unload&&(b._called_load=!1));A&&(Ca=null);return e};T=function(b){if(!c.useHTML5Audio||!c.hasHTML5)return!1;var e=b.url||null;b=b.type||null;var d=c.audioFormats,a;if(b&&c.html5[b]!==k)return c.html5[b]&&!V(b);if(!z){z=[];for(a in d)d.hasOwnProperty(a)&&(z.push(a),d[a].related&&(z=z.concat(d[a].related)));z=RegExp("\\.("+z.join("|")+")(\\?.*)?$","i")}a=e?e.toLowerCase().match(z):null;!a||!a.length?b&&(e=b.indexOf(";"),a=(-1!==e?b.substr(0,e):b).substr(6)):
-a=a[1];a&&c.html5[a]!==k?e=c.html5[a]&&!V(a):(b="audio/"+a,e=c.html5.canPlayType({type:b}),e=(c.html5[a]=e)&&c.html5[b]&&!V(b));return e};Wa=function(){function b(a){var b,d=b=!1;if(!e||"function"!==typeof e.canPlayType)return b;if(a instanceof Array){g=0;for(b=a.length;g<b;g++)if(c.html5[a[g]]||e.canPlayType(a[g]).match(c.html5Test))d=!0,c.html5[a[g]]=!0,c.flash[a[g]]=!!a[g].match(bb);b=d}else a=e&&"function"===typeof e.canPlayType?e.canPlayType(a):!1,b=!(!a||!a.match(c.html5Test));return b}if(!c.useHTML5Audio||
-!c.hasHTML5)return u=c.html5.usingFlash=!0,!1;var e=Audio!==k?Ea&&10>opera.version()?new Audio(null):new Audio:null,d,a,f={},h,g;h=c.audioFormats;for(d in h)if(h.hasOwnProperty(d)&&(a="audio/"+d,f[d]=b(h[d].type),f[a]=f[d],d.match(bb)?(c.flash[d]=!0,c.flash[a]=!0):(c.flash[d]=!1,c.flash[a]=!1),h[d]&&h[d].related))for(g=h[d].related.length-1;0<=g;g--)f["audio/"+h[d].related[g]]=f[d],c.html5[h[d].related[g]]=f[d],c.flash[h[d].related[g]]=f[d];f.canPlayType=e?b:null;c.html5=w(c.html5,f);c.html5.usingFlash=
-Va();u=c.html5.usingFlash;return!0};sa={};P=function(){};aa=function(b){8===m&&(1<b.loops&&b.stream)&&(b.stream=!1);return b};ba=function(b,c){if(b&&!b.usePolicyFile&&(b.onid3||b.usePeakData||b.useWaveformData||b.useEQData))b.usePolicyFile=!0;return b};la=function(){return!1};Pa=function(b){for(var c in b)b.hasOwnProperty(c)&&"function"===typeof b[c]&&(b[c]=la)};xa=function(b){b===k&&(b=!1);(y||b)&&c.disable(b)};Qa=function(b){var e=null;if(b)if(b.match(/\.swf(\?.*)?$/i)){if(e=b.substr(b.toLowerCase().lastIndexOf(".swf?")+
-4))return b}else b.lastIndexOf("/")!==b.length-1&&(b+="/");b=(b&&-1!==b.lastIndexOf("/")?b.substr(0,b.lastIndexOf("/")+1):"./")+c.movieURL;c.noSWFCache&&(b+="?ts\x3d"+(new Date).getTime());return b};ra=function(){m=parseInt(c.flashVersion,10);8!==m&&9!==m&&(c.flashVersion=m=8);var b=c.debugMode||c.debugFlash?"_debug.swf":".swf";c.useHTML5Audio&&(!c.html5Only&&c.audioFormats.mp4.required&&9>m)&&(c.flashVersion=m=9);c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===m?" (AS3/Flash 9)":
-" (AS2/Flash 8)");8<m?(c.defaultOptions=w(c.defaultOptions,c.flash9Options),c.features.buffering=!0,c.defaultOptions=w(c.defaultOptions,c.movieStarOptions),c.filePatterns.flash9=RegExp("\\.(mp3|"+eb.join("|")+")(\\?.*)?$","i"),c.features.movieStar=!0):c.features.movieStar=!1;c.filePattern=c.filePatterns[8!==m?"flash9":"flash8"];c.movieURL=(8===m?"soundmanager2.swf":"soundmanager2_flash9.swf").replace(".swf",b);c.features.peakData=c.features.waveformData=c.features.eqData=8<m};Oa=function(b,c){if(!l)return!1;
-l._setPolling(b,c)};wa=function(){};r=this.getSoundById;I=function(){var b=[];c.debugMode&&b.push("sm2_debug");c.debugFlash&&b.push("flash_debug");c.useHighPerformance&&b.push("high_performance");return b.join(" ")};za=function(){P("fbHandler");var b=c.getMoviePercent(),e={type:"FLASHBLOCK"};if(c.html5Only)return!1;c.ok()?c.oMC&&(c.oMC.className=[I(),"movieContainer","swf_loaded"+(c.didFlashBlock?" swf_unblocked":"")].join(" ")):(u&&(c.oMC.className=I()+" movieContainer "+(null===b?"swf_timedout":
-"swf_error")),c.didFlashBlock=!0,D({type:"ontimeout",ignoreInit:!0,error:e}),H(e))};pa=function(b,c,d){x[b]===k&&(x[b]=[]);x[b].push({method:c,scope:d||null,fired:!1})};D=function(b){b||(b={type:c.ok()?"onready":"ontimeout"});if(!p&&b&&!b.ignoreInit||"ontimeout"===b.type&&(c.ok()||y&&!b.ignoreInit))return!1;var e={success:b&&b.ignoreInit?c.ok():!y},d=b&&b.type?x[b.type]||[]:[],a=[],f,e=[e],h=u&&!c.ok();b.error&&(e[0].error=b.error);b=0;for(f=d.length;b<f;b++)!0!==d[b].fired&&a.push(d[b]);if(a.length){b=
-0;for(f=a.length;b<f;b++)a[b].scope?a[b].method.apply(a[b].scope,e):a[b].method.apply(this,e),h||(a[b].fired=!0)}return!0};E=function(){g.setTimeout(function(){c.useFlashBlock&&za();D();"function"===typeof c.onload&&c.onload.apply(g);c.waitForWindowLoad&&t.add(g,"load",E)},1)};Da=function(){if(v!==k)return v;var b=!1,c=navigator,d=c.plugins,a,f=g.ActiveXObject;if(d&&d.length)(c=c.mimeTypes)&&(c["application/x-shockwave-flash"]&&c["application/x-shockwave-flash"].enabledPlugin&&c["application/x-shockwave-flash"].enabledPlugin.description)&&
-(b=!0);else if(f!==k&&!s.match(/MSAppHost/i)){try{a=new f("ShockwaveFlash.ShockwaveFlash")}catch(h){a=null}b=!!a}return v=b};Va=function(){var b,e,d=c.audioFormats;if(ha&&s.match(/os (1|2|3_0|3_1)/i))c.hasHTML5=!1,c.html5Only=!0,c.oMC&&(c.oMC.style.display="none");else if(c.useHTML5Audio&&(!c.html5||!c.html5.canPlayType))c.hasHTML5=!1;if(c.useHTML5Audio&&c.hasHTML5)for(e in S=!0,d)if(d.hasOwnProperty(e)&&d[e].required)if(c.html5.canPlayType(d[e].type)){if(c.preferFlash&&(c.flash[e]||c.flash[d[e].type]))b=
-!0}else S=!1,b=!0;c.ignoreFlash&&(b=!1,S=!0);c.html5Only=c.hasHTML5&&c.useHTML5Audio&&!b;return!c.html5Only};da=function(b){var e,d,a=0;if(b instanceof Array){e=0;for(d=b.length;e<d;e++)if(b[e]instanceof Object){if(c.canPlayMIME(b[e].type)){a=e;break}}else if(c.canPlayURL(b[e])){a=e;break}b[a].url&&(b[a]=b[a].url);b=b[a]}return b};Ra=function(b){b._hasTimer||(b._hasTimer=!0,!Fa&&c.html5PollingInterval&&(null===R&&0===ca&&(R=setInterval(Ta,c.html5PollingInterval)),ca++))};Sa=function(b){b._hasTimer&&
-(b._hasTimer=!1,!Fa&&c.html5PollingInterval&&ca--)};Ta=function(){var b;if(null!==R&&!ca)return clearInterval(R),R=null,!1;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].isHTML5&&c.sounds[c.soundIDs[b]]._hasTimer&&c.sounds[c.soundIDs[b]]._onTimer()};H=function(b){b=b!==k?b:{};"function"===typeof c.onerror&&c.onerror.apply(g,[{type:b.type!==k?b.type:null}]);b.fatal!==k&&b.fatal&&c.disable()};Xa=function(){if(!$a||!Da())return!1;var b=c.audioFormats,e,d;for(d in b)if(b.hasOwnProperty(d)&&
-("mp3"===d||"mp4"===d))if(c.html5[d]=!1,b[d]&&b[d].related)for(e=b[d].related.length-1;0<=e;e--)c.html5[b[d].related[e]]=!1};this._setSandboxType=function(b){};this._externalInterfaceOK=function(b){if(c.swfLoaded)return!1;c.swfLoaded=!0;ja=!1;$a&&Xa();setTimeout(ma,C?100:1)};$=function(b,e){function d(a,b){return'\x3cparam name\x3d"'+a+'" value\x3d"'+b+'" /\x3e'}if(K&&L)return!1;if(c.html5Only)return ra(),c.oMC=W(c.movieID),ma(),L=K=!0,!1;var a=e||c.url,f=c.altURL||a,h=va(),g=I(),l=null,l=n.getElementsByTagName("html")[0],
-m,p,q,l=l&&l.dir&&l.dir.match(/rtl/i);b=b===k?c.id:b;ra();c.url=Qa(Ha?a:f);e=c.url;c.wmode=!c.wmode&&c.useHighPerformance?"transparent":c.wmode;if(null!==c.wmode&&(s.match(/msie 8/i)||!C&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i))Ua.push(sa.spcWmode),c.wmode=null;h={name:b,id:b,src:e,quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:cb+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",
-wmode:c.wmode,hasPriority:"true"};c.debugFlash&&(h.FlashVars="debug\x3d1");c.wmode||delete h.wmode;if(C)a=n.createElement("div"),p=['\x3cobject id\x3d"'+b+'" data\x3d"'+e+'" type\x3d"'+h.type+'" title\x3d"'+h.title+'" classid\x3d"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase\x3d"'+cb+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version\x3d6,0,40,0"\x3e',d("movie",e),d("AllowScriptAccess",c.allowScriptAccess),d("quality",h.quality),c.wmode?d("wmode",c.wmode):"",d("bgcolor",
-c.bgColor),d("hasPriority","true"),c.debugFlash?d("FlashVars",h.FlashVars):"","\x3c/object\x3e"].join("");else for(m in a=n.createElement("embed"),h)h.hasOwnProperty(m)&&a.setAttribute(m,h[m]);wa();g=I();if(h=va())if(c.oMC=W(c.movieID)||n.createElement("div"),c.oMC.id)q=c.oMC.className,c.oMC.className=(q?q+" ":"movieContainer")+(g?" "+g:""),c.oMC.appendChild(a),C&&(m=c.oMC.appendChild(n.createElement("div")),m.className="sm2-object-box",m.innerHTML=p),L=!0;else{c.oMC.id=c.movieID;c.oMC.className=
-"movieContainer "+g;m=g=null;c.useFlashBlock||(c.useHighPerformance?g={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",overflow:"hidden"}:(g={position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"},l&&(g.left=Math.abs(parseInt(g.left,10))+"px")));gb&&(c.oMC.style.zIndex=1E4);if(!c.debugFlash)for(q in g)g.hasOwnProperty(q)&&(c.oMC.style[q]=g[q]);try{C||c.oMC.appendChild(a),h.appendChild(c.oMC),C&&(m=c.oMC.appendChild(n.createElement("div")),m.className="sm2-object-box",
-m.innerHTML=p),L=!0}catch(r){throw Error(P("domError")+" \n"+r.toString());}}return K=!0};Z=function(){if(c.html5Only)return $(),!1;if(l||!c.url)return!1;l=c.getMovie(c.id);l||(O?(C?c.oMC.innerHTML=ya:c.oMC.appendChild(O),O=null,K=!0):$(c.id,c.url),l=c.getMovie(c.id));"function"===typeof c.oninitmovie&&setTimeout(c.oninitmovie,1);return!0};F=function(){setTimeout(Na,1E3)};qa=function(){g.setTimeout(function(){c.setup({preferFlash:!1}).reboot();c.didFlashBlock=!0;c.beginDelayedInit()},1)};Na=function(){var b,
-e=!1;if(!c.url||Q)return!1;Q=!0;t.remove(g,"load",F);if(v&&ja&&!Ga)return!1;p||(b=c.getMoviePercent(),0<b&&100>b&&(e=!0));setTimeout(function(){b=c.getMoviePercent();if(e)return Q=!1,g.setTimeout(F,1),!1;!p&&ab&&(null===b?c.useFlashBlock||0===c.flashLoadTimeout?c.useFlashBlock&&za():!c.useFlashBlock&&S?qa():D({type:"ontimeout",ignoreInit:!0,error:{type:"INIT_FLASHBLOCK"}}):0!==c.flashLoadTimeout&&(!c.useFlashBlock&&S?qa():xa(!0)))},c.flashLoadTimeout)};Y=function(){if(Ga||!ja)return t.remove(g,"focus",
-Y),!0;Ga=ab=!0;Q=!1;F();t.remove(g,"focus",Y);return!0};M=function(b){if(p)return!1;if(c.html5Only)return p=!0,E(),!0;var e=!0,d;if(!c.useFlashBlock||!c.flashLoadTimeout||c.getMoviePercent())p=!0;d={type:!v&&u?"NO_FLASH":"INIT_TIMEOUT"};if(y||b)c.useFlashBlock&&c.oMC&&(c.oMC.className=I()+" "+(null===c.getMoviePercent()?"swf_timedout":"swf_error")),D({type:"ontimeout",error:d,ignoreInit:!0}),H(d),e=!1;y||(c.waitForWindowLoad&&!na?t.add(g,"load",E):E());return e};Ma=function(){var b,e=c.setupOptions;
-for(b in e)e.hasOwnProperty(b)&&(c[b]===k?c[b]=e[b]:c[b]!==e[b]&&(c.setupOptions[b]=c[b]))};ma=function(){if(p)return!1;if(c.html5Only)return p||(t.remove(g,"load",c.beginDelayedInit),c.enabled=!0,M()),!0;Z();try{l._externalInterfaceTest(!1),Oa(!0,c.flashPollingInterval||(c.useHighPerformance?10:50)),c.debugMode||l._disableDebug(),c.enabled=!0,c.html5Only||t.add(g,"unload",la)}catch(b){return H({type:"JS_TO_FLASH_EXCEPTION",fatal:!0}),xa(!0),M(),!1}M();t.remove(g,"load",c.beginDelayedInit);return!0};
-G=function(){if(N)return!1;N=!0;Ma();wa();!v&&c.hasHTML5&&c.setup({useHTML5Audio:!0,preferFlash:!1});Wa();!v&&u&&(Ua.push(sa.needFlash),c.setup({flashLoadTimeout:1}));n.removeEventListener&&n.removeEventListener("DOMContentLoaded",G,!1);Z();return!0};Ba=function(){"complete"===n.readyState&&(G(),n.detachEvent("onreadystatechange",Ba));return!0};ua=function(){na=!0;t.remove(g,"load",ua)};ta=function(){if(Fa&&(c.setupOptions.useHTML5Audio=!0,c.setupOptions.preferFlash=!1,ha||Za&&!s.match(/android\s2\.3/i)))ha&&
-(c.ignoreFlash=!0),A=!0};ta();Da();t.add(g,"focus",Y);t.add(g,"load",F);t.add(g,"load",ua);n.addEventListener?n.addEventListener("DOMContentLoaded",G,!1):n.attachEvent?n.attachEvent("onreadystatechange",Ba):H({type:"NO_DOM2_EVENTS",fatal:!0})}var ka=null;if(void 0===g.SM2_DEFER||!SM2_DEFER)ka=new U;g.SoundManager=U;g.soundManager=ka})(window);
\ No newline at end of file
diff --git a/index.html b/index.html
deleted file mode 100644
index f9cb79d..0000000
--- a/index.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<script src="data/defaults.js" type="text/javascript"></script>
-<script src="data/soundmanager2.js" type="text/javascript"></script>
-<script src="data/background.js" type="text/javascript"></script>
-</head>
-<body>
-<h1>TumTaster</h1>
-<div id="Jukebox">
-</div>
-</body>
-</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
deleted file mode 100644
index b05705d..0000000
--- a/manifest.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "name": "TumTaster",
- "version": "0.5.0",
- "description": "An extension that creates download links for the MP3s you see on Tumblr.",
- "background": {
- "page": "index.html"
- },
- "browser_action": {
- "default_icon": "data/Icon-16.png",
- "default_popup": "data/popup.html",
- "default_title": "TumTaster"
- },
- "content_scripts": [ {
- "js": [ "data/script.js" ],
- "matches": [ "http://*/*", "https://*/*" ],
- "all_frames": true,
- "run_at": "document_start"
- } ],
- "icons": {
- "16": "data/Icon-16.png",
- "32": "data/Icon-32.png",
- "48": "data/Icon-48.png",
- "64": "data/Icon-64.png",
- "128": "data/Icon-128.png"
- },
- "manifest_version": 2,
- "options_page": "data/options.html",
- "permissions": [
- "http://*/*"
- ]
-}
\ No newline at end of file
diff --git a/src/Info.plist b/src/Info.plist
new file mode 100644
index 0000000..7c540d5
--- /dev/null
+++ b/src/Info.plist
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Author</key>
+ <string>Bjorn Stromberg</string>
+ <key>Builder Version</key>
+ <string>10600.1.25</string>
+ <key>CFBundleDisplayName</key>
+ <string>TumTaster</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.bjornstar.safari.tumtaster</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.6.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>Chrome</key>
+ <dict>
+ <key>Global Page</key>
+ <string>index.html</string>
+ <key>Toolbar Items</key>
+ <array>
+ <dict>
+ <key>Command</key>
+ <string>popup</string>
+ <key>Identifier</key>
+ <string>TumTaster Toolbar Button</string>
+ <key>Image</key>
+ <string>data/images/Icon-64.png</string>
+ <key>Label</key>
+ <string>TumTaster</string>
+ <key>Tool Tip</key>
+ <string>Click me to play some music</string>
+ </dict>
+ </array>
+ </dict>
+ <key>Content</key>
+ <dict>
+ <key>Blacklist</key>
+ <array>
+ <string>http://www.tumblr.com/uploads/*</string>
+ <string>https://www.tumblr.com/uploads/*</string>
+ </array>
+ <key>Scripts</key>
+ <dict>
+ <key>Start</key>
+ <array>
+ <string>data/script.js</string>
+ </array>
+ </dict>
+ <key>Whitelist</key>
+ <array>
+ <string>http://www.tumblr.com/*</string>
+ <string>https://www.tumblr.com/*</string>
+ <string>safari-extension://com.bjornstar.safari.tumtaster-4GANG9K96D/*</string>
+ </array>
+ </dict>
+ <key>Description</key>
+ <string>TumTaster creates download links on Tumblr audio posts</string>
+ <key>DeveloperIdentifier</key>
+ <string>4GANG9K96D</string>
+ <key>ExtensionInfoDictionaryVersion</key>
+ <string>1.0</string>
+ <key>Permissions</key>
+ <dict>
+ <key>Website Access</key>
+ <dict>
+ <key>Allowed Domains</key>
+ <array>
+ <string>com.bjornstar.safari.tumtaster-4GANG9K96D</string>
+ <string>www.tumblr.com</string>
+ <string>api.soundcloud.com</string>
+ </array>
+ <key>Include Secure Pages</key>
+ <true/>
+ <key>Level</key>
+ <string>Some</string>
+ </dict>
+ </dict>
+ <key>Update Manifest URL</key>
+ <string>http://tumtaster.bjornstar.com/update.plist</string>
+ <key>Website</key>
+ <string>http://tumtaster.bjornstar.com</string>
+</dict>
+</plist>
diff --git a/src/data/css/font-awesome.min.css b/src/data/css/font-awesome.min.css
new file mode 100755
index 0000000..ec53d4d
--- /dev/null
+++ b/src/data/css/font-awesome.min.css
@@ -0,0 +1,4 @@
+/*!
+ * Font Awesome 4.2.0 by @davegandy - http://fontawesome.io - @fontawesome
+ * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
+ */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.2.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}
\ No newline at end of file
diff --git a/src/data/css/options.css b/src/data/css/options.css
new file mode 100644
index 0000000..c81928f
--- /dev/null
+++ b/src/data/css/options.css
@@ -0,0 +1,72 @@
+html {
+ color: black;
+ font-family: arial,helvetica,sans-serif;
+ margin: 0;
+ padding: 10px 30px 30px 10px;
+ background-color: #36465d;
+ color: #4F545A;
+ width: 640px;
+}
+
+h1 {
+ color: black;
+}
+
+h2 {
+ margin: 0;
+}
+
+p {
+ margin: 0;
+}
+
+a {
+ color: #4F545A;
+ text-decoration: none;
+}
+
+#content {
+ background: white;
+ display: block;
+ margin: 0px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ padding-bottom: 5px;
+ padding-left: 30px;
+ padding-right: 30px;
+ padding-top: 5px;
+ width: 570px;
+ -webkit-border-radius: 10px;
+ -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .46);
+}
+#repeat_div, #player_div {
+ margin-bottom: 25px;
+}
+
+#listBlack, #listWhite {
+ float: left;
+ width: 240px;
+ margin-bottom: 25px;
+}
+
+#listSites {
+ clear: left;
+ width: 540px;
+}
+
+#listSites input {
+ width: 400px;
+}
+
+#version_div {
+ color: #A8B1BA;
+ font: 11px 'Lucida Grande',Verdana,sans-serif;
+ text-align: right;
+}
+
+#browser_span {
+ color: #A8B1BA;
+ font: 11px 'Lucida Grande',Verdana,sans-serif;
+ vertical-align: top;
+}
\ No newline at end of file
diff --git a/src/data/css/popup.css b/src/data/css/popup.css
new file mode 100644
index 0000000..525ade8
--- /dev/null
+++ b/src/data/css/popup.css
@@ -0,0 +1,181 @@
+html {
+ color: black;
+ font-family: arial, helvetica, sans-serif;
+ margin: 0;
+ padding: 0;
+ background-color: #36465d;
+ min-width: 400px;
+}
+
+h1 {
+ color:black;
+}
+
+a {
+ color:white;
+ text-decoration:none;
+}
+
+ol {
+ background-attachment: scroll;
+ background-clip: border-box;
+ background-color: #2C4762;
+ background-image: none;
+ background-origin: padding-box;
+ border-bottom-left-radius: 15px;
+ border-bottom-right-radius: 15px;
+ border-top-left-radius: 15px;
+ border-top-right-radius: 15px;
+ display: block;
+ list-style-type: none;
+ margin-bottom: 0px;
+ margin-left: 0px;
+ margin-right: 0px;
+ margin-top: 0px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ padding-bottom: 20px;
+ padding-left: 20px;
+ padding-right: 20px;
+ padding-top: 20px;
+}
+
+li a {
+ color:#444;
+}
+
+li {
+ background-color: white;
+ border-bottom-color: #BBB;
+ border-bottom-left-radius: 10px;
+ border-bottom-right-radius: 10px;
+ border-bottom-style: solid;
+ border-bottom-width: 2px;
+ border-top-left-radius: 10px;
+ border-top-right-radius: 10px;
+ display: list-item;
+ margin-bottom: 10px;
+ margin-left: 0px;
+ margin-right: 0px;
+ margin-top: 0px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ padding-bottom: 15px;
+ padding-left: 20px;
+ padding-right: 20px;
+ padding-top: 15px;
+ position: relative;
+ word-wrap: break-word;
+}
+
+#nowplayingdiv {
+ background-attachment: scroll;
+ background-clip: border-box;
+ background-color: #BBC552;
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
+ background-origin: padding-box;
+ border-bottom-left-radius: 3px;
+ border-bottom-right-radius: 3px;
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+ color: #C4CDD6;
+ display: block;
+ font-family: 'Lucida Grande', Verdana, sans-serif;
+ font-size: 13px;
+ font-style: normal;
+ font-variant: normal;
+ font-weight: normal;
+ line-height: normal;
+ outline-color: #C4CDD6;
+ outline-style: none;
+ outline-width: 0px;
+ padding-bottom: 9px;
+ padding-left: 10px;
+ padding-right: 10px;
+ padding-top: 8px;
+ position: relative;
+ clear: left;
+}
+
+#nowplayingdiv span {
+ color: #3B440F;
+ cursor: auto;
+ display: inline;
+ height: 0px;
+ outline-color: #3B440F;
+ outline-style: none;
+ outline-width: 0px;
+ text-decoration: none;
+ width: 0px;
+}
+
+#heading {
+ width: 100%;
+ height: 64px;
+}
+
+#heading h1 {
+ color: white;
+ float: left;
+ line-height: 32px;
+ vertical-align: absmiddle;
+ margin-left: 10px;
+}
+
+div#statistics {
+ position: absolute;
+ bottom: 0%;
+}
+
+#controls{
+ text-align: center;
+ width: 100%
+}
+
+#controls a {
+ margin: 20px;
+}
+
+#statusbar{
+ position: relative;
+ height: 12px;
+ background-color: #CDD568;
+ border: 2px solid #EAF839;
+ border-radius: 2px;
+ -moz-border-radius: 2px;
+ -webkit-border-radius: 2px;
+ overflow: hidden;
+ margin-top: 4px;
+}
+
+.remove {
+ position: absolute;
+ right: 8px;
+ top: 8px;
+}
+
+.position, .position2, .loading {
+ position: absolute;
+ left: 0px;
+ bottom: 0px;
+ height: 12px;
+}
+
+.position {
+ background-color: #3B440F;
+ border-right: 2px solid #3B440F;
+ border-radius: 2px;
+ -moz-border-radius: 2px;
+ -webkit-border-radius: 2px;
+ width: 20px;
+}
+
+.position2 {
+ background-color: #EAF839;
+}
+
+.loading {
+ background-color: #BBC552;
+}
diff --git a/src/data/defaults.js b/src/data/defaults.js
new file mode 100644
index 0000000..cb4151c
--- /dev/null
+++ b/src/data/defaults.js
@@ -0,0 +1,19 @@
+// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
+// - By Bjorn Stromberg (@bjornstar)
+
+var defaultSettings = {
+ 'version': '0.6.0',
+ 'shuffle': false,
+ 'repeat': true,
+ 'listBlack': [
+ 'beatles'
+ ],
+ 'listWhite': [
+ 'bjorn',
+ 'beck'
+ ],
+ 'listSites': [
+ 'http://www.tumblr.com/*',
+ 'https://www.tumblr.com/*',
+ ]
+};
diff --git a/src/data/fonts/fontawesome-webfont.woff b/src/data/fonts/fontawesome-webfont.woff
new file mode 100755
index 0000000..628b6a5
Binary files /dev/null and b/src/data/fonts/fontawesome-webfont.woff differ
diff --git a/data/Icon-128.png b/src/data/images/Icon-128.png
similarity index 100%
rename from data/Icon-128.png
rename to src/data/images/Icon-128.png
diff --git a/data/Icon-16.png b/src/data/images/Icon-16.png
similarity index 100%
rename from data/Icon-16.png
rename to src/data/images/Icon-16.png
diff --git a/data/Icon-32.png b/src/data/images/Icon-32.png
similarity index 100%
rename from data/Icon-32.png
rename to src/data/images/Icon-32.png
diff --git a/data/Icon-48.png b/src/data/images/Icon-48.png
similarity index 100%
rename from data/Icon-48.png
rename to src/data/images/Icon-48.png
diff --git a/data/Icon-64.png b/src/data/images/Icon-64.png
similarity index 100%
rename from data/Icon-64.png
rename to src/data/images/Icon-64.png
diff --git a/src/data/main.js b/src/data/main.js
new file mode 100644
index 0000000..d8c8a46
--- /dev/null
+++ b/src/data/main.js
@@ -0,0 +1,193 @@
+// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
+// - By Bjorn Stromberg (@bjornstar)
+
+var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
+
+var settings = defaultSettings;
+
+var savedSettings = localStorage['settings'];
+
+try {
+ if (savedSettings) {
+ settings = JSON.parse(savedSettings);
+ }
+} catch (e) {
+ console.error('Failed to parse settings: ', e);
+}
+
+var ports = {};
+var tracks = {};
+
+var scData = {};
+
+function getDetails(url, cb) {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', url + '.json?client_id=' + API_KEY, true);
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ var response;
+ try {
+ response = JSON.parse(xhr.responseText);
+ } catch (e) {
+ return cb(e);
+ }
+ cb(null, response);
+ }
+ }
+
+ xhr.send();
+}
+
+function broadcast(msg) {
+ for (var portId in ports) {
+ ports[portId].postMessage(msg);
+ }
+}
+
+function addToLibrary(track, seenBefore) {
+ var id = track.id;
+
+ broadcast({ track: track });
+
+ if (!track.streamable || seenBefore) {
+ return;
+ }
+
+ function failOrFinish() {
+ playnextsong(id);
+ }
+
+ if (track.streamable) {
+ soundManager.createSound({
+ id: id,
+ url: track.streamUrl,
+ onloadfailed: failOrFinish,
+ onfinish: failOrFinish
+ });
+ }
+
+ tracks[id] = track;
+}
+
+function addSoundCloudTrack(post, details) {
+ var track = {
+ downloadUrl: details.uri + '/download?client_id=' + API_KEY,
+ streamUrl: details.uri + '/stream?client_id=' + API_KEY,
+
+ downloadable: details.downloadable,
+ streamable: details.streamable,
+
+ artist: details.user ? details.user.username : '',
+ title: details.title,
+ id: details.id,
+
+ postId: post.postId
+ };
+
+ var seenBefore = scData.hasOwnProperty(track.id);
+ scData[track.id] = details;
+
+ addToLibrary(track, seenBefore);
+}
+
+var addPosts = {
+ tumblr: function (post) {
+ post.downloadUrl = post.baseUrl + '?play_key=' + post.postKey;
+ post.streamUrl = post.downloadUrl;
+
+ post.downloadable = true;
+ post.streamable = true;
+
+ post.id = post.postId;
+
+ addToLibrary(post);
+ },
+ soundcloud: function (post) {
+ getDetails(post.baseUrl, function (e, details) {
+ if (e) {
+ return console.error(error);
+ }
+
+ details = details || {};
+
+ if (details.kind === 'track') {
+ return addSoundCloudTrack(post, details);
+ }
+
+ for (var i = 0; i < details.tracks.length; i += 1) {
+ addSoundCloudTrack(post, details.tracks[i]);
+ }
+ });
+ }
+}
+
+function messageHandler(port, message) {
+ if (message === 'getSettings') {
+ return port.postMessage({ settings: settings});
+ }
+
+ if (message.hasOwnProperty('post')) {
+ var post = message.post;
+ addPosts[post.type](post);
+ }
+}
+
+function connectHandler(port) {
+ ports[port.portId_] = port;
+
+ port.onMessage.addListener(function onMessageHandler(message) {
+ messageHandler(port, message);
+ });
+
+ port.postMessage({ settings: settings });
+
+ port.onDisconnect.addListener(function onDisconnectHandler() {
+ disconnectHandler(port);
+ });
+}
+
+function disconnectHandler(port) {
+ delete ports[port.portId_];
+}
+
+chrome.runtime.onConnect.addListener(connectHandler);
+
+function playnextsong(previous_song) {
+ var bad_idea = null;
+ var first_song = null;
+ var next_song = null;
+ for (x in soundManager.sounds) {
+ if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = soundManager.sounds[x].sID;
+ }
+ bad_idea = soundManager.sounds[x].sID;
+ if (first_song == null) {
+ first_song = soundManager.sounds[x].sID;
+ }
+ }
+
+ if (settings['shuffle']) {
+ var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ next_song = soundManager.soundIDs[s];
+ }
+
+ if (settings['repeat'] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
+
+ if (next_song != null) {
+ var soundNext = soundManager.getSoundById(next_song);
+ soundNext.play();
+ }
+}
+
+function playrandomsong(previous_song) {
+ var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
+ mySoundObject.play();
+}
+
+document.addEventListener('DOMContentLoaded', function () {
+ soundManager.setup({'preferFlash': false});
+});
diff --git a/src/data/options/index.html b/src/data/options/index.html
new file mode 100644
index 0000000..ddc3b45
--- /dev/null
+++ b/src/data/options/index.html
@@ -0,0 +1,41 @@
+<html>
+ <head>
+ <title>Options for TumTaster</title>
+ <link href="../css/options.css" rel="stylesheet" type="text/css">
+ <link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css">
+ <script src="../defaults.js" type="text/javascript"></script>
+ <script src="index.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <div id="content">
+ <img style="float:left;" src="../images/Icon-64.png">
+ <h1 style="line-height:32px;height:32px;margin-top:16px;">TumTaster Options <span id="browser_span"> </span></h1>
+
+ <div id="shuffle_div">
+ <input type="checkbox" id="optionShuffle" name="optionShuffle" /> <label for="optionShuffle"> Shuffle</label>
+ </div>
+ <div id="repeat_div">
+ <input type="checkbox" id="optionRepeat" name="optionRepeat" /> <label for="optionRepeat"> Repeat</label>
+ </div>
+ <div id="listBlack">
+ <h2>Black List</h2>
+ <p>Do not add music with these words:</p>
+ <a href="#" id="listBlackAdd">add</a><br />
+ </div>
+ <div id="listWhite">
+ <h2>White List</h2>
+ <p>Always add music with these words:</p>
+ <a href="#" id="listWhiteAdd">add</a><br />
+ </div>
+ <div id="listSites">
+ <h2>Site List</h2>
+ <p>Run TumTaster on these sites:</p>
+ <a href="#" id="listSitesAdd">add</a><br />
+ </div>
+ <br />
+ <input id="save_btn" type="button" value="Save" />
+ <input id="reset_btn" type="button" value="Restore default" />
+ <div id="version_div"> </div>
+ </div>
+ </body>
+</html>
\ No newline at end of file
diff --git a/src/data/options/index.js b/src/data/options/index.js
new file mode 100644
index 0000000..fcf8727
--- /dev/null
+++ b/src/data/options/index.js
@@ -0,0 +1,174 @@
+var inputLast = 0;
+
+document.addEventListener('DOMContentLoaded', function () {
+ var save_btn = document.getElementById('save_btn');
+ var reset_btn = document.getElementById('reset_btn');
+ var listWhiteAdd = document.getElementById('listWhiteAdd');
+ var listBlackAdd = document.getElementById('listBlackAdd');
+ var listSitesAdd = document.getElementById('listSitesAdd');
+
+ save_btn.addEventListener('click', saveOptions);
+ reset_btn.addEventListener('click', function() { if (confirm('Are you sure you want to restore defaults?')) {eraseOptions()} });
+
+ listWhiteAdd.addEventListener('click', function(e) {
+ addInput('listWhite');
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ listBlackAdd.addEventListener('click', function(e) {
+ addInput('listBlack');
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ listSitesAdd.addEventListener('click', function(e) {
+ addInput('listSites');
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ loadOptions();
+});
+
+function loadOptions() {
+ var settings = localStorage['settings'];
+
+ if (settings == undefined) {
+ settings = defaultSettings;
+ } else {
+ settings = JSON.parse(settings);
+ }
+
+ var cbShuffle = document.getElementById('optionShuffle');
+ cbShuffle.checked = settings['shuffle'];
+
+ var cbRepeat = document.getElementById('optionRepeat');
+ cbRepeat.checked = settings['repeat'];
+
+ for (var itemBlack in settings['listBlack']) {
+ addInput('listBlack', settings['listBlack'][itemBlack]);
+ }
+
+ for (var itemWhite in settings['listWhite']) {
+ addInput('listWhite', settings['listWhite'][itemWhite]);
+ }
+
+ for (var itemSites in settings['listSites']) {
+ addInput('listSites', settings['listSites'][itemSites]);
+ }
+
+ addInput('listBlack'); //prepare a blank input box.
+ addInput('listWhite'); //prepare a blank input box.
+ addInput('listSites'); //prepare a blank input box.
+
+ var version_div = document.getElementById('version_div');
+ version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
+
+ if (typeof opera != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = 'for Opera™';
+ }
+
+ if (typeof chrome != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = 'for Chrome™';
+ }
+
+ if (typeof safari != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = 'for Safari™';
+ }
+}
+
+function removeInput(optionWhich) {
+ var optionInput = document.getElementById(optionWhich);
+ if (!optionInput) {
+ return;
+ }
+ optionInput.parentNode.removeChild(optionInput);
+}
+
+function addInput(whichList, itemValue) {
+ var listDiv, listAdd, optionInput, currentLength, removeThis, optionAdd, optionImage, optionLinebreak, optionDiv;
+
+ if (itemValue === undefined) { //if we don't pass an itemValue, make it blank.
+ itemValue = '';
+ }
+
+ currentLength = inputLast++; //have unique DOM id's
+
+ listDiv = document.getElementById(whichList);
+ listAdd = document.getElementById(whichList + 'Add');
+
+ optionInput = document.createElement('input');
+ optionInput.value = itemValue;
+ optionInput.name = 'option' + whichList;
+ optionInput.id = 'option' + whichList + currentLength;
+
+ optionAdd = document.createElement('a');
+ optionAdd.href = '#';
+ optionAdd.addEventListener('click', function (e) {
+ removeThis = e.target;
+ while (removeThis.tagName !== 'DIV') {
+ removeThis = removeThis.parentNode;
+ }
+ if (removeThis.id.indexOf('_div') >= 0) {
+ removeInput(removeThis.id);
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ optionAdd.appendChild(document.createTextNode('\u00A0'));
+
+ optionImage = document.createElement('img');
+ optionImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
+ optionAdd.appendChild(optionImage);
+
+ optionAdd.appendChild(document.createTextNode('\u00A0'));
+
+ optionLinebreak = document.createElement('br');
+ optionDiv = document.createElement('div');
+ optionDiv.id = 'option' + whichList + currentLength + '_div';
+ optionDiv.appendChild(optionAdd);
+ optionDiv.appendChild(optionInput);
+ optionDiv.appendChild(optionLinebreak);
+
+ listDiv.insertBefore(optionDiv, listAdd);
+}
+
+function saveOptions() {
+ var settings = {};
+
+ var cbShuffle = document.getElementById('optionShuffle');
+ settings['shuffle'] = cbShuffle.checked;
+
+ var cbRepeat = document.getElementById('optionRepeat');
+ settings['repeat'] = cbRepeat.checked;
+
+ settings['listWhite'] = [];
+ settings['listBlack'] = [];
+ settings['listSites'] = [];
+
+ var garbages = document.getElementsByTagName('input');
+ for (var i = 0; i< garbages.length; i++) {
+ if (garbages[i].value != '') {
+ console.log(garbages[i]);
+ if (garbages[i].name.indexOf('listWhite') !== -1) {
+ settings['listWhite'].push(garbages[i].value);
+ } else if (garbages[i].name.indexOf('listBlack') !== -1) {
+ settings['listBlack'].push(garbages[i].value);
+ } else if (garbages[i].name.indexOf('listSites') !== -1) {
+ settings['listSites'].push(garbages[i].value);
+ }
+ }
+ }
+ localStorage['settings'] = JSON.stringify(settings);
+ //location.reload();
+}
+
+function eraseOptions() {
+ localStorage.removeItem('settings');
+ location.reload();
+}
diff --git a/src/data/popup/index.html b/src/data/popup/index.html
new file mode 100644
index 0000000..9d19b77
--- /dev/null
+++ b/src/data/popup/index.html
@@ -0,0 +1,27 @@
+<html>
+ <head>
+ <link href="../css/popup.css" rel="stylesheet" type="text/css">
+ <link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css">
+ <script src="index.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <div id="heading"><img src="../images/Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
+ <div id="statistics"><span> </span></div>
+ <div id="nowplayingdiv"><span id="nowplaying"> </span>
+ <div id="statusbar">
+ <div id="loading" class="loading"> </div>
+ <div id="position2" class="position2"> </div>
+ <div id="position" class="position"> </div>
+ </div>
+ </div>
+
+ <p id="controls">
+ <a id="prev" href="#"><i class="fa fa-fast-backward fa-4x"></i></a>
+ <a id="play" href="#"><i class="fa fa-play fa-4x"></i></a>
+ <a id="next" href="#"><i class="fa fa-fast-forward fa-4x"></i></a>
+ <a id="mode" href="#"><i class="fa fa-random fa-4x"></i></a>
+ </p>
+
+ <ol id="playlist" class="playlist"></ol>
+ </body>
+</html>
\ No newline at end of file
diff --git a/data/popup.js b/src/data/popup/index.js
similarity index 74%
rename from data/popup.js
rename to src/data/popup/index.js
index 06f9e59..f7737cd 100644
--- a/data/popup.js
+++ b/src/data/popup/index.js
@@ -1,169 +1,172 @@
var bg = chrome.extension.getBackgroundPage();
var tracks = bg.tracks;
var sm = bg.soundManager;
var div_loading, div_position, div_position2, nowplaying;
+function getPlaying() {
+ for (sound in sm.sounds) {
+ if (sm.sounds[sound].playState == 1) {
+ return sm.sounds[sound];
+ }
+ }
+}
+
+function playPause() {
+ var track = getPlaying();
+
+ if (track) {
+ sm.pauseAll();
+ } else {
+ sm.resumeAll();
+ }
+}
+
document.addEventListener('DOMContentLoaded', function () {
- var stopLink = document.getElementById('stop');
- var pauseLink = document.getElementById('pause');
+ var prevLink = document.getElementById('prev');
var playLink = document.getElementById('play');
var nextLink = document.getElementById('next');
- var randomLink = document.getElementById('random');
-
- stopLink.addEventListener('click', function(e) {
- sm.stopAll();
- e.preventDefault();
- e.stopPropagation();
- }, false);
+ var modeLink = document.getElementById('mode');
- pauseLink.addEventListener('click', function(e) {
- pause();
+ prevLink.addEventListener('click', function(e) {
+ prev();
e.preventDefault();
e.stopPropagation();
}, false);
playLink.addEventListener('click', function(e) {
- sm.resumeAll();
+ playPause();
e.preventDefault();
e.stopPropagation();
}, false);
nextLink.addEventListener('click', function(e) {
playnextsong();
e.preventDefault();
e.stopPropagation();
}, false);
- randomLink.addEventListener('click', function(e) {
+ modeLink.addEventListener('click', function(e) {
playrandomsong();
e.preventDefault();
e.stopPropagation();
}, false);
div_loading = document.getElementById('loading');
div_position = document.getElementById('position');
div_position2 = document.getElementById('position2');
nowplaying = document.getElementById('nowplaying');
var playlist = document.getElementById('playlist');
- var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
-
- setInterval(updateStatus, 200);
-
for (var id in tracks) {
var track = tracks[id];
- var liSong = document.createElement('li');
- var aSong = document.createElement('a');
+ var liSong = document.createElement('LI');
+ var aSong = document.createElement('A');
aSong.id = id;
aSong.addEventListener('click', function(e) {
play(null, e.target.id);
e.preventDefault();
e.stopPropagation();
}, false);
aSong.href = '#';
var trackDisplay = id;
- if (track.artist && track.track) {
- trackDisplay = track.artist + ' - ' + track.track;
+ if (track.artist && track.title) {
+ trackDisplay = track.artist + ' - ' + track.title;
}
aSong.textContent = trackDisplay;
- var aRemove = document.createElement('a');
+ var aRemove = document.createElement('A');
aRemove.className = 'remove';
aRemove.href = '#';
aRemove.addEventListener('click', function(e) {
remove(e.target.parentNode.previousSibling.id);
e.preventDefault();
e.stopPropagation();
}, false);
- var imgRemove = document.createElement('img');
- imgRemove.src = PNGremove;
+ var iRemove = document.createElement('I');
+ iRemove.className = 'fa fa-remove'
- aRemove.appendChild(imgRemove);
+ aRemove.appendChild(iRemove);
liSong.appendChild(aSong);
liSong.appendChild(aRemove);
playlist.appendChild(liSong);
}
+
+ updateStatus();
});
function remove(song_id) {
sm.destroySound(song_id);
var song_li = document.getElementById(song_id);
song_li.parentNode.parentNode.removeChild(song_li.parentNode);
}
function pause() {
track = getPlaying();
track.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var sound = sm.getSoundById(post_url);
sound.play();
}
-function getPlaying() {
- for (sound in sm.sounds) {
- if (sm.sounds[sound].playState == 1) {
- return sm.sounds[sound];
- }
- }
-}
-
function playnextsong() {
var track = getPlaying();
var track_sID;
if (track) {
track.stop();
track_sID = track.sID;
}
bg.playnextsong(track_sID);
}
function playrandomsong() {
var current_song = getPlaying();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
}
function updateStatus() {
var track = getPlaying();
if (track) {
var bytesLoaded = track.bytesLoaded;
var bytesTotal = track.bytesTotal;
var position = track.position;
var durationEstimate = track.durationEstimate;
if (bytesTotal) {
div_loading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
}
div_position.style.left = (100 * position / durationEstimate) + '%';
div_position2.style.width = (100 * position / durationEstimate) + '%';
}
if (track && nowplaying.textContent !== track.id) {
var trackDisplay = track.id;
if (tracks[track.id].artist && tracks[track.id].track) {
trackDisplay = tracks[track.id].artist + ' - ' + tracks[track.id].track;
}
nowplaying.textContent = trackDisplay;
}
+
+ requestAnimationFrame(updateStatus);
}
\ No newline at end of file
diff --git a/data/script.js b/src/data/script.js
similarity index 60%
rename from data/script.js
rename to src/data/script.js
index 13ea42f..5f9bf2c 100644
--- a/data/script.js
+++ b/src/data/script.js
@@ -1,250 +1,260 @@
-// TumTaster v0.5.0 -- http://tumtaster.bjornstar.com
+// TumTaster v0.6.0 -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var settings, started;
function addLink(track) {
- var post = document.getElementById('post_' + track.postId);
- if (!post) {
+ var elmPost = document.getElementById('post_' + track.postId);
+ if (!elmPost) {
return;
}
- var footer = post.querySelector('.post_footer');
- if (footer) {
- var divDownload = document.createElement('DIV');
- divDownload.className = 'tumtaster';
- var aDownload = document.createElement('A');
- aDownload.href = track.downloadUrl;
- aDownload.textContent = 'Download';
- divDownload.appendChild(aDownload);
- footer.insertBefore(divDownload, footer.children[1]);
+ var elmFooter = elmPost.querySelector('.post_footer');
+ if (!elmFooter) {
+ return;
+ }
+
+ var divDownload = document.createElement('DIV');
+ divDownload.className = 'tumtaster';
+
+ var aDownload = document.createElement('A');
+ aDownload.href = track.downloadUrl;
+ aDownload.textContent = 'Download';
+
+ if (!track.downloadable) {
+ aDownload.style.setProperty('text-decoration', 'line-through');
}
+
+ divDownload.appendChild(aDownload);
+
+ elmFooter.insertBefore(divDownload, elmFooter.children[1]);
}
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
addLink(message.track);
}
}
var port = chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
- filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
+ filterRegex=filter[f].replace(/\x2a/g, '(.*?)');
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
-var tracks = {};
+var posts = {};
function makeTumblrLink(dataset) {
var postId = dataset.postId;
- tracks[postId] = {
+ posts[postId] = {
postId: postId,
- streamUrl: dataset.streamUrl,
+ baseUrl: dataset.streamUrl,
postKey: dataset.postKey,
artist: dataset.artist,
- track: dataset.track,
+ title: dataset.track,
type: 'tumblr'
};
- port.postMessage({ track: tracks[postId] });
+ port.postMessage({ post: posts[postId] });
}
function makeSoundCloudLink(dataset, url) {
var qs = url.split('?')[1];
var chunks = qs.split('&');
var url;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
url = decodeURIComponent(chunks[i].substring(4));
break;
}
}
var postId = dataset.postId;
- tracks[postId] = {
+ posts[postId] = {
postId: postId,
- streamUrl: url,
+ baseUrl: url,
type: 'soundcloud'
};
- port.postMessage({ track: tracks[postId] });
+ port.postMessage({ post: posts[postId] });
}
function extractAudioData(post) {
var postId = post.dataset.postId;
- if (!postId || tracks[postId]) {
+ if (!postId || posts[postId]) {
return;
}
var soundcloud = post.querySelector('.soundcloud_audio_player');
if (soundcloud) {
return makeSoundCloudLink(post.dataset, soundcloud.src);
}
var tumblr = post.querySelector('.audio_player_container');
if (tumblr) {
return makeTumblrLink(tumblr.dataset);
}
}
function handleNodeInserted(event) {
- snarfAudioPlayers(event.target);
+ snarfAudioPlayers(event.target.parentNode);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var cssRules = [];
cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
- cssRules[0] = "@keyframes nodeInserted {";
- cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[0] += "}";
-
- cssRules[1] = "@-moz-keyframes nodeInserted {";
- cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[1] += "}";
-
- cssRules[2] = "@-webkit-keyframes nodeInserted {";
- cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[2] += "}";
-
- cssRules[3] = "@-ms-keyframes nodeInserted {";
- cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[3] += "}";
-
- cssRules[4] = "@-o-keyframes nodeInserted {";
- cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[4] += "}";
-
- cssRules[5] = "ol#posts li {";
- cssRules[5] += " animation-duration: 1ms;";
- cssRules[5] += " -o-animation-duration: 1ms;";
- cssRules[5] += " -ms-animation-duration: 1ms;";
- cssRules[5] += " -moz-animation-duration: 1ms;";
- cssRules[5] += " -webkit-animation-duration: 1ms;";
- cssRules[5] += " animation-name: nodeInserted;";
- cssRules[5] += " -o-animation-name: nodeInserted;";
- cssRules[5] += " -ms-animation-name: nodeInserted;";
- cssRules[5] += " -moz-animation-name: nodeInserted;";
- cssRules[5] += " -webkit-animation-name: nodeInserted;";
- cssRules[5] += "}";
-
- addGlobalStyle("wires", cssRules);
+ cssRules[0] = '@keyframes nodeInserted {';
+ cssRules[0] += ' from { clip: rect(1px, auto, auto, auto); }';
+ cssRules[0] += ' to { clip: rect(0px, auto, auto, auto); }';
+ cssRules[0] += '}';
+
+ cssRules[1] = '@-moz-keyframes nodeInserted {';
+ cssRules[1] += ' from { clip: rect(1px, auto, auto, auto); }';
+ cssRules[1] += ' to { clip: rect(0px, auto, auto, auto); }';
+ cssRules[1] += '}';
+
+ cssRules[2] = '@-webkit-keyframes nodeInserted {';
+ cssRules[2] += ' from { clip: rect(1px, auto, auto, auto); }';
+ cssRules[2] += ' to { clip: rect(0px, auto, auto, auto); }';
+ cssRules[2] += '}';
+
+ cssRules[3] = '@-ms-keyframes nodeInserted {';
+ cssRules[3] += ' from { clip: rect(1px, auto, auto, auto); }';
+ cssRules[3] += ' to { clip: rect(0px, auto, auto, auto); }';
+ cssRules[3] += '}';
+
+ cssRules[4] = '@-o-keyframes nodeInserted {';
+ cssRules[4] += ' from { clip: rect(1px, auto, auto, auto); }';
+ cssRules[4] += ' to { clip: rect(0px, auto, auto, auto); }';
+ cssRules[4] += '}';
+
+ cssRules[5] = '.post_container div.post, li.post {';
+ cssRules[5] += ' animation-duration: 1ms;';
+ cssRules[5] += ' -o-animation-duration: 1ms;';
+ cssRules[5] += ' -ms-animation-duration: 1ms;';
+ cssRules[5] += ' -moz-animation-duration: 1ms;';
+ cssRules[5] += ' -webkit-animation-duration: 1ms;';
+ cssRules[5] += ' animation-name: nodeInserted;';
+ cssRules[5] += ' -o-animation-name: nodeInserted;';
+ cssRules[5] += ' -ms-animation-name: nodeInserted;';
+ cssRules[5] += ' -moz-animation-name: nodeInserted;';
+ cssRules[5] += ' -webkit-animation-name: nodeInserted;';
+ cssRules[5] += '}';
+
+ addGlobalStyle('tastyWires', cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
- started = true;
-
if (!checkurl(location.href, settings['listSites'])) {
port.disconnect();
return;
}
+ started = true;
+
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
-document.addEventListener("DOMContentLoaded", startTasting);
+document.onreadystatechange = startTasting;
+document.addEventListener('DOMContentLoaded', startTasting);
startTasting();
\ No newline at end of file
diff --git a/src/data/soundmanager2-nodebug-jsmin.js b/src/data/soundmanager2-nodebug-jsmin.js
new file mode 100755
index 0000000..cefbcc1
--- /dev/null
+++ b/src/data/soundmanager2-nodebug-jsmin.js
@@ -0,0 +1,83 @@
+/** @license
+ *
+ * SoundManager 2: JavaScript Sound for the Web
+ * ----------------------------------------------
+ * http://schillmania.com/projects/soundmanager2/
+ *
+ * Copyright (c) 2007, Scott Schiller. All rights reserved.
+ * Code provided under the BSD License:
+ * http://schillmania.com/projects/soundmanager2/license.txt
+ *
+ * V2.97a.20140901
+ */
+(function(g,h){function G(F,G){function W(b){return c.preferFlash&&v&&!c.ignoreFlash&&c.flash[b]!==h&&c.flash[b]}function r(b){return function(c){var d=this._s;return!d||!d._a?null:b.call(this,c)}}this.setupOptions={url:F||null,flashVersion:8,debugMode:!0,debugFlash:!1,useConsole:!0,consoleOnly:!0,waitForWindowLoad:!1,bgColor:"#ffffff",useHighPerformance:!1,flashPollingInterval:null,html5PollingInterval:null,flashLoadTimeout:1E3,wmode:null,allowScriptAccess:"always",useFlashBlock:!1,useHTML5Audio:!0,
+html5Test:/^(probably|maybe)$/i,preferFlash:!1,noSWFCache:!1,idPrefix:"sound"};this.defaultOptions={autoLoad:!1,autoPlay:!1,from:null,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onposition:null,onstop:null,onfailure:null,onfinish:null,multiShot:!0,multiShotEvents:!1,position:null,pan:0,stream:!0,to:null,type:null,usePolicyFile:!1,volume:100};this.flash9Options={isMovieStar:null,usePeakData:!1,useWaveformData:!1,useEQData:!1,onbufferchange:null,
+ondataerror:null};this.movieStarOptions={bufferTime:3,serverURL:null,onconnect:null,duration:null};this.audioFormats={mp3:{type:['audio/mpeg; codecs\x3d"mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:!0},mp4:{related:["aac","m4a","m4b"],type:['audio/mp4; codecs\x3d"mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:!1},ogg:{type:["audio/ogg; codecs\x3dvorbis"],required:!1},opus:{type:["audio/ogg; codecs\x3dopus","audio/opus"],required:!1},
+wav:{type:['audio/wav; codecs\x3d"1"',"audio/wav","audio/wave","audio/x-wav"],required:!1}};this.movieID="sm2-container";this.id=G||"sm2movie";this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.versionNumber="V2.97a.20140901";this.altURL=this.movieURL=this.version=null;this.enabled=this.swfLoaded=!1;this.oMC=null;this.sounds={};this.soundIDs=[];this.didFlashBlock=this.muted=!1;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.features=
+{buffering:!1,peakData:!1,waveformData:!1,eqData:!1,movieStar:!1};this.sandbox={};this.html5={usingFlash:null};this.flash={};this.ignoreFlash=this.html5Only=!1;var Ja,c=this,Ka=null,k=null,X,t=navigator.userAgent,La=g.location.href.toString(),p=document,la,Ma,ma,n,x=[],M=!1,N=!1,m=!1,y=!1,na=!1,O,w,oa,Y,pa,D,H,I,Na,qa,ra,Z,sa,$,ta,E,ua,P,va,aa,J,Oa,wa,Pa,xa,Qa,Q=null,ya=null,R,za,K,ba,ca,q,S=!1,Aa=!1,Ra,Sa,Ta,da=0,T=null,ea,Ua=[],U,u=null,Va,fa,V,z,ga,Ba,Wa,s,fb=Array.prototype.slice,A=!1,Ca,v,Da,
+Xa,B,ha,Ya=0,ia=t.match(/(ipad|iphone|ipod)/i),Za=t.match(/android/i),C=t.match(/msie/i),gb=t.match(/webkit/i),ja=t.match(/safari/i)&&!t.match(/chrome/i),Ea=t.match(/opera/i),Fa=t.match(/(mobile|pre\/|xoom)/i)||ia||Za,$a=!La.match(/usehtml5audio/i)&&!La.match(/sm2\-ignorebadua/i)&&ja&&!t.match(/silk/i)&&t.match(/OS X 10_6_([3-7])/i),Ga=p.hasFocus!==h?p.hasFocus():null,ka=ja&&(p.hasFocus===h||!p.hasFocus()),ab=!ka,bb=/(mp3|mp4|mpa|m4a|m4b)/i,Ha=p.location?p.location.protocol.match(/http/i):null,cb=
+!Ha?"http://":"",db=/^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|m4b|mp4v|3gp|3g2)\s*(?:$|;)/i,eb="mpeg4 aac flv mov mp4 m4v f4v m4a m4b mp4v 3gp 3g2".split(" "),hb=RegExp("\\.("+eb.join("|")+")(\\?.*)?$","i");this.mimePattern=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.useAltURL=!Ha;var Ia;try{Ia=Audio!==h&&(Ea&&opera!==h&&10>opera.version()?new Audio(null):new Audio).canPlayType!==h}catch(ib){Ia=!1}this.hasHTML5=Ia;this.setup=function(b){var e=!c.url;b!==h&&m&&u&&c.ok();oa(b);b&&
+(e&&(P&&b.url!==h)&&c.beginDelayedInit(),!P&&(b.url!==h&&"complete"===p.readyState)&&setTimeout(E,1));return c};this.supported=this.ok=function(){return u?m&&!y:c.useHTML5Audio&&c.hasHTML5};this.getMovie=function(b){return X(b)||p[b]||g[b]};this.createSound=function(b,e){function d(){a=ba(a);c.sounds[a.id]=new Ja(a);c.soundIDs.push(a.id);return c.sounds[a.id]}var a,f=null;if(!m||!c.ok())return!1;e!==h&&(b={id:b,url:e});a=w(b);a.url=ea(a.url);void 0===a.id&&(a.id=c.setupOptions.idPrefix+Ya++);if(q(a.id,
+!0))return c.sounds[a.id];if(fa(a))f=d(),f._setup_html5(a);else{if(c.html5Only||c.html5.usingFlash&&a.url&&a.url.match(/data\:/i))return d();8<n&&null===a.isMovieStar&&(a.isMovieStar=!(!a.serverURL&&!(a.type&&a.type.match(db)||a.url&&a.url.match(hb))));a=ca(a,void 0);f=d();8===n?k._createSound(a.id,a.loops||1,a.usePolicyFile):(k._createSound(a.id,a.url,a.usePeakData,a.useWaveformData,a.useEQData,a.isMovieStar,a.isMovieStar?a.bufferTime:!1,a.loops||1,a.serverURL,a.duration||null,a.autoPlay,!0,a.autoLoad,
+a.usePolicyFile),a.serverURL||(f.connected=!0,a.onconnect&&a.onconnect.apply(f)));!a.serverURL&&(a.autoLoad||a.autoPlay)&&f.load(a)}!a.serverURL&&a.autoPlay&&f.play();return f};this.destroySound=function(b,e){if(!q(b))return!1;var d=c.sounds[b],a;d._iO={};d.stop();d.unload();for(a=0;a<c.soundIDs.length;a++)if(c.soundIDs[a]===b){c.soundIDs.splice(a,1);break}e||d.destruct(!0);delete c.sounds[b];return!0};this.load=function(b,e){return!q(b)?!1:c.sounds[b].load(e)};this.unload=function(b){return!q(b)?
+!1:c.sounds[b].unload()};this.onposition=this.onPosition=function(b,e,d,a){return!q(b)?!1:c.sounds[b].onposition(e,d,a)};this.clearOnPosition=function(b,e,d){return!q(b)?!1:c.sounds[b].clearOnPosition(e,d)};this.start=this.play=function(b,e){var d=null,a=e&&!(e instanceof Object);if(!m||!c.ok())return!1;if(q(b,a))a&&(e={url:e});else{if(!a)return!1;a&&(e={url:e});e&&e.url&&(e.id=b,d=c.createSound(e).play())}null===d&&(d=c.sounds[b].play(e));return d};this.setPosition=function(b,e){return!q(b)?!1:c.sounds[b].setPosition(e)};
+this.stop=function(b){return!q(b)?!1:c.sounds[b].stop()};this.stopAll=function(){for(var b in c.sounds)c.sounds.hasOwnProperty(b)&&c.sounds[b].stop()};this.pause=function(b){return!q(b)?!1:c.sounds[b].pause()};this.pauseAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].pause()};this.resume=function(b){return!q(b)?!1:c.sounds[b].resume()};this.resumeAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].resume()};this.togglePause=function(b){return!q(b)?
+!1:c.sounds[b].togglePause()};this.setPan=function(b,e){return!q(b)?!1:c.sounds[b].setPan(e)};this.setVolume=function(b,e){return!q(b)?!1:c.sounds[b].setVolume(e)};this.mute=function(b){var e=0;b instanceof String&&(b=null);if(b)return!q(b)?!1:c.sounds[b].mute();for(e=c.soundIDs.length-1;0<=e;e--)c.sounds[c.soundIDs[e]].mute();return c.muted=!0};this.muteAll=function(){c.mute()};this.unmute=function(b){b instanceof String&&(b=null);if(b)return!q(b)?!1:c.sounds[b].unmute();for(b=c.soundIDs.length-
+1;0<=b;b--)c.sounds[c.soundIDs[b]].unmute();c.muted=!1;return!0};this.unmuteAll=function(){c.unmute()};this.toggleMute=function(b){return!q(b)?!1:c.sounds[b].toggleMute()};this.getMemoryUse=function(){var b=0;k&&8!==n&&(b=parseInt(k._getMemoryUse(),10));return b};this.disable=function(b){var e;b===h&&(b=!1);if(y)return!1;y=!0;for(e=c.soundIDs.length-1;0<=e;e--)Pa(c.sounds[c.soundIDs[e]]);O(b);s.remove(g,"load",H);return!0};this.canPlayMIME=function(b){var e;c.hasHTML5&&(e=V({type:b}));!e&&u&&(e=b&&
+c.ok()?!!(8<n&&b.match(db)||b.match(c.mimePattern)):null);return e};this.canPlayURL=function(b){var e;c.hasHTML5&&(e=V({url:b}));!e&&u&&(e=b&&c.ok()?!!b.match(c.filePattern):null);return e};this.canPlayLink=function(b){return b.type!==h&&b.type&&c.canPlayMIME(b.type)?!0:c.canPlayURL(b.href)};this.getSoundById=function(b,e){return!b?null:c.sounds[b]};this.onready=function(b,c){if("function"===typeof b)c||(c=g),pa("onready",b,c),D();else throw R("needFunction","onready");return!0};this.ontimeout=function(b,
+c){if("function"===typeof b)c||(c=g),pa("ontimeout",b,c),D({type:"ontimeout"});else throw R("needFunction","ontimeout");return!0};this._wD=this._writeDebug=function(b,c){return!0};this._debug=function(){};this.reboot=function(b,e){var d,a,f;for(d=c.soundIDs.length-1;0<=d;d--)c.sounds[c.soundIDs[d]].destruct();if(k)try{C&&(ya=k.innerHTML),Q=k.parentNode.removeChild(k)}catch(h){}ya=Q=u=k=null;c.enabled=P=m=S=Aa=M=N=y=A=c.swfLoaded=!1;c.soundIDs=[];c.sounds={};Ya=0;if(b)x=[];else for(d in x)if(x.hasOwnProperty(d)){a=
+0;for(f=x[d].length;a<f;a++)x[d][a].fired=!1}c.html5={usingFlash:null};c.flash={};c.html5Only=!1;c.ignoreFlash=!1;g.setTimeout(function(){ta();e||c.beginDelayedInit()},20);return c};this.reset=function(){return c.reboot(!0,!0)};this.getMoviePercent=function(){return k&&"PercentLoaded"in k?k.PercentLoaded():null};this.beginDelayedInit=function(){na=!0;E();setTimeout(function(){if(Aa)return!1;aa();$();return Aa=!0},20);I()};this.destruct=function(){c.disable(!0)};Ja=function(b){var e,d,a=this,f,l,L,
+g,p,r,t=!1,m=[],u=0,x,y,v=null,z;d=e=null;this.sID=this.id=b.id;this.url=b.url;this._iO=this.instanceOptions=this.options=w(b);this.pan=this.options.pan;this.volume=this.options.volume;this.isHTML5=!1;this._a=null;z=this.url?!1:!0;this.id3={};this._debug=function(){};this.load=function(b){var e=null,d;b!==h?a._iO=w(b,a.options):(b=a.options,a._iO=b,v&&v!==a.url&&(a._iO.url=a.url,a.url=null));a._iO.url||(a._iO.url=a.url);a._iO.url=ea(a._iO.url);d=a.instanceOptions=a._iO;if(!d.url&&!a.url)return a;
+if(d.url===a.url&&0!==a.readyState&&2!==a.readyState)return 3===a.readyState&&d.onload&&ha(a,function(){d.onload.apply(a,[!!a.duration])}),a;a.loaded=!1;a.readyState=1;a.playState=0;a.id3={};if(fa(d))e=a._setup_html5(d),e._called_load||(a._html5_canplay=!1,a.url!==d.url&&(a._a.src=d.url,a.setPosition(0)),a._a.autobuffer="auto",a._a.preload="auto",a._a._called_load=!0);else{if(c.html5Only||a._iO.url&&a._iO.url.match(/data\:/i))return a;try{a.isHTML5=!1;a._iO=ca(ba(d));if(a._iO.autoPlay&&(a._iO.position||
+a._iO.from))a._iO.autoPlay=!1;d=a._iO;8===n?k._load(a.id,d.url,d.stream,d.autoPlay,d.usePolicyFile):k._load(a.id,d.url,!!d.stream,!!d.autoPlay,d.loops||1,!!d.autoLoad,d.usePolicyFile)}catch(f){J({type:"SMSOUND_LOAD_JS_EXCEPTION",fatal:!0})}}a.url=d.url;return a};this.unload=function(){0!==a.readyState&&(a.isHTML5?(g(),a._a&&(a._a.pause(),v=ga(a._a))):8===n?k._unload(a.id,"about:blank"):k._unload(a.id),f());return a};this.destruct=function(b){a.isHTML5?(g(),a._a&&(a._a.pause(),ga(a._a),A||L(),a._a._s=
+null,a._a=null)):(a._iO.onfailure=null,k._destroySound(a.id));b||c.destroySound(a.id,!0)};this.start=this.play=function(b,e){var d,f,l,g,L;f=!0;f=null;e=e===h?!0:e;b||(b={});a.url&&(a._iO.url=a.url);a._iO=w(a._iO,a.options);a._iO=w(b,a._iO);a._iO.url=ea(a._iO.url);a.instanceOptions=a._iO;if(!a.isHTML5&&a._iO.serverURL&&!a.connected)return a.getAutoPlay()||a.setAutoPlay(!0),a;fa(a._iO)&&(a._setup_html5(a._iO),p());1===a.playState&&!a.paused&&(d=a._iO.multiShot,d||(a.isHTML5&&a.setPosition(a._iO.position),
+f=a));if(null!==f)return f;b.url&&b.url!==a.url&&(!a.readyState&&!a.isHTML5&&8===n&&z?z=!1:a.load(a._iO));a.loaded||(0===a.readyState?(!a.isHTML5&&!c.html5Only?(a._iO.autoPlay=!0,a.load(a._iO)):a.isHTML5?a.load(a._iO):f=a,a.instanceOptions=a._iO):2===a.readyState&&(f=a));if(null!==f)return f;!a.isHTML5&&(9===n&&0<a.position&&a.position===a.duration)&&(b.position=0);if(a.paused&&0<=a.position&&(!a._iO.serverURL||0<a.position))a.resume();else{a._iO=w(b,a._iO);if((!a.isHTML5&&null!==a._iO.position&&
+0<a._iO.position||null!==a._iO.from&&0<a._iO.from||null!==a._iO.to)&&0===a.instanceCount&&0===a.playState&&!a._iO.serverURL){d=function(){a._iO=w(b,a._iO);a.play(a._iO)};if(a.isHTML5&&!a._html5_canplay)a.load({_oncanplay:d}),f=!1;else if(!a.isHTML5&&!a.loaded&&(!a.readyState||2!==a.readyState))a.load({onload:d}),f=!1;if(null!==f)return f;a._iO=y()}(!a.instanceCount||a._iO.multiShotEvents||a.isHTML5&&a._iO.multiShot&&!A||!a.isHTML5&&8<n&&!a.getAutoPlay())&&a.instanceCount++;a._iO.onposition&&0===a.playState&&
+r(a);a.playState=1;a.paused=!1;a.position=a._iO.position!==h&&!isNaN(a._iO.position)?a._iO.position:0;a.isHTML5||(a._iO=ca(ba(a._iO)));a._iO.onplay&&e&&(a._iO.onplay.apply(a),t=!0);a.setVolume(a._iO.volume,!0);a.setPan(a._iO.pan,!0);a.isHTML5?2>a.instanceCount?(p(),f=a._setup_html5(),a.setPosition(a._iO.position),f.play()):(l=new Audio(a._iO.url),g=function(){s.remove(l,"ended",g);a._onfinish(a);ga(l);l=null},L=function(){s.remove(l,"canplay",L);try{l.currentTime=a._iO.position/1E3}catch(b){}l.play()},
+s.add(l,"ended",g),void 0!==a._iO.volume&&(l.volume=Math.max(0,Math.min(1,a._iO.volume/100))),a.muted&&(l.muted=!0),a._iO.position?s.add(l,"canplay",L):l.play()):(f=k._start(a.id,a._iO.loops||1,9===n?a.position:a.position/1E3,a._iO.multiShot||!1),9===n&&!f&&a._iO.onplayerror&&a._iO.onplayerror.apply(a))}return a};this.stop=function(b){var c=a._iO;1===a.playState&&(a._onbufferchange(0),a._resetOnPosition(0),a.paused=!1,a.isHTML5||(a.playState=0),x(),c.to&&a.clearOnPosition(c.to),a.isHTML5?a._a&&(b=
+a.position,a.setPosition(0),a.position=b,a._a.pause(),a.playState=0,a._onTimer(),g()):(k._stop(a.id,b),c.serverURL&&a.unload()),a.instanceCount=0,a._iO={},c.onstop&&c.onstop.apply(a));return a};this.setAutoPlay=function(b){a._iO.autoPlay=b;a.isHTML5||(k._setAutoPlay(a.id,b),b&&!a.instanceCount&&1===a.readyState&&a.instanceCount++)};this.getAutoPlay=function(){return a._iO.autoPlay};this.setPosition=function(b){b===h&&(b=0);var c=a.isHTML5?Math.max(b,0):Math.min(a.duration||a._iO.duration,Math.max(b,
+0));a.position=c;b=a.position/1E3;a._resetOnPosition(a.position);a._iO.position=c;if(a.isHTML5){if(a._a){if(a._html5_canplay){if(a._a.currentTime!==b)try{a._a.currentTime=b,(0===a.playState||a.paused)&&a._a.pause()}catch(e){}}else if(b)return a;a.paused&&a._onTimer(!0)}}else b=9===n?a.position:b,a.readyState&&2!==a.readyState&&k._setPosition(a.id,b,a.paused||!a.playState,a._iO.multiShot);return a};this.pause=function(b){if(a.paused||0===a.playState&&1!==a.readyState)return a;a.paused=!0;a.isHTML5?
+(a._setup_html5().pause(),g()):(b||b===h)&&k._pause(a.id,a._iO.multiShot);a._iO.onpause&&a._iO.onpause.apply(a);return a};this.resume=function(){var b=a._iO;if(!a.paused)return a;a.paused=!1;a.playState=1;a.isHTML5?(a._setup_html5().play(),p()):(b.isMovieStar&&!b.serverURL&&a.setPosition(a.position),k._pause(a.id,b.multiShot));!t&&b.onplay?(b.onplay.apply(a),t=!0):b.onresume&&b.onresume.apply(a);return a};this.togglePause=function(){if(0===a.playState)return a.play({position:9===n&&!a.isHTML5?a.position:
+a.position/1E3}),a;a.paused?a.resume():a.pause();return a};this.setPan=function(b,c){b===h&&(b=0);c===h&&(c=!1);a.isHTML5||k._setPan(a.id,b);a._iO.pan=b;c||(a.pan=b,a.options.pan=b);return a};this.setVolume=function(b,e){b===h&&(b=100);e===h&&(e=!1);a.isHTML5?a._a&&(c.muted&&!a.muted&&(a.muted=!0,a._a.muted=!0),a._a.volume=Math.max(0,Math.min(1,b/100))):k._setVolume(a.id,c.muted&&!a.muted||a.muted?0:b);a._iO.volume=b;e||(a.volume=b,a.options.volume=b);return a};this.mute=function(){a.muted=!0;a.isHTML5?
+a._a&&(a._a.muted=!0):k._setVolume(a.id,0);return a};this.unmute=function(){a.muted=!1;var b=a._iO.volume!==h;a.isHTML5?a._a&&(a._a.muted=!1):k._setVolume(a.id,b?a._iO.volume:a.options.volume);return a};this.toggleMute=function(){return a.muted?a.unmute():a.mute()};this.onposition=this.onPosition=function(b,c,e){m.push({position:parseInt(b,10),method:c,scope:e!==h?e:a,fired:!1});return a};this.clearOnPosition=function(a,b){var c;a=parseInt(a,10);if(isNaN(a))return!1;for(c=0;c<m.length;c++)if(a===
+m[c].position&&(!b||b===m[c].method))m[c].fired&&u--,m.splice(c,1)};this._processOnPosition=function(){var b,c;b=m.length;if(!b||!a.playState||u>=b)return!1;for(b-=1;0<=b;b--)c=m[b],!c.fired&&a.position>=c.position&&(c.fired=!0,u++,c.method.apply(c.scope,[c.position]));return!0};this._resetOnPosition=function(a){var b,c;b=m.length;if(!b)return!1;for(b-=1;0<=b;b--)c=m[b],c.fired&&a<=c.position&&(c.fired=!1,u--);return!0};y=function(){var b=a._iO,c=b.from,e=b.to,d,f;f=function(){a.clearOnPosition(e,
+f);a.stop()};d=function(){if(null!==e&&!isNaN(e))a.onPosition(e,f)};null!==c&&!isNaN(c)&&(b.position=c,b.multiShot=!1,d());return b};r=function(){var b,c=a._iO.onposition;if(c)for(b in c)if(c.hasOwnProperty(b))a.onPosition(parseInt(b,10),c[b])};x=function(){var b,c=a._iO.onposition;if(c)for(b in c)c.hasOwnProperty(b)&&a.clearOnPosition(parseInt(b,10))};p=function(){a.isHTML5&&Ra(a)};g=function(){a.isHTML5&&Sa(a)};f=function(b){b||(m=[],u=0);t=!1;a._hasTimer=null;a._a=null;a._html5_canplay=!1;a.bytesLoaded=
+null;a.bytesTotal=null;a.duration=a._iO&&a._iO.duration?a._iO.duration:null;a.durationEstimate=null;a.buffered=[];a.eqData=[];a.eqData.left=[];a.eqData.right=[];a.failures=0;a.isBuffering=!1;a.instanceOptions={};a.instanceCount=0;a.loaded=!1;a.metadata={};a.readyState=0;a.muted=!1;a.paused=!1;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.playState=0;a.position=null;a.id3={}};f();this._onTimer=function(b){var c,f=!1,l={};if(a._hasTimer||b){if(a._a&&(b||(0<a.playState||1===a.readyState)&&
+!a.paused))c=a._get_html5_duration(),c!==e&&(e=c,a.duration=c,f=!0),a.durationEstimate=a.duration,c=1E3*a._a.currentTime||0,c!==d&&(d=c,f=!0),(f||b)&&a._whileplaying(c,l,l,l,l);return f}};this._get_html5_duration=function(){var b=a._iO;return(b=a._a&&a._a.duration?1E3*a._a.duration:b&&b.duration?b.duration:null)&&!isNaN(b)&&Infinity!==b?b:null};this._apply_loop=function(a,b){a.loop=1<b?"loop":""};this._setup_html5=function(b){b=w(a._iO,b);var c=A?Ka:a._a,e=decodeURI(b.url),d;A?e===decodeURI(Ca)&&
+(d=!0):e===decodeURI(v)&&(d=!0);if(c){if(c._s)if(A)c._s&&(c._s.playState&&!d)&&c._s.stop();else if(!A&&e===decodeURI(v))return a._apply_loop(c,b.loops),c;d||(v&&f(!1),c.src=b.url,Ca=v=a.url=b.url,c._called_load=!1)}else b.autoLoad||b.autoPlay?(a._a=new Audio(b.url),a._a.load()):a._a=Ea&&10>opera.version()?new Audio(null):new Audio,c=a._a,c._called_load=!1,A&&(Ka=c);a.isHTML5=!0;a._a=c;c._s=a;l();a._apply_loop(c,b.loops);b.autoLoad||b.autoPlay?a.load():(c.autobuffer=!1,c.preload="auto");return c};
+l=function(){if(a._a._added_events)return!1;var b;a._a._added_events=!0;for(b in B)B.hasOwnProperty(b)&&a._a&&a._a.addEventListener(b,B[b],!1);return!0};L=function(){var b;a._a._added_events=!1;for(b in B)B.hasOwnProperty(b)&&a._a&&a._a.removeEventListener(b,B[b],!1)};this._onload=function(b){var c=!!b||!a.isHTML5&&8===n&&a.duration;a.loaded=c;a.readyState=c?3:2;a._onbufferchange(0);a._iO.onload&&ha(a,function(){a._iO.onload.apply(a,[c])});return!0};this._onbufferchange=function(b){if(0===a.playState||
+b&&a.isBuffering||!b&&!a.isBuffering)return!1;a.isBuffering=1===b;a._iO.onbufferchange&&a._iO.onbufferchange.apply(a,[b]);return!0};this._onsuspend=function(){a._iO.onsuspend&&a._iO.onsuspend.apply(a);return!0};this._onfailure=function(b,c,e){a.failures++;if(a._iO.onfailure&&1===a.failures)a._iO.onfailure(b,c,e)};this._onwarning=function(b,c,e){if(a._iO.onwarning)a._iO.onwarning(b,c,e)};this._onfinish=function(){var b=a._iO.onfinish;a._onbufferchange(0);a._resetOnPosition(0);a.instanceCount&&(a.instanceCount--,
+a.instanceCount||(x(),a.playState=0,a.paused=!1,a.instanceCount=0,a.instanceOptions={},a._iO={},g(),a.isHTML5&&(a.position=0)),(!a.instanceCount||a._iO.multiShotEvents)&&b&&ha(a,function(){b.apply(a)}))};this._whileloading=function(b,c,e,d){var f=a._iO;a.bytesLoaded=b;a.bytesTotal=c;a.duration=Math.floor(e);a.bufferLength=d;a.durationEstimate=!a.isHTML5&&!f.isMovieStar?f.duration?a.duration>f.duration?a.duration:f.duration:parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10):a.duration;a.isHTML5||(a.buffered=
+[{start:0,end:a.duration}]);(3!==a.readyState||a.isHTML5)&&f.whileloading&&f.whileloading.apply(a)};this._whileplaying=function(b,c,e,d,f){var l=a._iO;if(isNaN(b)||null===b)return!1;a.position=Math.max(0,b);a._processOnPosition();!a.isHTML5&&8<n&&(l.usePeakData&&(c!==h&&c)&&(a.peakData={left:c.leftPeak,right:c.rightPeak}),l.useWaveformData&&(e!==h&&e)&&(a.waveformData={left:e.split(","),right:d.split(",")}),l.useEQData&&(f!==h&&f&&f.leftEQ)&&(b=f.leftEQ.split(","),a.eqData=b,a.eqData.left=b,f.rightEQ!==
+h&&f.rightEQ&&(a.eqData.right=f.rightEQ.split(","))));1===a.playState&&(!a.isHTML5&&(8===n&&!a.position&&a.isBuffering)&&a._onbufferchange(0),l.whileplaying&&l.whileplaying.apply(a));return!0};this._oncaptiondata=function(b){a.captiondata=b;a._iO.oncaptiondata&&a._iO.oncaptiondata.apply(a,[b])};this._onmetadata=function(b,c){var e={},d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.metadata=e;console.log("updated metadata",a.metadata);a._iO.onmetadata&&a._iO.onmetadata.call(a,a.metadata)};this._onid3=
+function(b,c){var e=[],d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.id3=w(a.id3,e);a._iO.onid3&&a._iO.onid3.apply(a)};this._onconnect=function(b){b=1===b;if(a.connected=b)a.failures=0,q(a.id)&&(a.getAutoPlay()?a.play(h,a.getAutoPlay()):a._iO.autoLoad&&a.load()),a._iO.onconnect&&a._iO.onconnect.apply(a,[b])};this._ondataerror=function(b){0<a.playState&&a._iO.ondataerror&&a._iO.ondataerror.apply(a)}};va=function(){return p.body||p.getElementsByTagName("div")[0]};X=function(b){return p.getElementById(b)};
+w=function(b,e){var d=b||{},a,f;a=e===h?c.defaultOptions:e;for(f in a)a.hasOwnProperty(f)&&d[f]===h&&(d[f]="object"!==typeof a[f]||null===a[f]?a[f]:w(d[f],a[f]));return d};ha=function(b,c){!b.isHTML5&&8===n?g.setTimeout(c,0):c()};Y={onready:1,ontimeout:1,defaultOptions:1,flash9Options:1,movieStarOptions:1};oa=function(b,e){var d,a=!0,f=e!==h,l=c.setupOptions;for(d in b)if(b.hasOwnProperty(d))if("object"!==typeof b[d]||null===b[d]||b[d]instanceof Array||b[d]instanceof RegExp)f&&Y[e]!==h?c[e][d]=b[d]:
+l[d]!==h?(c.setupOptions[d]=b[d],c[d]=b[d]):Y[d]===h?a=!1:c[d]instanceof Function?c[d].apply(c,b[d]instanceof Array?b[d]:[b[d]]):c[d]=b[d];else if(Y[d]===h)a=!1;else return oa(b[d],d);return a};s=function(){function b(a){a=fb.call(a);var b=a.length;d?(a[1]="on"+a[1],3<b&&a.pop()):3===b&&a.push(!1);return a}function c(b,e){var h=b.shift(),g=[a[e]];if(d)h[g](b[0],b[1]);else h[g].apply(h,b)}var d=g.attachEvent,a={add:d?"attachEvent":"addEventListener",remove:d?"detachEvent":"removeEventListener"};return{add:function(){c(b(arguments),
+"add")},remove:function(){c(b(arguments),"remove")}}}();B={abort:r(function(){}),canplay:r(function(){var b=this._s,c;if(b._html5_canplay)return!0;b._html5_canplay=!0;b._onbufferchange(0);c=b._iO.position!==h&&!isNaN(b._iO.position)?b._iO.position/1E3:null;if(this.currentTime!==c)try{this.currentTime=c}catch(d){}b._iO._oncanplay&&b._iO._oncanplay()}),canplaythrough:r(function(){var b=this._s;b.loaded||(b._onbufferchange(0),b._whileloading(b.bytesLoaded,b.bytesTotal,b._get_html5_duration()),b._onload(!0))}),
+durationchange:r(function(){var b=this._s,c;c=b._get_html5_duration();!isNaN(c)&&c!==b.duration&&(b.durationEstimate=b.duration=c)}),ended:r(function(){this._s._onfinish()}),error:r(function(){this._s._onload(!1)}),loadeddata:r(function(){var b=this._s;!b._loaded&&!ja&&(b.duration=b._get_html5_duration())}),loadedmetadata:r(function(){}),loadstart:r(function(){this._s._onbufferchange(1)}),play:r(function(){this._s._onbufferchange(0)}),playing:r(function(){this._s._onbufferchange(0)}),progress:r(function(b){var c=
+this._s,d,a,f=0,f=b.target.buffered;d=b.loaded||0;var l=b.total||1;c.buffered=[];if(f&&f.length){d=0;for(a=f.length;d<a;d++)c.buffered.push({start:1E3*f.start(d),end:1E3*f.end(d)});f=1E3*(f.end(0)-f.start(0));d=Math.min(1,f/(1E3*b.target.duration))}isNaN(d)||(c._whileloading(d,l,c._get_html5_duration()),d&&(l&&d===l)&&B.canplaythrough.call(this,b))}),ratechange:r(function(){}),suspend:r(function(b){var c=this._s;B.progress.call(this,b);c._onsuspend()}),stalled:r(function(){}),timeupdate:r(function(){this._s._onTimer()}),
+waiting:r(function(){this._s._onbufferchange(1)})};fa=function(b){return!b||!b.type&&!b.url&&!b.serverURL?!1:b.serverURL||b.type&&W(b.type)?!1:b.type?V({type:b.type}):V({url:b.url})||c.html5Only||b.url.match(/data\:/i)};ga=function(b){var e;b&&(e=ja?"about:blank":c.html5.canPlayType("audio/wav")?"data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w\x3d\x3d":"about:blank",b.src=e,void 0!==b._called_unload&&(b._called_load=!1));A&&(Ca=null);return e};V=function(b){if(!c.useHTML5Audio||
+!c.hasHTML5)return!1;var e=b.url||null;b=b.type||null;var d=c.audioFormats,a;if(b&&c.html5[b]!==h)return c.html5[b]&&!W(b);if(!z){z=[];for(a in d)d.hasOwnProperty(a)&&(z.push(a),d[a].related&&(z=z.concat(d[a].related)));z=RegExp("\\.("+z.join("|")+")(\\?.*)?$","i")}a=e?e.toLowerCase().match(z):null;!a||!a.length?b&&(e=b.indexOf(";"),a=(-1!==e?b.substr(0,e):b).substr(6)):a=a[1];a&&c.html5[a]!==h?e=c.html5[a]&&!W(a):(b="audio/"+a,e=c.html5.canPlayType({type:b}),e=(c.html5[a]=e)&&c.html5[b]&&!W(b));
+return e};Wa=function(){function b(a){var b,d=b=!1;if(!e||"function"!==typeof e.canPlayType)return b;if(a instanceof Array){g=0;for(b=a.length;g<b;g++)if(c.html5[a[g]]||e.canPlayType(a[g]).match(c.html5Test))d=!0,c.html5[a[g]]=!0,c.flash[a[g]]=!!a[g].match(bb);b=d}else a=e&&"function"===typeof e.canPlayType?e.canPlayType(a):!1,b=!(!a||!a.match(c.html5Test));return b}if(!c.useHTML5Audio||!c.hasHTML5)return u=c.html5.usingFlash=!0,!1;var e=Audio!==h?Ea&&10>opera.version()?new Audio(null):new Audio:
+null,d,a,f={},l,g;l=c.audioFormats;for(d in l)if(l.hasOwnProperty(d)&&(a="audio/"+d,f[d]=b(l[d].type),f[a]=f[d],d.match(bb)?(c.flash[d]=!0,c.flash[a]=!0):(c.flash[d]=!1,c.flash[a]=!1),l[d]&&l[d].related))for(g=l[d].related.length-1;0<=g;g--)f["audio/"+l[d].related[g]]=f[d],c.html5[l[d].related[g]]=f[d],c.flash[l[d].related[g]]=f[d];f.canPlayType=e?b:null;c.html5=w(c.html5,f);c.html5.usingFlash=Va();u=c.html5.usingFlash;return!0};sa={};R=function(){};ba=function(b){8===n&&(1<b.loops&&b.stream)&&(b.stream=
+!1);return b};ca=function(b,c){if(b&&!b.usePolicyFile&&(b.onid3||b.usePeakData||b.useWaveformData||b.useEQData))b.usePolicyFile=!0;return b};la=function(){return!1};Pa=function(b){for(var c in b)b.hasOwnProperty(c)&&"function"===typeof b[c]&&(b[c]=la)};xa=function(b){b===h&&(b=!1);(y||b)&&c.disable(b)};Qa=function(b){var e=null;if(b)if(b.match(/\.swf(\?.*)?$/i)){if(e=b.substr(b.toLowerCase().lastIndexOf(".swf?")+4))return b}else b.lastIndexOf("/")!==b.length-1&&(b+="/");b=(b&&-1!==b.lastIndexOf("/")?
+b.substr(0,b.lastIndexOf("/")+1):"./")+c.movieURL;c.noSWFCache&&(b+="?ts\x3d"+(new Date).getTime());return b};ra=function(){n=parseInt(c.flashVersion,10);8!==n&&9!==n&&(c.flashVersion=n=8);var b=c.debugMode||c.debugFlash?"_debug.swf":".swf";c.useHTML5Audio&&(!c.html5Only&&c.audioFormats.mp4.required&&9>n)&&(c.flashVersion=n=9);c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===n?" (AS3/Flash 9)":" (AS2/Flash 8)");8<n?(c.defaultOptions=w(c.defaultOptions,c.flash9Options),c.features.buffering=
+!0,c.defaultOptions=w(c.defaultOptions,c.movieStarOptions),c.filePatterns.flash9=RegExp("\\.(mp3|"+eb.join("|")+")(\\?.*)?$","i"),c.features.movieStar=!0):c.features.movieStar=!1;c.filePattern=c.filePatterns[8!==n?"flash9":"flash8"];c.movieURL=(8===n?"soundmanager2.swf":"soundmanager2_flash9.swf").replace(".swf",b);c.features.peakData=c.features.waveformData=c.features.eqData=8<n};Oa=function(b,c){if(!k)return!1;k._setPolling(b,c)};wa=function(){};q=this.getSoundById;K=function(){var b=[];c.debugMode&&
+b.push("sm2_debug");c.debugFlash&&b.push("flash_debug");c.useHighPerformance&&b.push("high_performance");return b.join(" ")};za=function(){R("fbHandler");var b=c.getMoviePercent(),e={type:"FLASHBLOCK"};if(c.html5Only)return!1;c.ok()?c.oMC&&(c.oMC.className=[K(),"movieContainer","swf_loaded"+(c.didFlashBlock?" swf_unblocked":"")].join(" ")):(u&&(c.oMC.className=K()+" movieContainer "+(null===b?"swf_timedout":"swf_error")),c.didFlashBlock=!0,D({type:"ontimeout",ignoreInit:!0,error:e}),J(e))};pa=function(b,
+c,d){x[b]===h&&(x[b]=[]);x[b].push({method:c,scope:d||null,fired:!1})};D=function(b){b||(b={type:c.ok()?"onready":"ontimeout"});if(!m&&b&&!b.ignoreInit||"ontimeout"===b.type&&(c.ok()||y&&!b.ignoreInit))return!1;var e={success:b&&b.ignoreInit?c.ok():!y},d=b&&b.type?x[b.type]||[]:[],a=[],f,e=[e],g=u&&!c.ok();b.error&&(e[0].error=b.error);b=0;for(f=d.length;b<f;b++)!0!==d[b].fired&&a.push(d[b]);if(a.length){b=0;for(f=a.length;b<f;b++)a[b].scope?a[b].method.apply(a[b].scope,e):a[b].method.apply(this,
+e),g||(a[b].fired=!0)}return!0};H=function(){g.setTimeout(function(){c.useFlashBlock&&za();D();"function"===typeof c.onload&&c.onload.apply(g);c.waitForWindowLoad&&s.add(g,"load",H)},1)};Da=function(){if(v!==h)return v;var b=!1,c=navigator,d=c.plugins,a,f=g.ActiveXObject;if(d&&d.length)(c=c.mimeTypes)&&(c["application/x-shockwave-flash"]&&c["application/x-shockwave-flash"].enabledPlugin&&c["application/x-shockwave-flash"].enabledPlugin.description)&&(b=!0);else if(f!==h&&!t.match(/MSAppHost/i)){try{a=
+new f("ShockwaveFlash.ShockwaveFlash")}catch(l){a=null}b=!!a}return v=b};Va=function(){var b,e,d=c.audioFormats;if(ia&&t.match(/os (1|2|3_0|3_1)\s/i))c.hasHTML5=!1,c.html5Only=!0,c.oMC&&(c.oMC.style.display="none");else if(c.useHTML5Audio&&(!c.html5||!c.html5.canPlayType))c.hasHTML5=!1;if(c.useHTML5Audio&&c.hasHTML5)for(e in U=!0,d)if(d.hasOwnProperty(e)&&d[e].required)if(c.html5.canPlayType(d[e].type)){if(c.preferFlash&&(c.flash[e]||c.flash[d[e].type]))b=!0}else U=!1,b=!0;c.ignoreFlash&&(b=!1,U=
+!0);c.html5Only=c.hasHTML5&&c.useHTML5Audio&&!b;return!c.html5Only};ea=function(b){var e,d,a=0;if(b instanceof Array){e=0;for(d=b.length;e<d;e++)if(b[e]instanceof Object){if(c.canPlayMIME(b[e].type)){a=e;break}}else if(c.canPlayURL(b[e])){a=e;break}b[a].url&&(b[a]=b[a].url);b=b[a]}return b};Ra=function(b){b._hasTimer||(b._hasTimer=!0,!Fa&&c.html5PollingInterval&&(null===T&&0===da&&(T=setInterval(Ta,c.html5PollingInterval)),da++))};Sa=function(b){b._hasTimer&&(b._hasTimer=!1,!Fa&&c.html5PollingInterval&&
+da--)};Ta=function(){var b;if(null!==T&&!da)return clearInterval(T),T=null,!1;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].isHTML5&&c.sounds[c.soundIDs[b]]._hasTimer&&c.sounds[c.soundIDs[b]]._onTimer()};J=function(b){b=b!==h?b:{};"function"===typeof c.onerror&&c.onerror.apply(g,[{type:b.type!==h?b.type:null}]);b.fatal!==h&&b.fatal&&c.disable()};Xa=function(){if(!$a||!Da())return!1;var b=c.audioFormats,e,d;for(d in b)if(b.hasOwnProperty(d)&&("mp3"===d||"mp4"===d))if(c.html5[d]=!1,b[d]&&
+b[d].related)for(e=b[d].related.length-1;0<=e;e--)c.html5[b[d].related[e]]=!1};this._setSandboxType=function(b){};this._externalInterfaceOK=function(b){if(c.swfLoaded)return!1;c.swfLoaded=!0;ka=!1;$a&&Xa();setTimeout(ma,C?100:1)};aa=function(b,e){function d(a,b){return'\x3cparam name\x3d"'+a+'" value\x3d"'+b+'" /\x3e'}if(M&&N)return!1;if(c.html5Only)return ra(),c.oMC=X(c.movieID),ma(),N=M=!0,!1;var a=e||c.url,f=c.altURL||a,g=va(),k=K(),n=null,n=p.getElementsByTagName("html")[0],m,r,q,n=n&&n.dir&&
+n.dir.match(/rtl/i);b=b===h?c.id:b;ra();c.url=Qa(Ha?a:f);e=c.url;c.wmode=!c.wmode&&c.useHighPerformance?"transparent":c.wmode;if(null!==c.wmode&&(t.match(/msie 8/i)||!C&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i))Ua.push(sa.spcWmode),c.wmode=null;g={name:b,id:b,src:e,quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:cb+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",
+wmode:c.wmode,hasPriority:"true"};c.debugFlash&&(g.FlashVars="debug\x3d1");c.wmode||delete g.wmode;if(C)a=p.createElement("div"),r=['\x3cobject id\x3d"'+b+'" data\x3d"'+e+'" type\x3d"'+g.type+'" title\x3d"'+g.title+'" classid\x3d"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase\x3d"'+cb+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version\x3d6,0,40,0"\x3e',d("movie",e),d("AllowScriptAccess",c.allowScriptAccess),d("quality",g.quality),c.wmode?d("wmode",c.wmode):"",d("bgcolor",
+c.bgColor),d("hasPriority","true"),c.debugFlash?d("FlashVars",g.FlashVars):"","\x3c/object\x3e"].join("");else for(m in a=p.createElement("embed"),g)g.hasOwnProperty(m)&&a.setAttribute(m,g[m]);wa();k=K();if(g=va())if(c.oMC=X(c.movieID)||p.createElement("div"),c.oMC.id)q=c.oMC.className,c.oMC.className=(q?q+" ":"movieContainer")+(k?" "+k:""),c.oMC.appendChild(a),C&&(m=c.oMC.appendChild(p.createElement("div")),m.className="sm2-object-box",m.innerHTML=r),N=!0;else{c.oMC.id=c.movieID;c.oMC.className=
+"movieContainer "+k;m=k=null;c.useFlashBlock||(c.useHighPerformance?k={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",overflow:"hidden"}:(k={position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"},n&&(k.left=Math.abs(parseInt(k.left,10))+"px")));gb&&(c.oMC.style.zIndex=1E4);if(!c.debugFlash)for(q in k)k.hasOwnProperty(q)&&(c.oMC.style[q]=k[q]);try{C||c.oMC.appendChild(a),g.appendChild(c.oMC),C&&(m=c.oMC.appendChild(p.createElement("div")),m.className="sm2-object-box",
+m.innerHTML=r),N=!0}catch(s){throw Error(R("domError")+" \n"+s.toString());}}return M=!0};$=function(){if(c.html5Only)return aa(),!1;if(k||!c.url)return!1;k=c.getMovie(c.id);k||(Q?(C?c.oMC.innerHTML=ya:c.oMC.appendChild(Q),Q=null,M=!0):aa(c.id,c.url),k=c.getMovie(c.id));"function"===typeof c.oninitmovie&&setTimeout(c.oninitmovie,1);return!0};I=function(){setTimeout(Na,1E3)};qa=function(){g.setTimeout(function(){c.setup({preferFlash:!1}).reboot();c.didFlashBlock=!0;c.beginDelayedInit()},1)};Na=function(){var b,
+e=!1;if(!c.url||S)return!1;S=!0;s.remove(g,"load",I);if(v&&ka&&!Ga)return!1;m||(b=c.getMoviePercent(),0<b&&100>b&&(e=!0));setTimeout(function(){b=c.getMoviePercent();if(e)return S=!1,g.setTimeout(I,1),!1;!m&&ab&&(null===b?c.useFlashBlock||0===c.flashLoadTimeout?c.useFlashBlock&&za():!c.useFlashBlock&&U?qa():D({type:"ontimeout",ignoreInit:!0,error:{type:"INIT_FLASHBLOCK"}}):0!==c.flashLoadTimeout&&(!c.useFlashBlock&&U?qa():xa(!0)))},c.flashLoadTimeout)};Z=function(){if(Ga||!ka)return s.remove(g,"focus",
+Z),!0;Ga=ab=!0;S=!1;I();s.remove(g,"focus",Z);return!0};O=function(b){if(m)return!1;if(c.html5Only)return m=!0,H(),!0;var e=!0,d;if(!c.useFlashBlock||!c.flashLoadTimeout||c.getMoviePercent())m=!0;d={type:!v&&u?"NO_FLASH":"INIT_TIMEOUT"};if(y||b)c.useFlashBlock&&c.oMC&&(c.oMC.className=K()+" "+(null===c.getMoviePercent()?"swf_timedout":"swf_error")),D({type:"ontimeout",error:d,ignoreInit:!0}),J(d),e=!1;y||(c.waitForWindowLoad&&!na?s.add(g,"load",H):H());return e};Ma=function(){var b,e=c.setupOptions;
+for(b in e)e.hasOwnProperty(b)&&(c[b]===h?c[b]=e[b]:c[b]!==e[b]&&(c.setupOptions[b]=c[b]))};ma=function(){if(m)return!1;if(c.html5Only)return m||(s.remove(g,"load",c.beginDelayedInit),c.enabled=!0,O()),!0;$();try{k._externalInterfaceTest(!1),Oa(!0,c.flashPollingInterval||(c.useHighPerformance?10:50)),c.debugMode||k._disableDebug(),c.enabled=!0,c.html5Only||s.add(g,"unload",la)}catch(b){return J({type:"JS_TO_FLASH_EXCEPTION",fatal:!0}),xa(!0),O(),!1}O();s.remove(g,"load",c.beginDelayedInit);return!0};
+E=function(){if(P)return!1;P=!0;Ma();wa();!v&&c.hasHTML5&&c.setup({useHTML5Audio:!0,preferFlash:!1});Wa();!v&&u&&(Ua.push(sa.needFlash),c.setup({flashLoadTimeout:1}));p.removeEventListener&&p.removeEventListener("DOMContentLoaded",E,!1);$();return!0};Ba=function(){"complete"===p.readyState&&(E(),p.detachEvent("onreadystatechange",Ba));return!0};ua=function(){na=!0;E();s.remove(g,"load",ua)};ta=function(){if(Fa&&(c.setupOptions.useHTML5Audio=!0,c.setupOptions.preferFlash=!1,ia||Za&&!t.match(/android\s2\.3/i)))ia&&
+(c.ignoreFlash=!0),A=!0};ta();Da();s.add(g,"focus",Z);s.add(g,"load",I);s.add(g,"load",ua);p.addEventListener?p.addEventListener("DOMContentLoaded",E,!1):p.attachEvent?p.attachEvent("onreadystatechange",Ba):J({type:"NO_DOM2_EVENTS",fatal:!0})}if(!g||!g.document)throw Error("SoundManager requires a browser with window and document objects.");var F=null;if(void 0===g.SM2_DEFER||!SM2_DEFER)F=new G;"object"===typeof module&&module&&"object"===typeof module.exports?(g.soundManager=F,module.exports.SoundManager=
+G,module.exports.soundManager=F):"function"===typeof define&&define.amd?define("SoundManager",[],function(){return{SoundManager:G,soundManager:F}}):(g.SoundManager=G,g.soundManager=F)})(window);
\ No newline at end of file
diff --git a/src/index.html b/src/index.html
new file mode 100644
index 0000000..a062233
--- /dev/null
+++ b/src/index.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <script src="data/defaults.js" type="text/javascript"></script>
+ <script src="data/soundmanager2-nodebug-jsmin.js" type="text/javascript"></script>
+ <script src="data/main.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <h1>TumTaster</h1>
+ <div id="Jukebox"></div>
+ </body>
+</html>
diff --git a/src/manifest.json b/src/manifest.json
new file mode 100644
index 0000000..b1c0e72
--- /dev/null
+++ b/src/manifest.json
@@ -0,0 +1,42 @@
+{
+ "name": "TumTaster",
+ "version": "0.6.0",
+ "description": "Creates download links on Tumblr audio posts.",
+ "background": {
+ "scripts": [
+ "data/defaults.js",
+ "data/main.js",
+ "data/soundmanager2-nodebug-jsmin.js"
+ ]
+ },
+ "browser_action": {
+ "default_icon": "data/images/Icon-16.png",
+ "default_popup": "data/popup/index.html",
+ "default_title": "TumTaster"
+ },
+ "content_scripts": [ {
+ "js": [
+ "data/script.js"
+ ],
+ "matches": [
+ "http://www.tumblr.com/*",
+ "https://www.tumblr.com/*"
+ ],
+ "all_frames": true,
+ "run_at": "document_start"
+ } ],
+ "icons": {
+ "16": "data/images/Icon-16.png",
+ "32": "data/images/Icon-32.png",
+ "48": "data/images/Icon-48.png",
+ "64": "data/images/Icon-64.png",
+ "128": "data/images/Icon-128.png"
+ },
+ "manifest_version": 2,
+ "options_page": "data/options/index.html",
+ "permissions": [
+ "http://www.tumblr.com/*",
+ "https://www.tumblr.com/*",
+ "https://api.soundcloud.com/*"
+ ]
+}
\ No newline at end of file
diff --git a/src/package.json b/src/package.json
new file mode 100644
index 0000000..a912998
--- /dev/null
+++ b/src/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "tumtaster",
+ "license": "MPL 2.0",
+ "author": "Bjorn Stromberg",
+ "version": "0.6.0",
+ "fullName": "TumTaster",
+ "id": "jid1-W5guVoyeUR0uBg",
+ "description": "Creates download links on Tumblr audio posts",
+ "homepage": "http://tumtaster.bjornstar.com",
+ "icon": "data/images/Icon-48.png",
+ "icon64": "data/images/Icon-64.png",
+ "lib": "data"
+}
\ No newline at end of file
|
bjornstar/TumTaster
|
65c49f3b62ebb3c2c25042e61a02802388b9deb4
|
v0.5.0 - Kinda sorta better, tries to work with soundcloud but most soundcloud tracks don't allow downloading.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e43b0f9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.DS_Store
diff --git a/README b/README
index 50470e9..f27ffad 100644
--- a/README
+++ b/README
@@ -1,18 +1,8 @@
-TumTaster v0.4.5
+TumTaster v0.5.0 -- http://tumtaster.bjornstar.com
By Bjorn Stromberg (@bjornstar)
-This is an extension for Google Chrome that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
+TumTaster adds download links to posts and also keeps a playlist of all the tracks that you've seen. As of v0.5.0 it also tries to read soundcloud tracks. Unfortunately, most soundcloud tracks cannot be downloaded through their API.
-v0.4.5 Renamed the extension to TumTaster because Google suddenly decided they didn't like the old name and took down ChromeTaster.
-
-v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
-
-IMPORTANT: To get MP3 playback in flash to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
-
-chrome-extension:\\nanfbkacbckngfcklahdgfagjlghfbgm\
-
-I am working on switching to an HTML5 player, but it's going to take some time. In the mean time, you must add this extension to your flash allow list. And yes, you must use backslashes.
-
-ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
+TumTaster uses SoundManager2 for managing MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
TumTaster for Google Chrome can be installed here - https://chrome.google.com/webstore/detail/nanfbkacbckngfcklahdgfagjlghfbgm
\ No newline at end of file
diff --git a/data/background.js b/data/background.js
index 8342a8f..8bdea3a 100644
--- a/data/background.js
+++ b/data/background.js
@@ -1,80 +1,113 @@
-if (localStorage["settings"] == undefined) {
- settings = defaultSettings;
-} else {
- settings = JSON.parse(localStorage["settings"]);
+var API_KEY = '0b9cb426e9ffaf2af34e68ae54272549';
+
+var settings = defaultSettings;
+
+try {
+ settings = JSON.parse(localStorage["settings"]);
+} catch (e) {
+
+}
+
+var ports = {};
+var tracks = {};
+
+function addTrack(newTrack) {
+ var id = newTrack.postId;
+ var url = newTrack.streamUrl;
+
+ if (newTrack.postKey) {
+ url = url + '?play_key=' + newTrack.postKey;
+ }
+
+ if (newTrack.type === 'soundcloud') {
+ url = url + '/download?client_id=' + API_KEY;
+ }
+
+ newTrack.downloadUrl = url;
+
+ soundManager.createSound({
+ id: id,
+ url: url,
+ onloadfailed: function(){playnextsong(newTrack.postId)},
+ onfinish: function(){playnextsong(newTrack.postId)}
+ });
+
+ tracks[id] = newTrack;
+
+ broadcast({ track: newTrack });
+}
+
+function broadcast(msg) {
+ for (var portId in ports) {
+ ports[portId].postMessage(msg);
+ }
}
function messageHandler(port, message) {
if (message === 'getSettings') {
return port.postMessage({ settings: settings});
}
if (message.hasOwnProperty('track')) {
- return addTrack(message.track);
+ addTrack(message.track);
}
}
function connectHandler(port) {
+ ports[port.portId_] = port;
+
port.onMessage.addListener(function onMessageHandler(message) {
messageHandler(port, message);
});
port.postMessage({ settings: settings });
-}
-chrome.runtime.onConnect.addListener(connectHandler);
-
-function addTrack(newTrack) {
- var id = newTrack.postId;
- var url = newTrack.streamUrl + '?play_key=' + newTrack.postKey;
- var mySoundObject = soundManager.createSound({
- id: id,
- url: url,
- onloadfailed: function(){playnextsong(newTrack.postId)},
- onfinish: function(){playnextsong(newTrack.postId)}
- });
+ port.onDisconnect.addListener(function onDisconnectHandler() {
+ disconnectHandler(port);
+ });
}
-function getJukebox() {
- var jukebox = document.getElementsByTagName('audio');
- return jukebox;
+function disconnectHandler(port) {
+ delete ports[port.portId_];
}
+chrome.runtime.onConnect.addListener(connectHandler);
+
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
document.addEventListener("DOMContentLoaded", function () {
soundManager.setup({"preferFlash": false});
});
\ No newline at end of file
diff --git a/data/defaults.js b/data/defaults.js
index 8f475c6..482e50a 100644
--- a/data/defaults.js
+++ b/data/defaults.js
@@ -1,17 +1,16 @@
var defaultSettings = { //initialize default values.
'version': '0.5.0',
'shuffle': false,
'repeat': true,
- 'mp3player': 'flash',
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://*.tumblr.com/*',
'http://bjornstar.com/*'
]
};
\ No newline at end of file
diff --git a/data/options.html b/data/options.html
index 135d246..b3c9740 100644
--- a/data/options.html
+++ b/data/options.html
@@ -1,112 +1,105 @@
<html>
<head>
<title>Options for TumTaster</title>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:10px 30px 30px 10px;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
color:#4F545A;
width:640px;
}
h1{
color:black;
}
h2{
margin:0;
}
p{
margin:0;
}
a{
color:#4F545A;
text-decoration:none;
}
#content{
background: white;
display: block;
margin: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
padding-top: 5px;
width: 570px;
-webkit-border-radius: 10px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .46);
}
#repeat_div,#player_div{
margin-bottom:25px;
}
#listBlack,#listWhite{
float:left;
width:240px;
margin-bottom:25px;
}
#listSites{
clear:left;
width:540px;
}
#listSites input{
width:400px;
}
#version_div{
color:#A8B1BA;
font: 11px 'Lucida Grande',Verdana,sans-serif;
text-align:right;
}
#browser_span{
color:#A8B1BA;
font: 11px 'Lucida Grande',Verdana,sans-serif;
vertical-align:top;
}
</style>
<script src="defaults.js" type="text/javascript"></script>
<script src="options.js" type="text/javascript"></script>
</head>
<body>
<div id="content">
<img style="float:left;" src="Icon-64.png">
<h1 style="line-height:32px;height:32px;margin-top:16px;">TumTaster Options <span id="browser_span"> </span></h1>
-
+
<div id="shuffle_div">
<input type="checkbox" id="optionShuffle" name="optionShuffle" /> <label for="optionShuffle"> Shuffle</label>
</div>
<div id="repeat_div">
<input type="checkbox" id="optionRepeat" name="optionRepeat" /> <label for="optionRepeat"> Repeat</label>
</div>
- <div id="player_div">
- <label for="optionMP3Player">MP3 Player Method: </label>
- <select id="optionMP3Player" name="optionMP3Player" />
- <option value="flash">Flash</option>
- <option value="html5">HTML5</option>
- </select>
- </div>
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
<a href="#" id="listBlackAdd">add</a><br />
</div>
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
<a href="#" id="listWhiteAdd">add</a><br />
</div>
<div id="listSites">
<h2>Site List</h2>
- <p>Run ChromeTaster on these sites:</p>
+ <p>Run TumTaster on these sites:</p>
<a href="#" id="listSitesAdd">add</a><br />
</div>
<br />
<input id="save_btn" type="button" value="Save" />
<input id="reset_btn" type="button" value="Restore default" />
<div id="version_div"> </div>
</div>
</body>
</html>
\ No newline at end of file
diff --git a/data/options.js b/data/options.js
index e34f66f..7b75a51 100644
--- a/data/options.js
+++ b/data/options.js
@@ -1,156 +1,144 @@
document.addEventListener("DOMContentLoaded", function () {
var save_btn = document.getElementById("save_btn");
var reset_btn = document.getElementById("reset_btn");
var listWhiteAdd = document.getElementById("listWhiteAdd");
var listBlackAdd = document.getElementById("listBlackAdd");
var listSitesAdd = document.getElementById("listSitesAdd");
save_btn.addEventListener("click", saveOptions);
reset_btn.addEventListener("click", function() { if (confirm("Are you sure you want to restore defaults?")) {eraseOptions()} });
listWhiteAdd.addEventListener("click", function(e) {
addInput("White");
e.preventDefault();
e.stopPropagation();
}, false);
listBlackAdd.addEventListener("click", function(e) {
addInput("Black");
e.preventDefault();
e.stopPropagation();
}, false);
listSitesAdd.addEventListener("click", function(e) {
addInput("Sites");
e.preventDefault();
e.stopPropagation();
}, false);
loadOptions();
});
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
var cbShuffle = document.getElementById("optionShuffle");
cbShuffle.checked = settings['shuffle'];
-
+
var cbRepeat = document.getElementById("optionRepeat");
cbRepeat.checked = settings['repeat'];
- var select = document.getElementById("optionMP3Player");
- for (var i = 0; i < select.children.length; i++) {
- var child = select.children[i];
- if (child.value == settings['mp3player']) {
- child.selected = "true";
- break;
- }
- }
-
for (var itemBlack in settings['listBlack']) {
addInput("Black", settings['listBlack'][itemBlack]);
}
-
+
for (var itemWhite in settings['listWhite']) {
addInput("White", settings['listWhite'][itemWhite]);
}
-
+
for (var itemSites in settings['listSites']) {
addInput("Sites", settings['listSites'][itemSites]);
}
-
+
addInput("Black"); //prepare a blank input box.
addInput("White"); //prepare a blank input box.
addInput("Sites"); //prepare a blank input box.
var version_div = document.getElementById('version_div');
version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
if (typeof opera != 'undefined') {
var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = "for Opera™";
}
-
+
if (typeof chrome != 'undefined') {
var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Chrome™";
+ browser_span.innerHTML = "for Chrome™";
}
-
+
if (typeof safari != 'undefined') {
var browser_span = document.getElementById('browser_span');
browser_span.innerHTML = "for Safari™";
}
}
function addInput(whichList, itemValue) {
if (itemValue == undefined) {
itemValue = "";
}
var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
var listDiv = document.getElementById('list'+whichList);
var listAdd = document.getElementById('list'+whichList+'Add');
garbageInput = document.createElement('input');
garbageInput.value = itemValue;
garbageInput.name = 'option'+whichList;
garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
garbageAdd = document.createElement('a');
garbageAdd.href = "#";
garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
garbageAdd.innerHTML = '<img src="'+PNGremove+'" /> ';
garbageLinebreak = document.createElement('br');
listDiv.insertBefore(garbageAdd,listAdd);
listDiv.insertBefore(garbageInput,listAdd);
listDiv.insertBefore(garbageLinebreak,listAdd);
}
function removeInput(garbageWhich) {
var garbageInput = document.getElementById(garbageWhich);
garbageInput.parentNode.removeChild(garbageInput.previousSibling);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
var settings = {};
var cbShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = cbShuffle.checked;
-
+
var cbRepeat = document.getElementById('optionRepeat');
settings['repeat'] = cbRepeat.checked;
-
- var selectMP3Player = document.getElementById('optionMP3Player');
- settings['mp3player'] = selectMP3Player.children[selectMP3Player.selectedIndex].value;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != "") {
if (garbages[i].name.substring(0,11) == "optionWhite") {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionBlack") {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionSites") {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
diff --git a/data/popup.html b/data/popup.html
index 983ca5f..ef34cca 100644
--- a/data/popup.html
+++ b/data/popup.html
@@ -1,195 +1,195 @@
<html>
<head>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
min-width:400px;
}
h1{
color:black;
}
a{
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
#heading {
width:100%;
height:64px;
}
#heading h1{
color: white;
float: left;
line-height:32px;
vertical-align:absmiddle;
margin-left:10px;
}
div#statistics{
position:absolute;
bottom:0%;
}
#controls{
text-align:center;
}
#statusbar{
position:relative;
height:12px;
background-color:#CDD568;
border:2px solid #eaf839;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
overflow:hidden;
margin-top:4px;
}
.remove{
position:absolute;
right:8px;
top:8px;
}
.position, .position2, .loading{
position:absolute;
left:0px;
bottom:0px;
height:12px;
}
.position{
background-color: #3B440F;
border-right:2px solid #3B440F;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
width:20px;
}
.position2{
background-color:#eaf839;
}
.loading {
background-color:#BBC552;
}
</style>
<script src="popup.js" type="text/javascript"></script>
</head>
<body>
<div id="heading"><img src="Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
<div id="statistics"><span> </span></div>
-<div id="nowplayingdiv"><span>Now Playing: </span><span id="nowplaying"> </span>
+<div id="nowplayingdiv"><span id="nowplaying"> </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
<p id="controls">
<a id="stop" href="#">■</a>
<a id="pause" href="#">❙ ❙</a>
<a id="play" href="#">▶</a>
<a id="next" href="#">▶▶</a>
<a id="random" href="#">Random</a></p>
<ol id="playlist" class="playlist">
</ol>
</body>
</html>
\ No newline at end of file
diff --git a/data/popup.js b/data/popup.js
index 7e928af..06f9e59 100644
--- a/data/popup.js
+++ b/data/popup.js
@@ -1,153 +1,169 @@
var bg = chrome.extension.getBackgroundPage();
+var tracks = bg.tracks;
var sm = bg.soundManager;
var div_loading, div_position, div_position2, nowplaying;
-document.addEventListener("DOMContentLoaded", function () {
- var stopLink = document.getElementById("stop");
- var pauseLink = document.getElementById("pause");
- var playLink = document.getElementById("play");
- var nextLink = document.getElementById("next");
- var randomLink = document.getElementById("random");
-
- stopLink.addEventListener("click", function(e) {
- sm.stopAll();
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- pauseLink.addEventListener("click", function(e) {
- pause();
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- playLink.addEventListener("click", function(e) {
- sm.resumeAll();
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- nextLink.addEventListener("click", function(e) {
- playnextsong();
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- randomLink.addEventListener("click", function(e) {
- playrandomsong();
- e.preventDefault();
- e.stopPropagation();
- }, false);
-
- div_loading = document.getElementById('loading');
- div_position = document.getElementById('position');
- div_position2 = document.getElementById('position2');
- nowplaying = document.getElementById('nowplaying');
-
- var playlist = document.getElementById("playlist");
-
- var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
-
- setInterval(updateStatus, 200);
- var pl = sm.sounds;
- for (x in pl) {
- var liSong = document.createElement('li');
- var aSong = document.createElement('a');
- aSong.id = pl[x].sID;
- aSong.addEventListener("click", function(e) {
- play(null, e.target.id);
- e.preventDefault();
- e.stopPropagation();
- }, false);
- aSong.href = "#";
- aSong.textContent = pl[x].sID;
- var aRemove = document.createElement('a');
- aRemove.className = "remove";
- aRemove.href = "#";
- aRemove.addEventListener("click", function(e) {
- console.log(e.target.parentNode.previousSibling.id);
- remove(e.target.parentNode.previousSibling.id);
- e.preventDefault();
- e.stopPropagation();
- }, false);
- var imgRemove = document.createElement('img');
- imgRemove.src = PNGremove;
- aRemove.appendChild(imgRemove);
- liSong.appendChild(aSong);
- liSong.appendChild(aRemove);
- playlist.appendChild(liSong);
- }
+document.addEventListener('DOMContentLoaded', function () {
+ var stopLink = document.getElementById('stop');
+ var pauseLink = document.getElementById('pause');
+ var playLink = document.getElementById('play');
+ var nextLink = document.getElementById('next');
+ var randomLink = document.getElementById('random');
+
+ stopLink.addEventListener('click', function(e) {
+ sm.stopAll();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ pauseLink.addEventListener('click', function(e) {
+ pause();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ playLink.addEventListener('click', function(e) {
+ sm.resumeAll();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ nextLink.addEventListener('click', function(e) {
+ playnextsong();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ randomLink.addEventListener('click', function(e) {
+ playrandomsong();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ div_loading = document.getElementById('loading');
+ div_position = document.getElementById('position');
+ div_position2 = document.getElementById('position2');
+ nowplaying = document.getElementById('nowplaying');
+
+ var playlist = document.getElementById('playlist');
+
+ var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
+
+ setInterval(updateStatus, 200);
+
+ for (var id in tracks) {
+ var track = tracks[id];
+
+ var liSong = document.createElement('li');
+ var aSong = document.createElement('a');
+
+ aSong.id = id;
+ aSong.addEventListener('click', function(e) {
+ play(null, e.target.id);
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+ aSong.href = '#';
+
+ var trackDisplay = id;
+ if (track.artist && track.track) {
+ trackDisplay = track.artist + ' - ' + track.track;
+ }
+
+ aSong.textContent = trackDisplay;
+
+ var aRemove = document.createElement('a');
+ aRemove.className = 'remove';
+ aRemove.href = '#';
+ aRemove.addEventListener('click', function(e) {
+ remove(e.target.parentNode.previousSibling.id);
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ var imgRemove = document.createElement('img');
+ imgRemove.src = PNGremove;
+
+ aRemove.appendChild(imgRemove);
+ liSong.appendChild(aSong);
+ liSong.appendChild(aRemove);
+ playlist.appendChild(liSong);
+ }
});
function remove(song_id) {
sm.destroySound(song_id);
var song_li = document.getElementById(song_id);
song_li.parentNode.parentNode.removeChild(song_li.parentNode);
}
function pause() {
- track = getPlaying();
- track.pause();
+ track = getPlaying();
+ track.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var sound = sm.getSoundById(post_url);
sound.play();
}
function getPlaying() {
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1) {
return sm.sounds[sound];
}
}
}
function playnextsong() {
var track = getPlaying();
var track_sID;
if (track) {
track.stop();
track_sID = track.sID;
}
bg.playnextsong(track_sID);
}
function playrandomsong() {
var current_song = getPlaying();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
}
function updateStatus() {
var track = getPlaying();
if (track) {
var bytesLoaded = track.bytesLoaded;
var bytesTotal = track.bytesTotal;
var position = track.position;
var durationEstimate = track.durationEstimate;
if (bytesTotal) {
div_loading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
}
div_position.style.left = (100 * position / durationEstimate) + '%';
div_position2.style.width = (100 * position / durationEstimate) + '%';
}
if (track && nowplaying.textContent !== track.id) {
- nowplaying.textContent = track.id;
+ var trackDisplay = track.id;
+ if (tracks[track.id].artist && tracks[track.id].track) {
+ trackDisplay = tracks[track.id].artist + ' - ' + tracks[track.id].track;
+ }
+ nowplaying.textContent = trackDisplay;
}
}
\ No newline at end of file
diff --git a/data/script.js b/data/script.js
index 17eaa93..13ea42f 100644
--- a/data/script.js
+++ b/data/script.js
@@ -1,233 +1,250 @@
-// TumTaster v0.5.0
+// TumTaster v0.5.0 -- http://tumtaster.bjornstar.com
// - By Bjorn Stromberg (@bjornstar)
var settings, started;
+function addLink(track) {
+ var post = document.getElementById('post_' + track.postId);
+ if (!post) {
+ return;
+ }
+
+ var footer = post.querySelector('.post_footer');
+ if (footer) {
+ var divDownload = document.createElement('DIV');
+ divDownload.className = 'tumtaster';
+ var aDownload = document.createElement('A');
+ aDownload.href = track.downloadUrl;
+ aDownload.textContent = 'Download';
+ divDownload.appendChild(aDownload);
+ footer.insertBefore(divDownload, footer.children[1]);
+ }
+}
+
function messageHandler(message) {
if (message.hasOwnProperty('settings')) {
settings = message.settings;
startTasting();
}
if (message.hasOwnProperty('track')) {
- console.log(message.track);
+ addLink(message.track);
}
}
var port = chrome.runtime.connect();
port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var tracks = {};
function makeTumblrLink(dataset) {
var postId = dataset.postId;
tracks[postId] = {
postId: postId,
streamUrl: dataset.streamUrl,
postKey: dataset.postKey,
artist: dataset.artist,
- track: dataset.track
+ track: dataset.track,
+ type: 'tumblr'
};
port.postMessage({ track: tracks[postId] });
}
function makeSoundCloudLink(dataset, url) {
var qs = url.split('?')[1];
var chunks = qs.split('&');
var url;
for (var i = 0; i < chunks.length; i += 1) {
if (chunks[i].indexOf('url=') === 0) {
url = decodeURIComponent(chunks[i].substring(4));
break;
}
}
- console.log(url + '/download?client_id=0b9cb426e9ffaf2af34e68ae54272549');
+ var postId = dataset.postId;
+
+ tracks[postId] = {
+ postId: postId,
+ streamUrl: url,
+ type: 'soundcloud'
+ };
+
+ port.postMessage({ track: tracks[postId] });
}
function extractAudioData(post) {
var postId = post.dataset.postId;
if (!postId || tracks[postId]) {
- console.log('no post, or we already have it.')
return;
}
- if (!post.dataset.streamUrl) {
- var soundcloud = post.querySelector('.soundcloud_audio_player');
-
- if (soundcloud) {
- return makeSoundCloudLink(post.dataset, soundcloud.src);
- }
+ var soundcloud = post.querySelector('.soundcloud_audio_player');
- console.log('no streamUrl')
- return;
+ if (soundcloud) {
+ return makeSoundCloudLink(post.dataset, soundcloud.src);
}
- if (!post.dataset.dataPostKey) {
- console.log('no postkey')
- return;
- }
+ var tumblr = post.querySelector('.audio_player_container');
- makeTumblrLink(post.dataset);
+ if (tumblr) {
+ return makeTumblrLink(tumblr.dataset);
+ }
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target);
}
function snarfAudioPlayers(t) {
var audioPosts = t.querySelectorAll('.post.is_audio');
for (var i = 0; i < audioPosts.length; i += 1) {
var audioPost = audioPosts[i];
extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
- var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
- var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
var cssRules = [];
- cssRules.push('a.tumtaster: {ã' + tumtaster_style + ' }');
+ cssRules.push('.tumtaster { float: left; padding-right: 10px; }');
+ cssRules.push('.tumtaster a { text-decoration: none; color: #a7a7a7; }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
cssRules[0] = "@keyframes nodeInserted {";
cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[0] += "}";
cssRules[1] = "@-moz-keyframes nodeInserted {";
cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[1] += "}";
cssRules[2] = "@-webkit-keyframes nodeInserted {";
cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[2] += "}";
cssRules[3] = "@-ms-keyframes nodeInserted {";
cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[3] += "}";
cssRules[4] = "@-o-keyframes nodeInserted {";
cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[4] += "}";
cssRules[5] = "ol#posts li {";
cssRules[5] += " animation-duration: 1ms;";
cssRules[5] += " -o-animation-duration: 1ms;";
cssRules[5] += " -ms-animation-duration: 1ms;";
cssRules[5] += " -moz-animation-duration: 1ms;";
cssRules[5] += " -webkit-animation-duration: 1ms;";
cssRules[5] += " animation-name: nodeInserted;";
cssRules[5] += " -o-animation-name: nodeInserted;";
cssRules[5] += " -ms-animation-name: nodeInserted;";
cssRules[5] += " -moz-animation-name: nodeInserted;";
cssRules[5] += " -webkit-animation-name: nodeInserted;";
cssRules[5] += "}";
addGlobalStyle("wires", cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
// 2013-12-29: Today's soundcloud audio url
// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
function startTasting() {
if (document.readyState === 'loading' || !settings || started) {
return;
}
started = true;
if (!checkurl(location.href, settings['listSites'])) {
- console.log('not checking', location.href)
+ port.disconnect();
return;
}
- console.log('Now tasting', location.href);
-
addTumtasterStyle();
wireupnodes();
snarfAudioPlayers(document);
}
document.addEventListener("DOMContentLoaded", startTasting);
startTasting();
\ No newline at end of file
diff --git a/data/soundmanager2.js b/data/soundmanager2.js
index 455df4f..dcf7402 100644
--- a/data/soundmanager2.js
+++ b/data/soundmanager2.js
@@ -1,5466 +1,81 @@
/** @license
*
* SoundManager 2: JavaScript Sound for the Web
* ----------------------------------------------
* http://schillmania.com/projects/soundmanager2/
*
* Copyright (c) 2007, Scott Schiller. All rights reserved.
* Code provided under the BSD License:
* http://schillmania.com/projects/soundmanager2/license.txt
*
- * V2.97a.20120624
+ * V2.97a.20131201
*/
-
-/*global window, SM2_DEFER, sm2Debugger, console, document, navigator, setTimeout, setInterval, clearInterval, Audio */
-/*jslint regexp: true, sloppy: true, white: true, nomen: true, plusplus: true */
-
-/**
- * About this file
- * ---------------
- * This is the fully-commented source version of the SoundManager 2 API,
- * recommended for use during development and testing.
- *
- * See soundmanager2-nodebug-jsmin.js for an optimized build (~10KB with gzip.)
- * http://schillmania.com/projects/soundmanager2/doc/getstarted/#basic-inclusion
- * Alternately, serve this file with gzip for 75% compression savings (~30KB over HTTP.)
- *
- * You may notice <d> and </d> comments in this source; these are delimiters for
- * debug blocks which are removed in the -nodebug builds, further optimizing code size.
- *
- * Also, as you may note: Whoa, reliable cross-platform/device audio support is hard! ;)
- */
-
-(function(window) {
-
-var soundManager = null;
-
-/**
- * The SoundManager constructor.
- *
- * @constructor
- * @param {string} smURL Optional: Path to SWF files
- * @param {string} smID Optional: The ID to use for the SWF container element
- * @this {SoundManager}
- * @return {SoundManager} The new SoundManager instance
- */
-
-function SoundManager(smURL, smID) {
-
- /**
- * soundManager configuration options list
- * defines top-level configuration properties to be applied to the soundManager instance (eg. soundManager.flashVersion)
- * to set these properties, use the setup() method - eg., soundManager.setup({url: '/swf/', flashVersion: 9})
- */
-
- this.setupOptions = {
-
- 'url': (smURL || null), // path (directory) where SoundManager 2 SWFs exist, eg., /path/to/swfs/
- 'flashVersion': 8, // flash build to use (8 or 9.) Some API features require 9.
- 'debugMode': true, // enable debugging output (console.log() with HTML fallback)
- 'debugFlash': false, // enable debugging output inside SWF, troubleshoot Flash/browser issues
- 'useConsole': true, // use console.log() if available (otherwise, writes to #soundmanager-debug element)
- 'consoleOnly': true, // if console is being used, do not create/write to #soundmanager-debug
- 'waitForWindowLoad': false, // force SM2 to wait for window.onload() before trying to call soundManager.onload()
- 'bgColor': '#ffffff', // SWF background color. N/A when wmode = 'transparent'
- 'useHighPerformance': false, // position:fixed flash movie can help increase js/flash speed, minimize lag
- 'flashPollingInterval': null, // msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used.
- 'html5PollingInterval': null, // msec affecting whileplaying() for HTML5 audio, excluding mobile devices. If null, native HTML5 update events are used.
- 'flashLoadTimeout': 1000, // msec to wait for flash movie to load before failing (0 = infinity)
- 'wmode': null, // flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index to work)
- 'allowScriptAccess': 'always', // for scripting the SWF (object/embed property), 'always' or 'sameDomain'
- 'useFlashBlock': false, // *requires flashblock.css, see demos* - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable.
- 'useHTML5Audio': true, // use HTML5 Audio() where API is supported (most Safari, Chrome versions), Firefox (no MP3/MP4.) Ideally, transparent vs. Flash API where possible.
- 'html5Test': /^(probably|maybe)$/i, // HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative.
- 'preferFlash': false, // overrides useHTML5audio. if true and flash support present, will try to use flash for MP3/MP4 as needed since HTML5 audio support is still quirky in browsers.
- 'noSWFCache': false // if true, appends ?ts={date} to break aggressive SWF caching.
-
- };
-
- this.defaultOptions = {
-
- /**
- * the default configuration for sound objects made with createSound() and related methods
- * eg., volume, auto-load behaviour and so forth
- */
-
- 'autoLoad': false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can)
- 'autoPlay': false, // enable playing of file as soon as possible (much faster if "stream" is true)
- 'from': null, // position to start playback within a sound (msec), default = beginning
- 'loops': 1, // how many times to repeat the sound (position will wrap around to 0, setPosition() will break out of loop when >0)
- 'onid3': null, // callback function for "ID3 data is added/available"
- 'onload': null, // callback function for "load finished"
- 'whileloading': null, // callback function for "download progress update" (X of Y bytes received)
- 'onplay': null, // callback for "play" start
- 'onpause': null, // callback for "pause"
- 'onresume': null, // callback for "resume" (pause toggle)
- 'whileplaying': null, // callback during play (position update)
- 'onposition': null, // object containing times and function callbacks for positions of interest
- 'onstop': null, // callback for "user stop"
- 'onfailure': null, // callback function for when playing fails
- 'onfinish': null, // callback function for "sound finished playing"
- 'multiShot': true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time
- 'multiShotEvents': false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled
- 'position': null, // offset (milliseconds) to seek to within loaded sound data.
- 'pan': 0, // "pan" settings, left-to-right, -100 to 100
- 'stream': true, // allows playing before entire file has loaded (recommended)
- 'to': null, // position to end playback within a sound (msec), default = end
- 'type': null, // MIME-like hint for file pattern / canPlay() tests, eg. audio/mp3
- 'usePolicyFile': false, // enable crossdomain.xml request for audio on remote domains (for ID3/waveform access)
- 'volume': 100 // self-explanatory. 0-100, the latter being the max.
-
- };
-
- this.flash9Options = {
-
- /**
- * flash 9-only options,
- * merged into defaultOptions if flash 9 is being used
- */
-
- 'isMovieStar': null, // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
- 'usePeakData': false, // enable left/right channel peak (level) data
- 'useWaveformData': false, // enable sound spectrum (raw waveform data) - NOTE: May increase CPU load.
- 'useEQData': false, // enable sound EQ (frequency spectrum data) - NOTE: May increase CPU load.
- 'onbufferchange': null, // callback for "isBuffering" property change
- 'ondataerror': null // callback for waveform/eq data access error (flash playing audio in other tabs/domains)
-
- };
-
- this.movieStarOptions = {
-
- /**
- * flash 9.0r115+ MPEG4 audio options,
- * merged into defaultOptions if flash 9+movieStar mode is enabled
- */
-
- 'bufferTime': 3, // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try increasing.)
- 'serverURL': null, // rtmp: FMS or FMIS server to connect to, required when requesting media via RTMP or one of its variants
- 'onconnect': null, // rtmp: callback for connection to flash media server
- 'duration': null // rtmp: song duration (msec)
-
- };
-
- this.audioFormats = {
-
- /**
- * determines HTML5 support + flash requirements.
- * if no support (via flash and/or HTML5) for a "required" format, SM2 will fail to start.
- * flash fallback is used for MP3 or MP4 if HTML5 can't play it (or if preferFlash = true)
- * multiple MIME types may be tested while trying to get a positive canPlayType() response.
- */
-
- 'mp3': {
- 'type': ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'],
- 'required': true
- },
-
- 'mp4': {
- 'related': ['aac','m4a'], // additional formats under the MP4 container
- 'type': ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'],
- 'required': false
- },
-
- 'ogg': {
- 'type': ['audio/ogg; codecs=vorbis'],
- 'required': false
- },
-
- 'wav': {
- 'type': ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'],
- 'required': false
- }
-
- };
-
- // HTML attributes (id + class names) for the SWF container
-
- this.movieID = 'sm2-container';
- this.id = (smID || 'sm2movie');
-
- this.debugID = 'soundmanager-debug';
- this.debugURLParam = /([#?&])debug=1/i;
-
- // dynamic attributes
-
- this.versionNumber = 'V2.97a.20120624';
- this.version = null;
- this.movieURL = null;
- this.altURL = null;
- this.swfLoaded = false;
- this.enabled = false;
- this.oMC = null;
- this.sounds = {};
- this.soundIDs = [];
- this.muted = false;
- this.didFlashBlock = false;
- this.filePattern = null;
-
- this.filePatterns = {
-
- 'flash8': /\.mp3(\?.*)?$/i,
- 'flash9': /\.mp3(\?.*)?$/i
-
- };
-
- // support indicators, set at init
-
- this.features = {
-
- 'buffering': false,
- 'peakData': false,
- 'waveformData': false,
- 'eqData': false,
- 'movieStar': false
-
- };
-
- // flash sandbox info, used primarily in troubleshooting
-
- this.sandbox = {
-
- // <d>
- 'type': null,
- 'types': {
- 'remote': 'remote (domain-based) rules',
- 'localWithFile': 'local with file access (no internet access)',
- 'localWithNetwork': 'local with network (internet access only, no local access)',
- 'localTrusted': 'local, trusted (local+internet access)'
- },
- 'description': null,
- 'noRemote': null,
- 'noLocal': null
- // </d>
-
- };
-
- /**
- * basic HTML5 Audio() support test
- * try...catch because of IE 9 "not implemented" nonsense
- * https://github.com/Modernizr/Modernizr/issues/224
- */
-
- this.hasHTML5 = (function() {
- try {
- return (typeof Audio !== 'undefined' && typeof new Audio().canPlayType !== 'undefined');
- } catch(e) {
- return false;
- }
- }());
-
- /**
- * format support (html5/flash)
- * stores canPlayType() results based on audioFormats.
- * eg. { mp3: boolean, mp4: boolean }
- * treat as read-only.
- */
-
- this.html5 = {
- 'usingFlash': null // set if/when flash fallback is needed
- };
-
- // file type support hash
- this.flash = {};
-
- // determined at init time
- this.html5Only = false;
-
- // used for special cases (eg. iPad/iPhone/palm OS?)
- this.ignoreFlash = false;
-
- /**
- * a few private internals (OK, a lot. :D)
- */
-
- var SMSound,
- _s = this, _flash = null, _sm = 'soundManager', _smc = _sm+'::', _h5 = 'HTML5::', _id, _ua = navigator.userAgent, _win = window, _wl = _win.location.href.toString(), _doc = document, _doNothing, _setProperties, _init, _fV, _on_queue = [], _debugOpen = true, _debugTS, _didAppend = false, _appendSuccess = false, _didInit = false, _disabled = false, _windowLoaded = false, _wDS, _wdCount = 0, _initComplete, _mixin, _assign, _extraOptions, _addOnEvent, _processOnEvents, _initUserOnload, _delayWaitForEI, _waitForEI, _setVersionInfo, _handleFocus, _strings, _initMovie, _domContentLoaded, _winOnLoad, _didDCLoaded, _getDocument, _createMovie, _catchError, _setPolling, _initDebug, _debugLevels = ['log', 'info', 'warn', 'error'], _defaultFlashVersion = 8, _disableObject, _failSafely, _normalizeMovieURL, _oRemoved = null, _oRemovedHTML = null, _str, _flashBlockHandler, _getSWFCSS, _swfCSS, _toggleDebug, _loopFix, _policyFix, _complain, _idCheck, _waitingForEI = false, _initPending = false, _startTimer, _stopTimer, _timerExecute, _h5TimerCount = 0, _h5IntervalTimer = null, _parseURL,
- _needsFlash = null, _featureCheck, _html5OK, _html5CanPlay, _html5Ext, _html5Unload, _domContentLoadedIE, _testHTML5, _event, _slice = Array.prototype.slice, _useGlobalHTML5Audio = false, _hasFlash, _detectFlash, _badSafariFix, _html5_events, _showSupport,
- _is_iDevice = _ua.match(/(ipad|iphone|ipod)/i), _isIE = _ua.match(/msie/i), _isWebkit = _ua.match(/webkit/i), _isSafari = (_ua.match(/safari/i) && !_ua.match(/chrome/i)), _isOpera = (_ua.match(/opera/i)),
- _mobileHTML5 = (_ua.match(/(mobile|pre\/|xoom)/i) || _is_iDevice),
- _isBadSafari = (!_wl.match(/usehtml5audio/i) && !_wl.match(/sm2\-ignorebadua/i) && _isSafari && !_ua.match(/silk/i) && _ua.match(/OS X 10_6_([3-7])/i)), // Safari 4 and 5 (excluding Kindle Fire, "Silk") occasionally fail to load/play HTML5 audio on Snow Leopard 10.6.3 through 10.6.7 due to bug(s) in QuickTime X and/or other underlying frameworks. :/ Confirmed bug. https://bugs.webkit.org/show_bug.cgi?id=32159
- _hasConsole = (typeof console !== 'undefined' && typeof console.log !== 'undefined'), _isFocused = (typeof _doc.hasFocus !== 'undefined'?_doc.hasFocus():null), _tryInitOnFocus = (_isSafari && (typeof _doc.hasFocus === 'undefined' || !_doc.hasFocus())), _okToDisable = !_tryInitOnFocus, _flashMIME = /(mp3|mp4|mpa|m4a)/i,
- _emptyURL = 'about:blank', // safe URL to unload, or load nothing from (flash 8 + most HTML5 UAs)
- _overHTTP = (_doc.location?_doc.location.protocol.match(/http/i):null),
- _http = (!_overHTTP ? 'http:/'+'/' : ''),
- // mp3, mp4, aac etc.
- _netStreamMimeTypes = /^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|mp4v|3gp|3g2)\s*(?:$|;)/i,
- // Flash v9.0r115+ "moviestar" formats
- _netStreamTypes = ['mpeg4', 'aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'mp4v', '3gp', '3g2'],
- _netStreamPattern = new RegExp('\\.(' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i');
-
- this.mimePattern = /^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i; // default mp3 set
-
- // use altURL if not "online"
- this.useAltURL = !_overHTTP;
-
- this._global_a = null;
-
- _swfCSS = {
-
- 'swfBox': 'sm2-object-box',
- 'swfDefault': 'movieContainer',
- 'swfError': 'swf_error', // SWF loaded, but SM2 couldn't start (other error)
- 'swfTimedout': 'swf_timedout',
- 'swfLoaded': 'swf_loaded',
- 'swfUnblocked': 'swf_unblocked', // or loaded OK
- 'sm2Debug': 'sm2_debug',
- 'highPerf': 'high_performance',
- 'flashDebug': 'flash_debug'
-
- };
-
- if (_mobileHTML5) {
-
- // prefer HTML5 for mobile + tablet-like devices, probably more reliable vs. flash at this point.
- _s.useHTML5Audio = true;
- _s.preferFlash = false;
-
- if (_is_iDevice) {
- // by default, use global feature. iOS onfinish() -> next may fail otherwise.
- _s.ignoreFlash = true;
- _useGlobalHTML5Audio = true;
- }
-
- }
-
- /**
- * Public SoundManager API
- * -----------------------
- */
-
- /**
- * Configures top-level soundManager properties.
- *
- * @param {object} options Option parameters, eg. { flashVersion: 9, url: '/path/to/swfs/' }
- * onready and ontimeout are also accepted parameters. call soundManager.setup() to see the full list.
- */
-
- this.setup = function(options) {
-
- // warn if flash options have already been applied
-
- if (typeof options !== 'undefined' && _didInit && _needsFlash && _s.ok() && (typeof options.flashVersion !== 'undefined' || typeof options.url !== 'undefined')) {
- _complain(_str('setupLate'));
- }
-
- // TODO: defer: true?
-
- _assign(options);
-
- return _s;
-
- };
-
- this.ok = function() {
-
- return (_needsFlash?(_didInit && !_disabled):(_s.useHTML5Audio && _s.hasHTML5));
-
- };
-
- this.supported = this.ok; // legacy
-
- this.getMovie = function(smID) {
-
- // safety net: some old browsers differ on SWF references, possibly related to ExternalInterface / flash version
- return _id(smID) || _doc[smID] || _win[smID];
-
- };
-
- /**
- * Creates a SMSound sound object instance.
- *
- * @param {object} oOptions Sound options (at minimum, id and url parameters are required.)
- * @return {object} SMSound The new SMSound object.
- */
-
- this.createSound = function(oOptions, _url) {
-
- var _cs, _cs_string, thisOptions = null, oSound = null, _tO = null;
-
- // <d>
- _cs = _sm+'.createSound(): ';
- _cs_string = _cs + _str(!_didInit?'notReady':'notOK');
- // </d>
-
- if (!_didInit || !_s.ok()) {
- _complain(_cs_string);
- return false;
- }
-
- if (typeof _url !== 'undefined') {
- // function overloading in JS! :) ..assume simple createSound(id,url) use case
- oOptions = {
- 'id': oOptions,
- 'url': _url
- };
- }
-
- // inherit from defaultOptions
- thisOptions = _mixin(oOptions);
-
- thisOptions.url = _parseURL(thisOptions.url);
-
- // local shortcut
- _tO = thisOptions;
-
- // <d>
- if (_tO.id.toString().charAt(0).match(/^[0-9]$/)) {
- _s._wD(_cs + _str('badID', _tO.id), 2);
- }
-
- _s._wD(_cs + _tO.id + ' (' + _tO.url + ')', 1);
- // </d>
-
- if (_idCheck(_tO.id, true)) {
- _s._wD(_cs + _tO.id + ' exists', 1);
- return _s.sounds[_tO.id];
- }
-
- function make() {
-
- thisOptions = _loopFix(thisOptions);
- _s.sounds[_tO.id] = new SMSound(_tO);
- _s.soundIDs.push(_tO.id);
- return _s.sounds[_tO.id];
-
- }
-
- if (_html5OK(_tO)) {
-
- oSound = make();
- _s._wD('Creating sound '+_tO.id+', using HTML5');
- oSound._setup_html5(_tO);
-
- } else {
-
- if (_fV > 8) {
- if (_tO.isMovieStar === null) {
- // attempt to detect MPEG-4 formats
- _tO.isMovieStar = !!(_tO.serverURL || (_tO.type ? _tO.type.match(_netStreamMimeTypes) : false) || _tO.url.match(_netStreamPattern));
- }
- // <d>
- if (_tO.isMovieStar) {
- _s._wD(_cs + 'using MovieStar handling');
- if (_tO.loops > 1) {
- _wDS('noNSLoop');
- }
- }
- // </d>
- }
-
- _tO = _policyFix(_tO, _cs);
- oSound = make();
-
- if (_fV === 8) {
- _flash._createSound(_tO.id, _tO.loops||1, _tO.usePolicyFile);
- } else {
- _flash._createSound(_tO.id, _tO.url, _tO.usePeakData, _tO.useWaveformData, _tO.useEQData, _tO.isMovieStar, (_tO.isMovieStar?_tO.bufferTime:false), _tO.loops||1, _tO.serverURL, _tO.duration||null, _tO.autoPlay, true, _tO.autoLoad, _tO.usePolicyFile);
- if (!_tO.serverURL) {
- // We are connected immediately
- oSound.connected = true;
- if (_tO.onconnect) {
- _tO.onconnect.apply(oSound);
- }
- }
- }
-
- if (!_tO.serverURL && (_tO.autoLoad || _tO.autoPlay)) {
- // call load for non-rtmp streams
- oSound.load(_tO);
- }
-
- }
-
- // rtmp will play in onconnect
- if (!_tO.serverURL && _tO.autoPlay) {
- oSound.play();
- }
-
- return oSound;
-
- };
-
- /**
- * Destroys a SMSound sound object instance.
- *
- * @param {string} sID The ID of the sound to destroy
- */
-
- this.destroySound = function(sID, _bFromSound) {
-
- // explicitly destroy a sound before normal page unload, etc.
-
- if (!_idCheck(sID)) {
- return false;
- }
-
- var oS = _s.sounds[sID], i;
-
- // Disable all callbacks while the sound is being destroyed
- oS._iO = {};
-
- oS.stop();
- oS.unload();
-
- for (i = 0; i < _s.soundIDs.length; i++) {
- if (_s.soundIDs[i] === sID) {
- _s.soundIDs.splice(i, 1);
- break;
- }
- }
-
- if (!_bFromSound) {
- // ignore if being called from SMSound instance
- oS.destruct(true);
- }
-
- oS = null;
- delete _s.sounds[sID];
-
- return true;
-
- };
-
- /**
- * Calls the load() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {object} oOptions Optional: Sound options
- */
-
- this.load = function(sID, oOptions) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].load(oOptions);
-
- };
-
- /**
- * Calls the unload() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- */
-
- this.unload = function(sID) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].unload();
-
- };
-
- /**
- * Calls the onPosition() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {number} nPosition The position to watch for
- * @param {function} oMethod The relevant callback to fire
- * @param {object} oScope Optional: The scope to apply the callback to
- * @return {SMSound} The SMSound object
- */
-
- this.onPosition = function(sID, nPosition, oMethod, oScope) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].onposition(nPosition, oMethod, oScope);
-
- };
-
- // legacy/backwards-compability: lower-case method name
- this.onposition = this.onPosition;
-
- /**
- * Calls the clearOnPosition() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {number} nPosition The position to watch for
- * @param {function} oMethod Optional: The relevant callback to fire
- * @return {SMSound} The SMSound object
- */
-
- this.clearOnPosition = function(sID, nPosition, oMethod) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].clearOnPosition(nPosition, oMethod);
-
- };
-
- /**
- * Calls the play() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {object} oOptions Optional: Sound options
- * @return {SMSound} The SMSound object
- */
-
- this.play = function(sID, oOptions) {
-
- var result = false;
-
- if (!_didInit || !_s.ok()) {
- _complain(_sm+'.play(): ' + _str(!_didInit?'notReady':'notOK'));
- return result;
- }
-
- if (!_idCheck(sID)) {
- if (!(oOptions instanceof Object)) {
- // overloading use case: play('mySound','/path/to/some.mp3');
- oOptions = {
- url: oOptions
- };
- }
- if (oOptions && oOptions.url) {
- // overloading use case, create+play: .play('someID',{url:'/path/to.mp3'});
- _s._wD(_sm+'.play(): attempting to create "' + sID + '"', 1);
- oOptions.id = sID;
- result = _s.createSound(oOptions).play();
- }
- return result;
- }
-
- return _s.sounds[sID].play(oOptions);
-
- };
-
- this.start = this.play; // just for convenience
-
- /**
- * Calls the setPosition() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {number} nMsecOffset Position (milliseconds)
- * @return {SMSound} The SMSound object
- */
-
- this.setPosition = function(sID, nMsecOffset) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].setPosition(nMsecOffset);
-
- };
-
- /**
- * Calls the stop() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @return {SMSound} The SMSound object
- */
-
- this.stop = function(sID) {
-
- if (!_idCheck(sID)) {
- return false;
- }
-
- _s._wD(_sm+'.stop(' + sID + ')', 1);
- return _s.sounds[sID].stop();
-
- };
-
- /**
- * Stops all currently-playing sounds.
- */
-
- this.stopAll = function() {
-
- var oSound;
- _s._wD(_sm+'.stopAll()', 1);
-
- for (oSound in _s.sounds) {
- if (_s.sounds.hasOwnProperty(oSound)) {
- // apply only to sound objects
- _s.sounds[oSound].stop();
- }
- }
-
- };
-
- /**
- * Calls the pause() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @return {SMSound} The SMSound object
- */
-
- this.pause = function(sID) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].pause();
-
- };
-
- /**
- * Pauses all currently-playing sounds.
- */
-
- this.pauseAll = function() {
-
- var i;
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
- _s.sounds[_s.soundIDs[i]].pause();
- }
-
- };
-
- /**
- * Calls the resume() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @return {SMSound} The SMSound object
- */
-
- this.resume = function(sID) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].resume();
-
- };
-
- /**
- * Resumes all currently-paused sounds.
- */
-
- this.resumeAll = function() {
-
- var i;
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
- _s.sounds[_s.soundIDs[i]].resume();
- }
-
- };
-
- /**
- * Calls the togglePause() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @return {SMSound} The SMSound object
- */
-
- this.togglePause = function(sID) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].togglePause();
-
- };
-
- /**
- * Calls the setPan() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {number} nPan The pan value (-100 to 100)
- * @return {SMSound} The SMSound object
- */
-
- this.setPan = function(sID, nPan) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].setPan(nPan);
-
- };
-
- /**
- * Calls the setVolume() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @param {number} nVol The volume value (0 to 100)
- * @return {SMSound} The SMSound object
- */
-
- this.setVolume = function(sID, nVol) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].setVolume(nVol);
-
- };
-
- /**
- * Calls the mute() method of either a single SMSound object by ID, or all sound objects.
- *
- * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.)
- */
-
- this.mute = function(sID) {
-
- var i = 0;
-
- if (typeof sID !== 'string') {
- sID = null;
- }
-
- if (!sID) {
- _s._wD(_sm+'.mute(): Muting all sounds');
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
- _s.sounds[_s.soundIDs[i]].mute();
- }
- _s.muted = true;
- } else {
- if (!_idCheck(sID)) {
- return false;
- }
- _s._wD(_sm+'.mute(): Muting "' + sID + '"');
- return _s.sounds[sID].mute();
- }
-
- return true;
-
- };
-
- /**
- * Mutes all sounds.
- */
-
- this.muteAll = function() {
-
- _s.mute();
-
- };
-
- /**
- * Calls the unmute() method of either a single SMSound object by ID, or all sound objects.
- *
- * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.)
- */
-
- this.unmute = function(sID) {
-
- var i;
-
- if (typeof sID !== 'string') {
- sID = null;
- }
-
- if (!sID) {
-
- _s._wD(_sm+'.unmute(): Unmuting all sounds');
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
- _s.sounds[_s.soundIDs[i]].unmute();
- }
- _s.muted = false;
-
- } else {
-
- if (!_idCheck(sID)) {
- return false;
- }
- _s._wD(_sm+'.unmute(): Unmuting "' + sID + '"');
- return _s.sounds[sID].unmute();
-
- }
-
- return true;
-
- };
-
- /**
- * Unmutes all sounds.
- */
-
- this.unmuteAll = function() {
-
- _s.unmute();
-
- };
-
- /**
- * Calls the toggleMute() method of a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @return {SMSound} The SMSound object
- */
-
- this.toggleMute = function(sID) {
-
- if (!_idCheck(sID)) {
- return false;
- }
- return _s.sounds[sID].toggleMute();
-
- };
-
- /**
- * Retrieves the memory used by the flash plugin.
- *
- * @return {number} The amount of memory in use
- */
-
- this.getMemoryUse = function() {
-
- // flash-only
- var ram = 0;
-
- if (_flash && _fV !== 8) {
- ram = parseInt(_flash._getMemoryUse(), 10);
- }
-
- return ram;
-
- };
-
- /**
- * Undocumented: NOPs soundManager and all SMSound objects.
- */
-
- this.disable = function(bNoDisable) {
-
- // destroy all functions
- var i;
-
- if (typeof bNoDisable === 'undefined') {
- bNoDisable = false;
- }
-
- if (_disabled) {
- return false;
- }
-
- _disabled = true;
- _wDS('shutdown', 1);
-
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
- _disableObject(_s.sounds[_s.soundIDs[i]]);
- }
-
- // fire "complete", despite fail
- _initComplete(bNoDisable);
- _event.remove(_win, 'load', _initUserOnload);
-
- return true;
-
- };
-
- /**
- * Determines playability of a MIME type, eg. 'audio/mp3'.
- */
-
- this.canPlayMIME = function(sMIME) {
-
- var result;
-
- if (_s.hasHTML5) {
- result = _html5CanPlay({type:sMIME});
- }
-
- if (!result && _needsFlash) {
- // if flash 9, test netStream (movieStar) types as well.
- result = (sMIME && _s.ok() ? !!((_fV > 8 ? sMIME.match(_netStreamMimeTypes) : null) || sMIME.match(_s.mimePattern)) : null);
- }
-
- return result;
-
- };
-
- /**
- * Determines playability of a URL based on audio support.
- *
- * @param {string} sURL The URL to test
- * @return {boolean} URL playability
- */
-
- this.canPlayURL = function(sURL) {
-
- var result;
-
- if (_s.hasHTML5) {
- result = _html5CanPlay({url: sURL});
- }
-
- if (!result && _needsFlash) {
- result = (sURL && _s.ok() ? !!(sURL.match(_s.filePattern)) : null);
- }
-
- return result;
-
- };
-
- /**
- * Determines playability of an HTML DOM <a> object (or similar object literal) based on audio support.
- *
- * @param {object} oLink an HTML DOM <a> object or object literal including href and/or type attributes
- * @return {boolean} URL playability
- */
-
- this.canPlayLink = function(oLink) {
-
- if (typeof oLink.type !== 'undefined' && oLink.type) {
- if (_s.canPlayMIME(oLink.type)) {
- return true;
- }
- }
-
- return _s.canPlayURL(oLink.href);
-
- };
-
- /**
- * Retrieves a SMSound object by ID.
- *
- * @param {string} sID The ID of the sound
- * @return {SMSound} The SMSound object
- */
-
- this.getSoundById = function(sID, _suppressDebug) {
-
- if (!sID) {
- throw new Error(_sm+'.getSoundById(): sID is null/undefined');
- }
-
- var result = _s.sounds[sID];
-
- // <d>
- if (!result && !_suppressDebug) {
- _s._wD('"' + sID + '" is an invalid sound ID.', 2);
- }
- // </d>
-
- return result;
-
- };
-
- /**
- * Queues a callback for execution when SoundManager has successfully initialized.
- *
- * @param {function} oMethod The callback method to fire
- * @param {object} oScope Optional: The scope to apply to the callback
- */
-
- this.onready = function(oMethod, oScope) {
-
- var sType = 'onready',
- result = false;
-
- if (typeof oMethod === 'function') {
-
- // <d>
- if (_didInit) {
- _s._wD(_str('queue', sType));
- }
- // </d>
-
- if (!oScope) {
- oScope = _win;
- }
-
- _addOnEvent(sType, oMethod, oScope);
- _processOnEvents();
-
- result = true;
-
- } else {
-
- throw _str('needFunction', sType);
-
- }
-
- return result;
-
- };
-
- /**
- * Queues a callback for execution when SoundManager has failed to initialize.
- *
- * @param {function} oMethod The callback method to fire
- * @param {object} oScope Optional: The scope to apply to the callback
- */
-
- this.ontimeout = function(oMethod, oScope) {
-
- var sType = 'ontimeout',
- result = false;
-
- if (typeof oMethod === 'function') {
-
- // <d>
- if (_didInit) {
- _s._wD(_str('queue', sType));
- }
- // </d>
-
- if (!oScope) {
- oScope = _win;
- }
-
- _addOnEvent(sType, oMethod, oScope);
- _processOnEvents({type:sType});
-
- result = true;
-
- } else {
-
- throw _str('needFunction', sType);
-
- }
-
- return result;
-
- };
-
- /**
- * Writes console.log()-style debug output to a console or in-browser element.
- * Applies when debugMode = true
- *
- * @param {string} sText The console message
- * @param {string} sType Optional: Log type of 'info', 'warn' or 'error'
- * @param {object} Optional: The scope to apply to the callback
- */
-
- this._writeDebug = function(sText, sType, _bTimestamp) {
-
- // pseudo-private console.log()-style output
- // <d>
-
- var sDID = 'soundmanager-debug', o, oItem, sMethod;
-
- if (!_s.debugMode) {
- return false;
- }
-
- if (typeof _bTimestamp !== 'undefined' && _bTimestamp) {
- sText = sText + ' | ' + new Date().getTime();
- }
-
- if (_hasConsole && _s.useConsole) {
- sMethod = _debugLevels[sType];
- if (typeof console[sMethod] !== 'undefined') {
- console[sMethod](sText);
- } else {
- console.log(sText);
- }
- if (_s.consoleOnly) {
- return true;
- }
- }
-
- try {
-
- o = _id(sDID);
-
- if (!o) {
- return false;
- }
-
- oItem = _doc.createElement('div');
-
- if (++_wdCount % 2 === 0) {
- oItem.className = 'sm2-alt';
- }
-
- if (typeof sType === 'undefined') {
- sType = 0;
- } else {
- sType = parseInt(sType, 10);
- }
-
- oItem.appendChild(_doc.createTextNode(sText));
-
- if (sType) {
- if (sType >= 2) {
- oItem.style.fontWeight = 'bold';
- }
- if (sType === 3) {
- oItem.style.color = '#ff3333';
- }
- }
-
- // top-to-bottom
- // o.appendChild(oItem);
-
- // bottom-to-top
- o.insertBefore(oItem, o.firstChild);
-
- } catch(e) {
- // oh well
- }
-
- o = null;
- // </d>
-
- return true;
-
- };
-
- // alias
- this._wD = this._writeDebug;
-
- /**
- * Provides debug / state information on all SMSound objects.
- */
-
- this._debug = function() {
-
- // <d>
- var i, j;
- _wDS('currentObj', 1);
-
- for (i = 0, j = _s.soundIDs.length; i < j; i++) {
- _s.sounds[_s.soundIDs[i]]._debug();
- }
- // </d>
-
- };
-
- /**
- * Restarts and re-initializes the SoundManager instance.
- */
-
- this.reboot = function() {
-
- // attempt to reset and init SM2
- _s._wD(_sm+'.reboot()');
-
- // <d>
- if (_s.soundIDs.length) {
- _s._wD('Destroying ' + _s.soundIDs.length + ' SMSound objects...');
- }
- // </d>
-
- var i, j;
-
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
- _s.sounds[_s.soundIDs[i]].destruct();
- }
-
- // trash ze flash
-
- if (_flash) {
- try {
- if (_isIE) {
- _oRemovedHTML = _flash.innerHTML;
- }
- _oRemoved = _flash.parentNode.removeChild(_flash);
- _s._wD('Flash movie removed.');
- } catch(e) {
- // uh-oh.
- _wDS('badRemove', 2);
- }
- }
-
- // actually, force recreate of movie.
- _oRemovedHTML = _oRemoved = _needsFlash = null;
-
- _s.enabled = _didDCLoaded = _didInit = _waitingForEI = _initPending = _didAppend = _appendSuccess = _disabled = _s.swfLoaded = false;
- _s.soundIDs = [];
- _s.sounds = {};
- _flash = null;
-
- for (i in _on_queue) {
- if (_on_queue.hasOwnProperty(i)) {
- for (j = _on_queue[i].length-1; j >= 0; j--) {
- _on_queue[i][j].fired = false;
- }
- }
- }
-
- _s._wD(_sm + ': Rebooting...');
- _win.setTimeout(_s.beginDelayedInit, 20);
-
- };
-
- /**
- * Undocumented: Determines the SM2 flash movie's load progress.
- *
- * @return {number or null} Percent loaded, or if invalid/unsupported, null.
- */
-
- this.getMoviePercent = function() {
-
- // interesting note: flash/ExternalInterface bridge methods are not typeof "function" nor instanceof Function, but are still valid.
- return (_flash && typeof _flash.PercentLoaded !== 'undefined' ? _flash.PercentLoaded() : null);
-
- };
-
- /**
- * Additional helper for manually invoking SM2's init process after DOM Ready / window.onload().
- */
-
- this.beginDelayedInit = function() {
-
- _windowLoaded = true;
- _domContentLoaded();
-
- setTimeout(function() {
-
- if (_initPending) {
- return false;
- }
-
- _createMovie();
- _initMovie();
- _initPending = true;
-
- return true;
-
- }, 20);
-
- _delayWaitForEI();
-
- };
-
- /**
- * Destroys the SoundManager instance and all SMSound instances.
- */
-
- this.destruct = function() {
-
- _s._wD(_sm+'.destruct()');
- _s.disable(true);
-
- };
-
- /**
- * SMSound() (sound object) constructor
- * ------------------------------------
- *
- * @param {object} oOptions Sound options (id and url are required attributes)
- * @return {SMSound} The new SMSound object
- */
-
- SMSound = function(oOptions) {
-
- var _t = this, _resetProperties, _add_html5_events, _remove_html5_events, _stop_html5_timer, _start_html5_timer, _attachOnPosition, _onplay_called = false, _onPositionItems = [], _onPositionFired = 0, _detachOnPosition, _applyFromTo, _lastURL = null, _lastHTML5State;
-
- _lastHTML5State = {
- // tracks duration + position (time)
- duration: null,
- time: null
- };
-
- this.id = oOptions.id;
-
- // legacy
- this.sID = this.id;
-
- this.url = oOptions.url;
- this.options = _mixin(oOptions);
-
- // per-play-instance-specific options
- this.instanceOptions = this.options;
-
- // short alias
- this._iO = this.instanceOptions;
-
- // assign property defaults
- this.pan = this.options.pan;
- this.volume = this.options.volume;
-
- // whether or not this object is using HTML5
- this.isHTML5 = false;
-
- // internal HTML5 Audio() object reference
- this._a = null;
-
- /**
- * SMSound() public methods
- * ------------------------
- */
-
- this.id3 = {};
-
- /**
- * Writes SMSound object parameters to debug console
- */
-
- this._debug = function() {
-
- // <d>
- // pseudo-private console.log()-style output
-
- if (_s.debugMode) {
-
- var stuff = null, msg = [], sF, sfBracket, maxLength = 64;
-
- for (stuff in _t.options) {
- if (_t.options[stuff] !== null) {
- if (typeof _t.options[stuff] === 'function') {
- // handle functions specially
- sF = _t.options[stuff].toString();
- // normalize spaces
- sF = sF.replace(/\s\s+/g, ' ');
- sfBracket = sF.indexOf('{');
- msg.push(' ' + stuff + ': {' + sF.substr(sfBracket + 1, (Math.min(Math.max(sF.indexOf('\n') - 1, maxLength), maxLength))).replace(/\n/g, '') + '... }');
- } else {
- msg.push(' ' + stuff + ': ' + _t.options[stuff]);
- }
- }
- }
-
- _s._wD('SMSound() merged options: {\n' + msg.join(', \n') + '\n}');
-
- }
- // </d>
-
- };
-
- // <d>
- this._debug();
- // </d>
-
- /**
- * Begins loading a sound per its *url*.
- *
- * @param {object} oOptions Optional: Sound options
- * @return {SMSound} The SMSound object
- */
-
- this.load = function(oOptions) {
-
- var oS = null, _iO;
-
- if (typeof oOptions !== 'undefined') {
- _t._iO = _mixin(oOptions, _t.options);
- _t.instanceOptions = _t._iO;
- } else {
- oOptions = _t.options;
- _t._iO = oOptions;
- _t.instanceOptions = _t._iO;
- if (_lastURL && _lastURL !== _t.url) {
- _wDS('manURL');
- _t._iO.url = _t.url;
- _t.url = null;
- }
- }
-
- if (!_t._iO.url) {
- _t._iO.url = _t.url;
- }
-
- _t._iO.url = _parseURL(_t._iO.url);
-
- _s._wD('SMSound.load(): ' + _t._iO.url, 1);
-
- if (_t._iO.url === _t.url && _t.readyState !== 0 && _t.readyState !== 2) {
- _wDS('onURL', 1);
- // if loaded and an onload() exists, fire immediately.
- if (_t.readyState === 3 && _t._iO.onload) {
- // assume success based on truthy duration.
- _t._iO.onload.apply(_t, [(!!_t.duration)]);
- }
- return _t;
- }
-
- // local shortcut
- _iO = _t._iO;
-
- _lastURL = _t.url;
-
- // reset a few state properties
-
- _t.loaded = false;
- _t.readyState = 1;
- _t.playState = 0;
- _t.id3 = {};
-
- // TODO: If switching from HTML5 -> flash (or vice versa), stop currently-playing audio.
-
- if (_html5OK(_iO)) {
-
- oS = _t._setup_html5(_iO);
-
- if (!oS._called_load) {
-
- _s._wD(_h5+'load: '+_t.id);
-
- _t._html5_canplay = false;
-
- // TODO: review called_load / html5_canplay logic
-
- // if url provided directly to load(), assign it here.
-
- if (_t._a.src !== _iO.url) {
-
- _s._wD(_wDS('manURL') + ': ' + _iO.url);
-
- _t._a.src = _iO.url;
-
- // TODO: review / re-apply all relevant options (volume, loop, onposition etc.)
-
- // reset position for new URL
- _t.setPosition(0);
-
- }
-
- // given explicit load call, try to preload.
-
- // early HTML5 implementation (non-standard)
- _t._a.autobuffer = 'auto';
-
- // standard
- _t._a.preload = 'auto';
-
- oS._called_load = true;
-
- if (_iO.autoPlay) {
- _t.play();
- }
-
- } else {
-
- _s._wD(_h5+'ignoring request to load again: '+_t.id);
-
- }
-
- } else {
-
- try {
- _t.isHTML5 = false;
- _t._iO = _policyFix(_loopFix(_iO));
- // re-assign local shortcut
- _iO = _t._iO;
- if (_fV === 8) {
- _flash._load(_t.id, _iO.url, _iO.stream, _iO.autoPlay, (_iO.whileloading?1:0), _iO.loops||1, _iO.usePolicyFile);
- } else {
- _flash._load(_t.id, _iO.url, !!(_iO.stream), !!(_iO.autoPlay), _iO.loops||1, !!(_iO.autoLoad), _iO.usePolicyFile);
- }
- } catch(e) {
- _wDS('smError', 2);
- _debugTS('onload', false);
- _catchError({type:'SMSOUND_LOAD_JS_EXCEPTION', fatal:true});
-
- }
-
- }
-
- return _t;
-
- };
-
- /**
- * Unloads a sound, canceling any open HTTP requests.
- *
- * @return {SMSound} The SMSound object
- */
-
- this.unload = function() {
-
- // Flash 8/AS2 can't "close" a stream - fake it by loading an empty URL
- // Flash 9/AS3: Close stream, preventing further load
- // HTML5: Most UAs will use empty URL
-
- if (_t.readyState !== 0) {
-
- _s._wD('SMSound.unload(): "' + _t.id + '"');
-
- if (!_t.isHTML5) {
-
- if (_fV === 8) {
- _flash._unload(_t.id, _emptyURL);
- } else {
- _flash._unload(_t.id);
- }
-
- } else {
-
- _stop_html5_timer();
-
- if (_t._a) {
-
- _t._a.pause();
- _html5Unload(_t._a, _emptyURL);
-
- // reset local URL for next load / play call, too
- _t.url = _emptyURL;
-
- }
-
- }
-
- // reset load/status flags
- _resetProperties();
-
- }
-
- return _t;
-
- };
-
- /**
- * Unloads and destroys a sound.
- */
-
- this.destruct = function(_bFromSM) {
-
- _s._wD('SMSound.destruct(): "' + _t.id + '"');
-
- if (!_t.isHTML5) {
-
- // kill sound within Flash
- // Disable the onfailure handler
- _t._iO.onfailure = null;
- _flash._destroySound(_t.id);
-
- } else {
-
- _stop_html5_timer();
-
- if (_t._a) {
- _t._a.pause();
- _html5Unload(_t._a);
- if (!_useGlobalHTML5Audio) {
- _remove_html5_events();
- }
- // break obvious circular reference
- _t._a._t = null;
- _t._a = null;
- }
-
- }
-
- if (!_bFromSM) {
- // ensure deletion from controller
- _s.destroySound(_t.id, true);
-
- }
-
- };
-
- /**
- * Begins playing a sound.
- *
- * @param {object} oOptions Optional: Sound options
- * @return {SMSound} The SMSound object
- */
-
- this.play = function(oOptions, _updatePlayState) {
-
- var fN, allowMulti, a, onready, startOK = true,
- exit = null;
-
- // <d>
- fN = 'SMSound.play(): ';
- // </d>
-
- // default to true
- _updatePlayState = (typeof _updatePlayState === 'undefined' ? true : _updatePlayState);
-
- if (!oOptions) {
- oOptions = {};
- }
-
- _t._iO = _mixin(oOptions, _t._iO);
- _t._iO = _mixin(_t._iO, _t.options);
- _t._iO.url = _parseURL(_t._iO.url);
- _t.instanceOptions = _t._iO;
-
- // RTMP-only
- if (_t._iO.serverURL && !_t.connected) {
- if (!_t.getAutoPlay()) {
- _s._wD(fN+' Netstream not connected yet - setting autoPlay');
- _t.setAutoPlay(true);
- }
- // play will be called in _onconnect()
- return _t;
- }
-
- if (_html5OK(_t._iO)) {
- _t._setup_html5(_t._iO);
- _start_html5_timer();
- }
-
- if (_t.playState === 1 && !_t.paused) {
- allowMulti = _t._iO.multiShot;
- if (!allowMulti) {
- _s._wD(fN + '"' + _t.id + '" already playing (one-shot)', 1);
- exit = _t;
- } else {
- _s._wD(fN + '"' + _t.id + '" already playing (multi-shot)', 1);
- }
- }
-
- if (exit !== null) {
- return exit;
- }
-
- if (!_t.loaded) {
-
- if (_t.readyState === 0) {
-
- _s._wD(fN + 'Attempting to load "' + _t.id + '"', 1);
-
- // try to get this sound playing ASAP
- if (!_t.isHTML5) {
- // assign directly because setAutoPlay() increments the instanceCount
- _t._iO.autoPlay = true;
- _t.load(_t._iO);
- } else {
- // iOS needs this when recycling sounds, loading a new URL on an existing object.
- _t.load(_t._iO);
- }
-
- } else if (_t.readyState === 2) {
-
- _s._wD(fN + 'Could not load "' + _t.id + '" - exiting', 2);
- exit = _t;
-
- } else {
-
- _s._wD(fN + '"' + _t.id + '" is loading - attempting to play..', 1);
-
- }
-
- } else {
-
- _s._wD(fN + '"' + _t.id + '"');
-
- }
-
- if (exit !== null) {
- return exit;
- }
-
- if (!_t.isHTML5 && _fV === 9 && _t.position > 0 && _t.position === _t.duration) {
- // flash 9 needs a position reset if play() is called while at the end of a sound.
- _s._wD(fN + '"' + _t.id + '": Sound at end, resetting to position:0');
- oOptions.position = 0;
- }
-
- /**
- * Streams will pause when their buffer is full if they are being loaded.
- * In this case paused is true, but the song hasn't started playing yet.
- * If we just call resume() the onplay() callback will never be called.
- * So only call resume() if the position is > 0.
- * Another reason is because options like volume won't have been applied yet.
- */
-
- if (_t.paused && _t.position && _t.position > 0) {
-
- // https://gist.github.com/37b17df75cc4d7a90bf6
- _s._wD(fN + '"' + _t.id + '" is resuming from paused state',1);
- _t.resume();
-
- } else {
-
- _t._iO = _mixin(oOptions, _t._iO);
-
- // apply from/to parameters, if they exist (and not using RTMP)
- if (_t._iO.from !== null && _t._iO.to !== null && _t.instanceCount === 0 && _t.playState === 0 && !_t._iO.serverURL) {
-
- onready = function() {
- // sound "canplay" or onload()
- // re-apply from/to to instance options, and start playback
- _t._iO = _mixin(oOptions, _t._iO);
- _t.play(_t._iO);
- };
-
- // HTML5 needs to at least have "canplay" fired before seeking.
- if (_t.isHTML5 && !_t._html5_canplay) {
-
- // this hasn't been loaded yet. load it first, and then do this again.
- _s._wD(fN+'Beginning load of "'+ _t.id+'" for from/to case');
-
- _t.load({
- _oncanplay: onready
- });
-
- exit = false;
-
- } else if (!_t.isHTML5 && !_t.loaded && (!_t.readyState || _t.readyState !== 2)) {
-
- // to be safe, preload the whole thing in Flash.
-
- _s._wD(fN+'Preloading "'+ _t.id+'" for from/to case');
-
- _t.load({
- onload: onready
- });
-
- exit = false;
-
- }
-
- if (exit !== null) {
- return exit;
- }
-
- // otherwise, we're ready to go. re-apply local options, and continue
-
- _t._iO = _applyFromTo();
-
- }
-
- _s._wD(fN+'"'+ _t.id+'" is starting to play');
-
- if (!_t.instanceCount || _t._iO.multiShotEvents || (!_t.isHTML5 && _fV > 8 && !_t.getAutoPlay())) {
- _t.instanceCount++;
- }
-
- // if first play and onposition parameters exist, apply them now
- if (_t._iO.onposition && _t.playState === 0) {
- _attachOnPosition(_t);
- }
-
- _t.playState = 1;
- _t.paused = false;
-
- _t.position = (typeof _t._iO.position !== 'undefined' && !isNaN(_t._iO.position) ? _t._iO.position : 0);
-
- if (!_t.isHTML5) {
- _t._iO = _policyFix(_loopFix(_t._iO));
- }
-
- if (_t._iO.onplay && _updatePlayState) {
- _t._iO.onplay.apply(_t);
- _onplay_called = true;
- }
-
- _t.setVolume(_t._iO.volume, true);
- _t.setPan(_t._iO.pan, true);
-
- if (!_t.isHTML5) {
-
- startOK = _flash._start(_t.id, _t._iO.loops || 1, (_fV === 9 ? _t._iO.position : _t._iO.position / 1000), _t._iO.multiShot);
-
- if (_fV === 9 && !startOK) {
- // edge case: no sound hardware, or 32-channel flash ceiling hit.
- // applies only to Flash 9, non-NetStream/MovieStar sounds.
- // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Sound.html#play%28%29
- _s._wD(fN+ _t.id+': No sound hardware, or 32-sound ceiling hit');
- if (_t._iO.onplayerror) {
- _t._iO.onplayerror.apply(_t);
- }
-
- }
-
- } else {
-
- _start_html5_timer();
-
- a = _t._setup_html5();
-
- _t.setPosition(_t._iO.position);
-
- a.play();
-
- }
-
- }
-
- return _t;
-
- };
-
- // just for convenience
- this.start = this.play;
-
- /**
- * Stops playing a sound (and optionally, all sounds)
- *
- * @param {boolean} bAll Optional: Whether to stop all sounds
- * @return {SMSound} The SMSound object
- */
-
- this.stop = function(bAll) {
-
- var _iO = _t._iO, _oP;
-
- if (_t.playState === 1) {
-
- _t._onbufferchange(0);
- _t._resetOnPosition(0);
- _t.paused = false;
-
- if (!_t.isHTML5) {
- _t.playState = 0;
- }
-
- // remove onPosition listeners, if any
- _detachOnPosition();
-
- // and "to" position, if set
- if (_iO.to) {
- _t.clearOnPosition(_iO.to);
- }
-
- if (!_t.isHTML5) {
-
- _flash._stop(_t.id, bAll);
-
- // hack for netStream: just unload
- if (_iO.serverURL) {
- _t.unload();
- }
-
- } else {
-
- if (_t._a) {
-
- _oP = _t.position;
-
- // act like Flash, though
- _t.setPosition(0);
-
- // hack: reflect old position for onstop() (also like Flash)
- _t.position = _oP;
-
- // html5 has no stop()
- // NOTE: pausing means iOS requires interaction to resume.
- _t._a.pause();
-
- _t.playState = 0;
-
- // and update UI
- _t._onTimer();
-
- _stop_html5_timer();
-
- }
-
- }
-
- _t.instanceCount = 0;
- _t._iO = {};
-
- if (_iO.onstop) {
- _iO.onstop.apply(_t);
- }
-
- }
-
- return _t;
-
- };
-
- /**
- * Undocumented/internal: Sets autoPlay for RTMP.
- *
- * @param {boolean} autoPlay state
- */
-
- this.setAutoPlay = function(autoPlay) {
-
- _s._wD('sound '+_t.id+' turned autoplay ' + (autoPlay ? 'on' : 'off'));
- _t._iO.autoPlay = autoPlay;
-
- if (!_t.isHTML5) {
- _flash._setAutoPlay(_t.id, autoPlay);
- if (autoPlay) {
- // only increment the instanceCount if the sound isn't loaded (TODO: verify RTMP)
- if (!_t.instanceCount && _t.readyState === 1) {
- _t.instanceCount++;
- _s._wD('sound '+_t.id+' incremented instance count to '+_t.instanceCount);
- }
- }
- }
-
- };
-
- /**
- * Undocumented/internal: Returns the autoPlay boolean.
- *
- * @return {boolean} The current autoPlay value
- */
-
- this.getAutoPlay = function() {
-
- return _t._iO.autoPlay;
-
- };
-
- /**
- * Sets the position of a sound.
- *
- * @param {number} nMsecOffset Position (milliseconds)
- * @return {SMSound} The SMSound object
- */
-
- this.setPosition = function(nMsecOffset) {
-
- if (typeof nMsecOffset === 'undefined') {
- nMsecOffset = 0;
- }
-
- var original_pos,
- position, position1K,
- // Use the duration from the instance options, if we don't have a track duration yet.
- // position >= 0 and <= current available (loaded) duration
- offset = (_t.isHTML5 ? Math.max(nMsecOffset,0) : Math.min(_t.duration || _t._iO.duration, Math.max(nMsecOffset, 0)));
-
- original_pos = _t.position;
- _t.position = offset;
- position1K = _t.position/1000;
- _t._resetOnPosition(_t.position);
- _t._iO.position = offset;
-
- if (!_t.isHTML5) {
-
- position = (_fV === 9 ? _t.position : position1K);
- if (_t.readyState && _t.readyState !== 2) {
- // if paused or not playing, will not resume (by playing)
- _flash._setPosition(_t.id, position, (_t.paused || !_t.playState), _t._iO.multiShot);
- }
-
- } else if (_t._a) {
-
- // Set the position in the canplay handler if the sound is not ready yet
- if (_t._html5_canplay) {
- if (_t._a.currentTime !== position1K) {
- /**
- * DOM/JS errors/exceptions to watch out for:
- * if seek is beyond (loaded?) position, "DOM exception 11"
- * "INDEX_SIZE_ERR": DOM exception 1
- */
- _s._wD('setPosition('+position1K+'): setting position');
- try {
- _t._a.currentTime = position1K;
- if (_t.playState === 0 || _t.paused) {
- // allow seek without auto-play/resume
- _t._a.pause();
- }
- } catch(e) {
- _s._wD('setPosition('+position1K+'): setting position failed: '+e.message, 2);
- }
- }
- } else {
- _s._wD('setPosition('+position1K+'): delaying, sound not ready');
- }
-
- }
-
- if (_t.isHTML5) {
- if (_t.paused) {
- // if paused, refresh UI right away
- // force update
- _t._onTimer(true);
- }
- }
-
- return _t;
-
- };
-
- /**
- * Pauses sound playback.
- *
- * @return {SMSound} The SMSound object
- */
-
- this.pause = function(_bCallFlash) {
-
- if (_t.paused || (_t.playState === 0 && _t.readyState !== 1)) {
- return _t;
- }
-
- _s._wD('SMSound.pause()');
- _t.paused = true;
-
- if (!_t.isHTML5) {
- if (_bCallFlash || typeof _bCallFlash === 'undefined') {
- _flash._pause(_t.id, _t._iO.multiShot);
- }
- } else {
- _t._setup_html5().pause();
- _stop_html5_timer();
- }
-
- if (_t._iO.onpause) {
- _t._iO.onpause.apply(_t);
- }
-
- return _t;
-
- };
-
- /**
- * Resumes sound playback.
- *
- * @return {SMSound} The SMSound object
- */
-
- /**
- * When auto-loaded streams pause on buffer full they have a playState of 0.
- * We need to make sure that the playState is set to 1 when these streams "resume".
- * When a paused stream is resumed, we need to trigger the onplay() callback if it
- * hasn't been called already. In this case since the sound is being played for the
- * first time, I think it's more appropriate to call onplay() rather than onresume().
- */
-
- this.resume = function() {
-
- var _iO = _t._iO;
-
- if (!_t.paused) {
- return _t;
- }
-
- _s._wD('SMSound.resume()');
- _t.paused = false;
- _t.playState = 1;
-
- if (!_t.isHTML5) {
- if (_iO.isMovieStar && !_iO.serverURL) {
- // Bizarre Webkit bug (Chrome reported via 8tracks.com dudes): AAC content paused for 30+ seconds(?) will not resume without a reposition.
- _t.setPosition(_t.position);
- }
- // flash method is toggle-based (pause/resume)
- _flash._pause(_t.id, _iO.multiShot);
- } else {
- _t._setup_html5().play();
- _start_html5_timer();
- }
-
- if (!_onplay_called && _iO.onplay) {
- _iO.onplay.apply(_t);
- _onplay_called = true;
- } else if (_iO.onresume) {
- _iO.onresume.apply(_t);
- }
-
- return _t;
-
- };
-
- /**
- * Toggles sound playback.
- *
- * @return {SMSound} The SMSound object
- */
-
- this.togglePause = function() {
-
- _s._wD('SMSound.togglePause()');
-
- if (_t.playState === 0) {
- _t.play({
- position: (_fV === 9 && !_t.isHTML5 ? _t.position : _t.position / 1000)
- });
- return _t;
- }
-
- if (_t.paused) {
- _t.resume();
- } else {
- _t.pause();
- }
-
- return _t;
-
- };
-
- /**
- * Sets the panning (L-R) effect.
- *
- * @param {number} nPan The pan value (-100 to 100)
- * @return {SMSound} The SMSound object
- */
-
- this.setPan = function(nPan, bInstanceOnly) {
-
- if (typeof nPan === 'undefined') {
- nPan = 0;
- }
-
- if (typeof bInstanceOnly === 'undefined') {
- bInstanceOnly = false;
- }
-
- if (!_t.isHTML5) {
- _flash._setPan(_t.id, nPan);
- } // else { no HTML5 pan? }
-
- _t._iO.pan = nPan;
-
- if (!bInstanceOnly) {
- _t.pan = nPan;
- _t.options.pan = nPan;
- }
-
- return _t;
-
- };
-
- /**
- * Sets the volume.
- *
- * @param {number} nVol The volume value (0 to 100)
- * @return {SMSound} The SMSound object
- */
-
- this.setVolume = function(nVol, _bInstanceOnly) {
-
- /**
- * Note: Setting volume has no effect on iOS "special snowflake" devices.
- * Hardware volume control overrides software, and volume
- * will always return 1 per Apple docs. (iOS 4 + 5.)
- * http://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AddingSoundtoCanvasAnimations/AddingSoundtoCanvasAnimations.html
- */
-
- if (typeof nVol === 'undefined') {
- nVol = 100;
- }
-
- if (typeof _bInstanceOnly === 'undefined') {
- _bInstanceOnly = false;
- }
-
- if (!_t.isHTML5) {
- _flash._setVolume(_t.id, (_s.muted && !_t.muted) || _t.muted?0:nVol);
- } else if (_t._a) {
- // valid range: 0-1
- _t._a.volume = Math.max(0, Math.min(1, nVol/100));
- }
-
- _t._iO.volume = nVol;
-
- if (!_bInstanceOnly) {
- _t.volume = nVol;
- _t.options.volume = nVol;
- }
-
- return _t;
-
- };
-
- /**
- * Mutes the sound.
- *
- * @return {SMSound} The SMSound object
- */
-
- this.mute = function() {
-
- _t.muted = true;
-
- if (!_t.isHTML5) {
- _flash._setVolume(_t.id, 0);
- } else if (_t._a) {
- _t._a.muted = true;
- }
-
- return _t;
-
- };
-
- /**
- * Unmutes the sound.
- *
- * @return {SMSound} The SMSound object
- */
-
- this.unmute = function() {
-
- _t.muted = false;
- var hasIO = (typeof _t._iO.volume !== 'undefined');
-
- if (!_t.isHTML5) {
- _flash._setVolume(_t.id, hasIO?_t._iO.volume:_t.options.volume);
- } else if (_t._a) {
- _t._a.muted = false;
- }
-
- return _t;
-
- };
-
- /**
- * Toggles the muted state of a sound.
- *
- * @return {SMSound} The SMSound object
- */
-
- this.toggleMute = function() {
-
- return (_t.muted?_t.unmute():_t.mute());
-
- };
-
- /**
- * Registers a callback to be fired when a sound reaches a given position during playback.
- *
- * @param {number} nPosition The position to watch for
- * @param {function} oMethod The relevant callback to fire
- * @param {object} oScope Optional: The scope to apply the callback to
- * @return {SMSound} The SMSound object
- */
-
- this.onPosition = function(nPosition, oMethod, oScope) {
-
- // TODO: basic dupe checking?
-
- _onPositionItems.push({
- position: parseInt(nPosition, 10),
- method: oMethod,
- scope: (typeof oScope !== 'undefined' ? oScope : _t),
- fired: false
- });
-
- return _t;
-
- };
-
- // legacy/backwards-compability: lower-case method name
- this.onposition = this.onPosition;
-
- /**
- * Removes registered callback(s) from a sound, by position and/or callback.
- *
- * @param {number} nPosition The position to clear callback(s) for
- * @param {function} oMethod Optional: Identify one callback to be removed when multiple listeners exist for one position
- * @return {SMSound} The SMSound object
- */
-
- this.clearOnPosition = function(nPosition, oMethod) {
-
- var i;
-
- nPosition = parseInt(nPosition, 10);
-
- if (isNaN(nPosition)) {
- // safety check
- return false;
- }
-
- for (i=0; i < _onPositionItems.length; i++) {
-
- if (nPosition === _onPositionItems[i].position) {
- // remove this item if no method was specified, or, if the method matches
- if (!oMethod || (oMethod === _onPositionItems[i].method)) {
- if (_onPositionItems[i].fired) {
- // decrement "fired" counter, too
- _onPositionFired--;
- }
- _onPositionItems.splice(i, 1);
- }
- }
-
- }
-
- };
-
- this._processOnPosition = function() {
-
- var i, item, j = _onPositionItems.length;
-
- if (!j || !_t.playState || _onPositionFired >= j) {
- return false;
- }
-
- for (i=j-1; i >= 0; i--) {
- item = _onPositionItems[i];
- if (!item.fired && _t.position >= item.position) {
- item.fired = true;
- _onPositionFired++;
- item.method.apply(item.scope, [item.position]);
- }
- }
-
- return true;
-
- };
-
- this._resetOnPosition = function(nPosition) {
-
- // reset "fired" for items interested in this position
- var i, item, j = _onPositionItems.length;
-
- if (!j) {
- return false;
- }
-
- for (i=j-1; i >= 0; i--) {
- item = _onPositionItems[i];
- if (item.fired && nPosition <= item.position) {
- item.fired = false;
- _onPositionFired--;
- }
- }
-
- return true;
-
- };
-
- /**
- * SMSound() private internals
- * --------------------------------
- */
-
- _applyFromTo = function() {
-
- var _iO = _t._iO,
- f = _iO.from,
- t = _iO.to,
- start, end;
-
- end = function() {
-
- // end has been reached.
- _s._wD(_t.id + ': "to" time of ' + t + ' reached.');
-
- // detach listener
- _t.clearOnPosition(t, end);
-
- // stop should clear this, too
- _t.stop();
-
- };
-
- start = function() {
-
- _s._wD(_t.id + ': playing "from" ' + f);
-
- // add listener for end
- if (t !== null && !isNaN(t)) {
- _t.onPosition(t, end);
- }
-
- };
-
- if (f !== null && !isNaN(f)) {
-
- // apply to instance options, guaranteeing correct start position.
- _iO.position = f;
-
- // multiShot timing can't be tracked, so prevent that.
- _iO.multiShot = false;
-
- start();
-
- }
-
- // return updated instanceOptions including starting position
- return _iO;
-
- };
-
- _attachOnPosition = function() {
-
- var item,
- op = _t._iO.onposition;
-
- // attach onposition things, if any, now.
-
- if (op) {
-
- for (item in op) {
- if (op.hasOwnProperty(item)) {
- _t.onPosition(parseInt(item, 10), op[item]);
- }
- }
-
- }
-
- };
-
- _detachOnPosition = function() {
-
- var item,
- op = _t._iO.onposition;
-
- // detach any onposition()-style listeners.
-
- if (op) {
-
- for (item in op) {
- if (op.hasOwnProperty(item)) {
- _t.clearOnPosition(parseInt(item, 10));
- }
- }
-
- }
-
- };
-
- _start_html5_timer = function() {
-
- if (_t.isHTML5) {
- _startTimer(_t);
- }
-
- };
-
- _stop_html5_timer = function() {
-
- if (_t.isHTML5) {
- _stopTimer(_t);
- }
-
- };
-
- _resetProperties = function(retainPosition) {
-
- if (!retainPosition) {
- _onPositionItems = [];
- _onPositionFired = 0;
- }
-
- _onplay_called = false;
-
- _t._hasTimer = null;
- _t._a = null;
- _t._html5_canplay = false;
- _t.bytesLoaded = null;
- _t.bytesTotal = null;
- _t.duration = (_t._iO && _t._iO.duration ? _t._iO.duration : null);
- _t.durationEstimate = null;
- _t.buffered = [];
-
- // legacy: 1D array
- _t.eqData = [];
-
- _t.eqData.left = [];
- _t.eqData.right = [];
-
- _t.failures = 0;
- _t.isBuffering = false;
- _t.instanceOptions = {};
- _t.instanceCount = 0;
- _t.loaded = false;
- _t.metadata = {};
-
- // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success
- _t.readyState = 0;
-
- _t.muted = false;
- _t.paused = false;
-
- _t.peakData = {
- left: 0,
- right: 0
- };
-
- _t.waveformData = {
- left: [],
- right: []
- };
-
- _t.playState = 0;
- _t.position = null;
-
- _t.id3 = {};
-
- };
-
- _resetProperties();
-
- /**
- * Pseudo-private SMSound internals
- * --------------------------------
- */
-
- this._onTimer = function(bForce) {
-
- /**
- * HTML5-only _whileplaying() etc.
- * called from both HTML5 native events, and polling/interval-based timers
- * mimics flash and fires only when time/duration change, so as to be polling-friendly
- */
-
- var duration, isNew = false, time, x = {};
-
- if (_t._hasTimer || bForce) {
-
- // TODO: May not need to track readyState (1 = loading)
-
- if (_t._a && (bForce || ((_t.playState > 0 || _t.readyState === 1) && !_t.paused))) {
-
- duration = _t._get_html5_duration();
-
- if (duration !== _lastHTML5State.duration) {
-
- _lastHTML5State.duration = duration;
- _t.duration = duration;
- isNew = true;
-
- }
-
- // TODO: investigate why this goes wack if not set/re-set each time.
- _t.durationEstimate = _t.duration;
-
- time = (_t._a.currentTime * 1000 || 0);
-
- if (time !== _lastHTML5State.time) {
-
- _lastHTML5State.time = time;
- isNew = true;
-
- }
-
- if (isNew || bForce) {
-
- _t._whileplaying(time,x,x,x,x);
-
- }
-
- }/* else {
-
- // _s._wD('_onTimer: Warn for "'+_t.id+'": '+(!_t._a?'Could not find element. ':'')+(_t.playState === 0?'playState bad, 0?':'playState = '+_t.playState+', OK'));
-
- return false;
-
- }*/
-
- return isNew;
-
- }
-
- };
-
- this._get_html5_duration = function() {
-
- var _iO = _t._iO,
- d = (_t._a ? _t._a.duration*1000 : (_iO ? _iO.duration : undefined)),
- result = (d && !isNaN(d) && d !== Infinity ? d : (_iO ? _iO.duration : null));
-
- return result;
-
- };
-
- this._apply_loop = function(a, nLoops) {
-
- /**
- * boolean instead of "loop", for webkit? - spec says string. http://www.w3.org/TR/html-markup/audio.html#audio.attrs.loop
- * note that loop is either off or infinite under HTML5, unlike Flash which allows arbitrary loop counts to be specified.
- */
-
- // <d>
- if (!a.loop && nLoops > 1) {
- _s._wD('Note: Native HTML5 looping is infinite.');
- }
- // </d>
-
- a.loop = (nLoops > 1 ? 'loop' : '');
-
- };
-
- this._setup_html5 = function(oOptions) {
-
- var _iO = _mixin(_t._iO, oOptions), d = decodeURI,
- _a = _useGlobalHTML5Audio ? _s._global_a : _t._a,
- _dURL = d(_iO.url),
- _oldIO = (_a && _a._t ? _a._t.instanceOptions : null),
- result;
-
- if (_a) {
-
- if (_a._t) {
-
- if (!_useGlobalHTML5Audio && _dURL === d(_lastURL)) {
-
- // same url, ignore request
- result = _a;
-
- } else if (_useGlobalHTML5Audio && _oldIO.url === _iO.url && (!_lastURL || (_lastURL === _oldIO.url))) {
-
- // iOS-type reuse case
- result = _a;
-
- }
-
- if (result) {
-
- _t._apply_loop(_a, _iO.loops);
- return result;
-
- }
-
- }
-
- _s._wD('setting URL on existing object: ' + _dURL + (_lastURL ? ', old URL: ' + _lastURL : ''));
-
- /**
- * "First things first, I, Poppa.." (reset the previous state of the old sound, if playing)
- * Fixes case with devices that can only play one sound at a time
- * Otherwise, other sounds in mid-play will be terminated without warning and in a stuck state
- */
-
- if (_useGlobalHTML5Audio && _a._t && _a._t.playState && _iO.url !== _oldIO.url) {
-
- _a._t.stop();
-
- }
-
- // reset load/playstate, onPosition etc. if the URL is new.
- // somewhat-tricky object re-use vs. new SMSound object, old vs. new URL comparisons
- _resetProperties((_oldIO && _oldIO.url ? _iO.url === _oldIO.url : (_lastURL ? _lastURL === _iO.url : false)));
-
- _a.src = _iO.url;
- _t.url = _iO.url;
- _lastURL = _iO.url;
- _a._called_load = false;
-
- } else {
-
- _wDS('h5a');
-
- if (_iO.autoLoad || _iO.autoPlay) {
-
- _t._a = new Audio(_iO.url);
-
- } else {
-
- // null for stupid Opera 9.64 case
- _t._a = (_isOpera ? new Audio(null) : new Audio());
-
- }
-
- // assign local reference
- _a = _t._a;
-
- _a._called_load = false;
-
- if (_useGlobalHTML5Audio) {
-
- _s._global_a = _a;
-
- }
-
- }
-
- _t.isHTML5 = true;
-
- // store a ref on the track
- _t._a = _a;
-
- // store a ref on the audio
- _a._t = _t;
-
- _add_html5_events();
-
- _t._apply_loop(_a, _iO.loops);
-
- if (_iO.autoLoad || _iO.autoPlay) {
-
- _t.load();
-
- } else {
-
- // early HTML5 implementation (non-standard)
- _a.autobuffer = false;
-
- // standard ('none' is also an option.)
- _a.preload = 'auto';
-
- }
-
- return _a;
-
- };
-
- _add_html5_events = function() {
-
- if (_t._a._added_events) {
- return false;
- }
-
- var f;
-
- function add(oEvt, oFn, bCapture) {
- return _t._a ? _t._a.addEventListener(oEvt, oFn, bCapture||false) : null;
- }
-
- _t._a._added_events = true;
-
- for (f in _html5_events) {
- if (_html5_events.hasOwnProperty(f)) {
- add(f, _html5_events[f]);
- }
- }
-
- return true;
-
- };
-
- _remove_html5_events = function() {
-
- // Remove event listeners
-
- var f;
-
- function remove(oEvt, oFn, bCapture) {
- return (_t._a ? _t._a.removeEventListener(oEvt, oFn, bCapture||false) : null);
- }
-
- _s._wD(_h5+'removing event listeners: '+_t.id);
- _t._a._added_events = false;
-
- for (f in _html5_events) {
- if (_html5_events.hasOwnProperty(f)) {
- remove(f, _html5_events[f]);
- }
- }
-
- };
-
- /**
- * Pseudo-private event internals
- * ------------------------------
- */
-
- this._onload = function(nSuccess) {
-
-
- var fN,
- // check for duration to prevent false positives from flash 8 when loading from cache.
- loadOK = (!!(nSuccess) || (!_t.isHTML5 && _fV === 8 && _t.duration));
-
- // <d>
- fN = 'SMSound._onload(): ';
- _s._wD(fN + '"' + _t.id + '"' + (loadOK?' loaded.':' failed to load? - ' + _t.url), (loadOK?1:2));
- if (!loadOK && !_t.isHTML5) {
- if (_s.sandbox.noRemote === true) {
- _s._wD(fN + _str('noNet'), 1);
- }
- if (_s.sandbox.noLocal === true) {
- _s._wD(fN + _str('noLocal'), 1);
- }
- }
- // </d>
-
- _t.loaded = loadOK;
- _t.readyState = loadOK?3:2;
- _t._onbufferchange(0);
-
- if (_t._iO.onload) {
- _t._iO.onload.apply(_t, [loadOK]);
- }
-
- return true;
-
- };
-
- this._onbufferchange = function(nIsBuffering) {
-
- if (_t.playState === 0) {
- // ignore if not playing
- return false;
- }
-
- if ((nIsBuffering && _t.isBuffering) || (!nIsBuffering && !_t.isBuffering)) {
- return false;
- }
-
- _t.isBuffering = (nIsBuffering === 1);
- if (_t._iO.onbufferchange) {
- _s._wD('SMSound._onbufferchange(): ' + nIsBuffering);
- _t._iO.onbufferchange.apply(_t);
- }
-
- return true;
-
- };
-
- /**
- * Notify Mobile Safari that user action is required
- * to continue playing / loading the audio file.
- */
-
- this._onsuspend = function() {
-
- if (_t._iO.onsuspend) {
- _s._wD('SMSound._onsuspend()');
- _t._iO.onsuspend.apply(_t);
- }
-
- return true;
-
- };
-
- /**
- * flash 9/movieStar + RTMP-only method, should fire only once at most
- * at this point we just recreate failed sounds rather than trying to reconnect
- */
-
- this._onfailure = function(msg, level, code) {
-
- _t.failures++;
- _s._wD('SMSound._onfailure(): "'+_t.id+'" count '+_t.failures);
-
- if (_t._iO.onfailure && _t.failures === 1) {
- _t._iO.onfailure(_t, msg, level, code);
- } else {
- _s._wD('SMSound._onfailure(): ignoring');
- }
-
- };
-
- this._onfinish = function() {
-
- // store local copy before it gets trashed..
- var _io_onfinish = _t._iO.onfinish;
-
- _t._onbufferchange(0);
- _t._resetOnPosition(0);
-
- // reset some state items
- if (_t.instanceCount) {
-
- _t.instanceCount--;
-
- if (!_t.instanceCount) {
-
- // remove onPosition listeners, if any
- _detachOnPosition();
-
- // reset instance options
- _t.playState = 0;
- _t.paused = false;
- _t.instanceCount = 0;
- _t.instanceOptions = {};
- _t._iO = {};
- _stop_html5_timer();
-
- // reset position, too
- if (_t.isHTML5) {
- _t.position = 0;
- }
-
- }
-
- if (!_t.instanceCount || _t._iO.multiShotEvents) {
- // fire onfinish for last, or every instance
- if (_io_onfinish) {
- _s._wD('SMSound._onfinish(): "' + _t.id + '"');
- _io_onfinish.apply(_t);
- }
- }
-
- }
-
- };
-
- this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration, nBufferLength) {
-
- var _iO = _t._iO;
-
- _t.bytesLoaded = nBytesLoaded;
- _t.bytesTotal = nBytesTotal;
- _t.duration = Math.floor(nDuration);
- _t.bufferLength = nBufferLength;
-
- if (!_iO.isMovieStar) {
-
- if (_iO.duration) {
- // use duration from options, if specified and larger
- _t.durationEstimate = (_t.duration > _iO.duration) ? _t.duration : _iO.duration;
- } else {
- _t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10);
- }
-
- if (typeof _t.durationEstimate === 'undefined') {
- _t.durationEstimate = _t.duration;
- }
-
- } else {
-
- _t.durationEstimate = _t.duration;
-
- }
-
- // for flash, reflect sequential-load-style buffering
- if (!_t.isHTML5) {
- _t.buffered = [{
- 'start': 0,
- 'end': _t.duration
- }];
- }
-
- // allow whileloading to fire even if "load" fired under HTML5, due to HTTP range/partials
- if ((_t.readyState !== 3 || _t.isHTML5) && _iO.whileloading) {
- _iO.whileloading.apply(_t);
- }
-
- };
-
- this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) {
-
- var _iO = _t._iO,
- eqLeft;
-
- if (isNaN(nPosition) || nPosition === null) {
- // flash safety net
- return false;
- }
-
- // Safari HTML5 play() may return small -ve values when starting from position: 0, eg. -50.120396875. Unexpected/invalid per W3, I think. Normalize to 0.
- _t.position = Math.max(0, nPosition);
-
- _t._processOnPosition();
-
- if (!_t.isHTML5 && _fV > 8) {
-
- if (_iO.usePeakData && typeof oPeakData !== 'undefined' && oPeakData) {
- _t.peakData = {
- left: oPeakData.leftPeak,
- right: oPeakData.rightPeak
- };
- }
-
- if (_iO.useWaveformData && typeof oWaveformDataLeft !== 'undefined' && oWaveformDataLeft) {
- _t.waveformData = {
- left: oWaveformDataLeft.split(','),
- right: oWaveformDataRight.split(',')
- };
- }
-
- if (_iO.useEQData) {
- if (typeof oEQData !== 'undefined' && oEQData && oEQData.leftEQ) {
- eqLeft = oEQData.leftEQ.split(',');
- _t.eqData = eqLeft;
- _t.eqData.left = eqLeft;
- if (typeof oEQData.rightEQ !== 'undefined' && oEQData.rightEQ) {
- _t.eqData.right = oEQData.rightEQ.split(',');
- }
- }
- }
-
- }
-
- if (_t.playState === 1) {
-
- // special case/hack: ensure buffering is false if loading from cache (and not yet started)
- if (!_t.isHTML5 && _fV === 8 && !_t.position && _t.isBuffering) {
- _t._onbufferchange(0);
- }
-
- if (_iO.whileplaying) {
- // flash may call after actual finish
- _iO.whileplaying.apply(_t);
- }
-
- }
-
- return true;
-
- };
-
- this._oncaptiondata = function(oData) {
-
- /**
- * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature
- *
- * @param {object} oData
- */
-
- _s._wD('SMSound._oncaptiondata(): "' + this.id + '" caption data received.');
-
- _t.captiondata = oData;
-
- if (_t._iO.oncaptiondata) {
- _t._iO.oncaptiondata.apply(_t);
- }
-
- };
-
- this._onmetadata = function(oMDProps, oMDData) {
-
- /**
- * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature
- * RTMP may include song title, MovieStar content may include encoding info
- *
- * @param {array} oMDProps (names)
- * @param {array} oMDData (values)
- */
-
- _s._wD('SMSound._onmetadata(): "' + this.id + '" metadata received.');
-
- var oData = {}, i, j;
-
- for (i = 0, j = oMDProps.length; i < j; i++) {
- oData[oMDProps[i]] = oMDData[i];
- }
- _t.metadata = oData;
-
- if (_t._iO.onmetadata) {
- _t._iO.onmetadata.apply(_t);
- }
-
- };
-
- this._onid3 = function(oID3Props, oID3Data) {
-
- /**
- * internal: flash 8 + flash 9 ID3 feature
- * may include artist, song title etc.
- *
- * @param {array} oID3Props (names)
- * @param {array} oID3Data (values)
- */
-
- _s._wD('SMSound._onid3(): "' + this.id + '" ID3 data received.');
-
- var oData = [], i, j;
-
- for (i = 0, j = oID3Props.length; i < j; i++) {
- oData[oID3Props[i]] = oID3Data[i];
- }
- _t.id3 = _mixin(_t.id3, oData);
-
- if (_t._iO.onid3) {
- _t._iO.onid3.apply(_t);
- }
-
- };
-
- // flash/RTMP-only
-
- this._onconnect = function(bSuccess) {
-
- bSuccess = (bSuccess === 1);
- _s._wD('SMSound._onconnect(): "'+_t.id+'"'+(bSuccess?' connected.':' failed to connect? - '+_t.url), (bSuccess?1:2));
- _t.connected = bSuccess;
-
- if (bSuccess) {
-
- _t.failures = 0;
-
- if (_idCheck(_t.id)) {
- if (_t.getAutoPlay()) {
- // only update the play state if auto playing
- _t.play(undefined, _t.getAutoPlay());
- } else if (_t._iO.autoLoad) {
- _t.load();
- }
- }
-
- if (_t._iO.onconnect) {
- _t._iO.onconnect.apply(_t, [bSuccess]);
- }
-
- }
-
- };
-
- this._ondataerror = function(sError) {
-
- // flash 9 wave/eq data handler
- // hack: called at start, and end from flash at/after onfinish()
- if (_t.playState > 0) {
- _s._wD('SMSound._ondataerror(): ' + sError);
- if (_t._iO.ondataerror) {
- _t._iO.ondataerror.apply(_t);
- }
- }
-
- };
-
- }; // SMSound()
-
- /**
- * Private SoundManager internals
- * ------------------------------
- */
-
- _getDocument = function() {
-
- return (_doc.body || _doc._docElement || _doc.getElementsByTagName('div')[0]);
-
- };
-
- _id = function(sID) {
-
- return _doc.getElementById(sID);
-
- };
-
- _mixin = function(oMain, oAdd) {
-
- // non-destructive merge
- var o1 = (oMain || {}), o2, o;
-
- // if unspecified, o2 is the default options object
- o2 = (typeof oAdd === 'undefined' ? _s.defaultOptions : oAdd);
-
- for (o in o2) {
-
- if (o2.hasOwnProperty(o) && typeof o1[o] === 'undefined') {
-
- if (typeof o2[o] !== 'object' || o2[o] === null) {
-
- // assign directly
- o1[o] = o2[o];
-
- } else {
-
- // recurse through o2
- o1[o] = _mixin(o1[o], o2[o]);
-
- }
-
- }
-
- }
-
- return o1;
-
- };
-
- // additional soundManager properties that soundManager.setup() will accept
-
- _extraOptions = {
- 'onready': 1,
- 'ontimeout': 1,
- 'defaultOptions': 1,
- 'flash9Options': 1,
- 'movieStarOptions': 1
- };
-
- _assign = function(o, oParent) {
-
- /**
- * recursive assignment of properties, soundManager.setup() helper
- * allows property assignment based on whitelist
- */
-
- var i,
- result = true,
- hasParent = (typeof oParent !== 'undefined'),
- setupOptions = _s.setupOptions,
- extraOptions = _extraOptions;
-
- // <d>
-
- // if soundManager.setup() called, show accepted parameters.
-
- if (typeof o === 'undefined') {
-
- result = [];
-
- for (i in setupOptions) {
-
- if (setupOptions.hasOwnProperty(i)) {
- result.push(i);
- }
-
- }
-
- for (i in extraOptions) {
-
- if (extraOptions.hasOwnProperty(i)) {
-
- if (typeof _s[i] === 'object') {
-
- result.push(i+': {...}');
-
- } else if (_s[i] instanceof Function) {
-
- result.push(i+': function() {...}');
-
- } else {
-
- result.push(i);
-
- }
-
- }
-
- }
-
- _s._wD(_str('setup', result.join(', ')));
-
- return false;
-
- }
-
- // </d>
-
- for (i in o) {
-
- if (o.hasOwnProperty(i)) {
-
- // if not an {object} we want to recurse through...
-
- if (typeof o[i] !== 'object' || o[i] === null || o[i] instanceof Array) {
-
- // check "allowed" options
-
- if (hasParent && typeof extraOptions[oParent] !== 'undefined') {
-
- // valid recursive / nested object option, eg., { defaultOptions: { volume: 50 } }
- _s[oParent][i] = o[i];
-
- } else if (typeof setupOptions[i] !== 'undefined') {
-
- // special case: assign to setupOptions object, which soundManager property references
- _s.setupOptions[i] = o[i];
-
- // assign directly to soundManager, too
- _s[i] = o[i];
-
- } else if (typeof extraOptions[i] === 'undefined') {
-
- // invalid or disallowed parameter. complain.
- _complain(_str((typeof _s[i] === 'undefined' ? 'setupUndef' : 'setupError'), i), 2);
-
- result = false;
-
- } else {
-
- /**
- * valid extraOptions parameter.
- * is it a method, like onready/ontimeout? call it.
- * multiple parameters should be in an array, eg. soundManager.setup({onready: [myHandler, myScope]});
- */
-
- if (_s[i] instanceof Function) {
-
- _s[i].apply(_s, (o[i] instanceof Array? o[i] : [o[i]]));
-
- } else {
-
- // good old-fashioned direct assignment
- _s[i] = o[i];
-
- }
-
- }
-
- } else {
-
- // recursion case, eg., { defaultOptions: { ... } }
-
- if (typeof extraOptions[i] === 'undefined') {
-
- // invalid or disallowed parameter. complain.
- _complain(_str((typeof _s[i] === 'undefined' ? 'setupUndef' : 'setupError'), i), 2);
-
- result = false;
-
- } else {
-
- // recurse through object
- return _assign(o[i], i);
-
- }
-
- }
-
- }
-
- }
-
- return result;
-
- };
-
- _event = (function() {
-
- var old = (_win.attachEvent),
- evt = {
- add: (old?'attachEvent':'addEventListener'),
- remove: (old?'detachEvent':'removeEventListener')
- };
-
- function getArgs(oArgs) {
-
- var args = _slice.call(oArgs), len = args.length;
-
- if (old) {
- // prefix
- args[1] = 'on' + args[1];
- if (len > 3) {
- // no capture
- args.pop();
- }
- } else if (len === 3) {
- args.push(false);
- }
-
- return args;
-
- }
-
- function apply(args, sType) {
-
- var element = args.shift(),
- method = [evt[sType]];
-
- if (old) {
- element[method](args[0], args[1]);
- } else {
- element[method].apply(element, args);
- }
-
- }
-
- function add() {
-
- apply(getArgs(arguments), 'add');
-
- }
-
- function remove() {
-
- apply(getArgs(arguments), 'remove');
-
- }
-
- return {
- 'add': add,
- 'remove': remove
- };
-
- }());
-
- function _preferFlashCheck(kind) {
-
- // whether flash should play a given type
- return (_s.preferFlash && _hasFlash && !_s.ignoreFlash && (typeof _s.flash[kind] !== 'undefined' && _s.flash[kind]));
-
- }
-
- /**
- * Internal HTML5 event handling
- * -----------------------------
- */
-
- function _html5_event(oFn) {
-
- // wrap html5 event handlers so we don't call them on destroyed sounds
-
- return function(e) {
-
- var t = this._t,
- result;
-
- if (!t || !t._a) {
- // <d>
- if (t && t.id) {
- _s._wD(_h5+'ignoring '+e.type+': '+t.id);
- } else {
- _s._wD(_h5+'ignoring '+e.type);
- }
- // </d>
- result = null;
- } else {
- result = oFn.call(this, e);
- }
-
- return result;
-
- };
-
- }
-
- _html5_events = {
-
- // HTML5 event-name-to-handler map
-
- abort: _html5_event(function() {
-
- _s._wD(_h5+'abort: '+this._t.id);
-
- }),
-
- // enough has loaded to play
-
- canplay: _html5_event(function() {
-
- var t = this._t,
- position1K;
-
- if (t._html5_canplay) {
- // this event has already fired. ignore.
- return true;
- }
-
- t._html5_canplay = true;
- _s._wD(_h5+'canplay: '+t.id+', '+t.url);
- t._onbufferchange(0);
-
- // position according to instance options
- position1K = (typeof t._iO.position !== 'undefined' && !isNaN(t._iO.position)?t._iO.position/1000:null);
-
- // set the position if position was set before the sound loaded
- if (t.position && this.currentTime !== position1K) {
- _s._wD(_h5+'canplay: setting position to '+position1K);
- try {
- this.currentTime = position1K;
- } catch(ee) {
- _s._wD(_h5+'setting position of ' + position1K + ' failed: '+ee.message, 2);
- }
- }
-
- // hack for HTML5 from/to case
- if (t._iO._oncanplay) {
- t._iO._oncanplay();
- }
-
- }),
-
- canplaythrough: _html5_event(function() {
-
- var t = this._t;
-
- if (!t.loaded) {
- t._onbufferchange(0);
- t._whileloading(t.bytesLoaded, t.bytesTotal, t._get_html5_duration());
- t._onload(true);
- }
-
- }),
-
- // TODO: Reserved for potential use
- /*
- emptied: _html5_event(function() {
-
- _s._wD(_h5+'emptied: '+this._t.id);
-
- }),
- */
-
- ended: _html5_event(function() {
-
- var t = this._t;
-
- _s._wD(_h5+'ended: '+t.id);
- t._onfinish();
-
- }),
-
- error: _html5_event(function() {
-
- _s._wD(_h5+'error: '+this.error.code);
- // call load with error state?
- this._t._onload(false);
-
- }),
-
- loadeddata: _html5_event(function() {
-
- var t = this._t;
-
- _s._wD(_h5+'loadeddata: '+this._t.id);
-
- // safari seems to nicely report progress events, eventually totalling 100%
- if (!t._loaded && !_isSafari) {
- t.duration = t._get_html5_duration();
- }
-
- }),
-
- loadedmetadata: _html5_event(function() {
-
- _s._wD(_h5+'loadedmetadata: '+this._t.id);
-
- }),
-
- loadstart: _html5_event(function() {
-
- _s._wD(_h5+'loadstart: '+this._t.id);
- // assume buffering at first
- this._t._onbufferchange(1);
-
- }),
-
- play: _html5_event(function() {
-
- _s._wD(_h5+'play: '+this._t.id+', '+this._t.url);
- // once play starts, no buffering
- this._t._onbufferchange(0);
-
- }),
-
- playing: _html5_event(function() {
-
- _s._wD(_h5+'playing: '+this._t.id);
-
- // once play starts, no buffering
- this._t._onbufferchange(0);
-
- }),
-
- progress: _html5_event(function(e) {
-
- // note: can fire repeatedly after "loaded" event, due to use of HTTP range/partials
-
- var t = this._t,
- i, j, str, buffered = 0,
- isProgress = (e.type === 'progress'),
- ranges = e.target.buffered,
- // firefox 3.6 implements e.loaded/total (bytes)
- loaded = (e.loaded||0),
- total = (e.total||1);
-
- // reset the "buffered" (loaded byte ranges) array
- t.buffered = [];
-
- if (ranges && ranges.length) {
-
- // if loaded is 0, try TimeRanges implementation as % of load
- // https://developer.mozilla.org/en/DOM/TimeRanges
-
- // re-build "buffered" array
- for (i=0, j=ranges.length; i<j; i++) {
- t.buffered.push({
- 'start': ranges.start(i),
- 'end': ranges.end(i)
- });
- }
-
- // use the last value locally
- buffered = (ranges.end(0) - ranges.start(0));
-
- // linear case, buffer sum; does not account for seeking and HTTP partials / byte ranges
- loaded = buffered/e.target.duration;
-
- // <d>
- if (isProgress && ranges.length > 1) {
- str = [];
- j = ranges.length;
- for (i=0; i<j; i++) {
- str.push(e.target.buffered.start(i) +'-'+ e.target.buffered.end(i));
- }
- _s._wD(_h5+'progress: timeRanges: '+str.join(', '));
- }
-
- if (isProgress && !isNaN(loaded)) {
- _s._wD(_h5+'progress: '+t.id+': ' + Math.floor(loaded*100)+'% loaded');
- }
- // </d>
-
- }
-
- if (!isNaN(loaded)) {
-
- // if progress, likely not buffering
- t._onbufferchange(0);
- // TODO: prevent calls with duplicate values.
- t._whileloading(loaded, total, t._get_html5_duration());
- if (loaded && total && loaded === total) {
- // in case "onload" doesn't fire (eg. gecko 1.9.2)
- _html5_events.canplaythrough.call(this, e);
- }
-
- }
-
- }),
-
- ratechange: _html5_event(function() {
-
- _s._wD(_h5+'ratechange: '+this._t.id);
-
- }),
-
- suspend: _html5_event(function(e) {
-
- // download paused/stopped, may have finished (eg. onload)
- var t = this._t;
-
- _s._wD(_h5+'suspend: '+t.id);
- _html5_events.progress.call(this, e);
- t._onsuspend();
-
- }),
-
- stalled: _html5_event(function() {
-
- _s._wD(_h5+'stalled: '+this._t.id);
-
- }),
-
- timeupdate: _html5_event(function() {
-
- this._t._onTimer();
-
- }),
-
- waiting: _html5_event(function() {
-
- var t = this._t;
-
- // see also: seeking
- _s._wD(_h5+'waiting: '+t.id);
-
- // playback faster than download rate, etc.
- t._onbufferchange(1);
-
- })
-
- };
-
- _html5OK = function(iO) {
-
- // playability test based on URL or MIME type
-
- var result;
-
- if (iO.serverURL || (iO.type && _preferFlashCheck(iO.type))) {
-
- // RTMP, or preferring flash
- result = false;
-
- } else {
-
- // Use type, if specified. If HTML5-only mode, no other options, so just give 'er
- result = ((iO.type ? _html5CanPlay({type:iO.type}) : _html5CanPlay({url:iO.url}) || _s.html5Only));
-
- }
-
- return result;
-
- };
-
- _html5Unload = function(oAudio, url) {
-
- /**
- * Internal method: Unload media, and cancel any current/pending network requests.
- * Firefox can load an empty URL, which allegedly destroys the decoder and stops the download.
- * https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox#Stopping_the_download_of_media
- * However, Firefox has been seen loading a relative URL from '' and thus requesting the hosting page on unload.
- * Other UA behaviour is unclear, so everyone else gets an about:blank-style URL.
- */
-
- if (oAudio) {
- // Firefox likes '' for unload (used to work?) - however, may request hosting page URL (bad.) Most other UAs dislike '' and fail to unload.
- oAudio.src = url;
- }
-
- };
-
- _html5CanPlay = function(o) {
-
- /**
- * Try to find MIME, test and return truthiness
- * o = {
- * url: '/path/to/an.mp3',
- * type: 'audio/mp3'
- * }
- */
-
- if (!_s.useHTML5Audio || !_s.hasHTML5) {
- return false;
- }
-
- var url = (o.url || null),
- mime = (o.type || null),
- aF = _s.audioFormats,
- result,
- offset,
- fileExt,
- item;
-
- // account for known cases like audio/mp3
-
- if (mime && typeof _s.html5[mime] !== 'undefined') {
- return (_s.html5[mime] && !_preferFlashCheck(mime));
- }
-
- if (!_html5Ext) {
- _html5Ext = [];
- for (item in aF) {
- if (aF.hasOwnProperty(item)) {
- _html5Ext.push(item);
- if (aF[item].related) {
- _html5Ext = _html5Ext.concat(aF[item].related);
- }
- }
- }
- _html5Ext = new RegExp('\\.('+_html5Ext.join('|')+')(\\?.*)?$','i');
- }
-
- // TODO: Strip URL queries, etc.
- fileExt = (url ? url.toLowerCase().match(_html5Ext) : null);
-
- if (!fileExt || !fileExt.length) {
- if (!mime) {
- result = false;
- } else {
- // audio/mp3 -> mp3, result should be known
- offset = mime.indexOf(';');
- // strip "audio/X; codecs.."
- fileExt = (offset !== -1?mime.substr(0,offset):mime).substr(6);
- }
- } else {
- // match the raw extension name - "mp3", for example
- fileExt = fileExt[1];
- }
-
- if (fileExt && typeof _s.html5[fileExt] !== 'undefined') {
- // result known
- result = (_s.html5[fileExt] && !_preferFlashCheck(fileExt));
- } else {
- mime = 'audio/'+fileExt;
- result = _s.html5.canPlayType({type:mime});
- _s.html5[fileExt] = result;
- // _s._wD('canPlayType, found result: '+result);
- result = (result && _s.html5[mime] && !_preferFlashCheck(mime));
- }
-
- return result;
-
- };
-
- _testHTML5 = function() {
-
- if (!_s.useHTML5Audio || typeof Audio === 'undefined') {
- return false;
- }
-
- // double-whammy: Opera 9.64 throws WRONG_ARGUMENTS_ERR if no parameter passed to Audio(), and Webkit + iOS happily tries to load "null" as a URL. :/
- var a = (typeof Audio !== 'undefined' ? (_isOpera ? new Audio(null) : new Audio()) : null),
- item, lookup, support = {}, aF, i;
-
- function _cp(m) {
-
- var canPlay, i, j,
- result = false,
- isOK = false;
-
- if (!a || typeof a.canPlayType !== 'function') {
- return result;
- }
-
- if (m instanceof Array) {
- // iterate through all mime types, return any successes
- for (i=0, j=m.length; i<j && !isOK; i++) {
- if (_s.html5[m[i]] || a.canPlayType(m[i]).match(_s.html5Test)) {
- isOK = true;
- _s.html5[m[i]] = true;
- // note flash support, too
- _s.flash[m[i]] = !!(m[i].match(_flashMIME));
- }
- }
- result = isOK;
- } else {
- canPlay = (a && typeof a.canPlayType === 'function' ? a.canPlayType(m) : false);
- result = !!(canPlay && (canPlay.match(_s.html5Test)));
- }
-
- return result;
-
- }
-
- // test all registered formats + codecs
-
- aF = _s.audioFormats;
-
- for (item in aF) {
-
- if (aF.hasOwnProperty(item)) {
-
- lookup = 'audio/' + item;
-
- support[item] = _cp(aF[item].type);
-
- // write back generic type too, eg. audio/mp3
- support[lookup] = support[item];
-
- // assign flash
- if (item.match(_flashMIME)) {
-
- _s.flash[item] = true;
- _s.flash[lookup] = true;
-
- } else {
-
- _s.flash[item] = false;
- _s.flash[lookup] = false;
-
- }
-
- // assign result to related formats, too
-
- if (aF[item] && aF[item].related) {
-
- for (i=aF[item].related.length-1; i >= 0; i--) {
-
- // eg. audio/m4a
- support['audio/'+aF[item].related[i]] = support[item];
- _s.html5[aF[item].related[i]] = support[item];
- _s.flash[aF[item].related[i]] = support[item];
-
- }
-
- }
-
- }
-
- }
-
- support.canPlayType = (a?_cp:null);
- _s.html5 = _mixin(_s.html5, support);
-
- return true;
-
- };
-
- _strings = {
-
- // <d>
- notReady: 'Not loaded yet - wait for soundManager.onready()',
- notOK: 'Audio support is not available.',
- domError: _smc + 'createMovie(): appendChild/innerHTML call failed. DOM not ready or other error.',
- spcWmode: _smc + 'createMovie(): Removing wmode, preventing known SWF loading issue(s)',
- swf404: _sm + ': Verify that %s is a valid path.',
- tryDebug: 'Try ' + _sm + '.debugFlash = true for more security details (output goes to SWF.)',
- checkSWF: 'See SWF output for more debug info.',
- localFail: _sm + ': Non-HTTP page (' + _doc.location.protocol + ' URL?) Review Flash player security settings for this special case:\nhttp://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/',
- waitFocus: _sm + ': Special case: Waiting for SWF to load with window focus...',
- waitImpatient: _sm + ': Getting impatient, still waiting for Flash%s...',
- waitForever: _sm + ': Waiting indefinitely for Flash (will recover if unblocked)...',
- waitSWF: _sm + ': Retrying, waiting for 100% SWF load...',
- needFunction: _sm + ': Function object expected for %s',
- badID: 'Warning: Sound ID "%s" should be a string, starting with a non-numeric character',
- currentObj: '--- ' + _sm + '._debug(): Current sound objects ---',
- waitEI: _smc + 'initMovie(): Waiting for ExternalInterface call from Flash...',
- waitOnload: _sm + ': Waiting for window.onload()',
- docLoaded: _sm + ': Document already loaded',
- onload: _smc + 'initComplete(): calling soundManager.onload()',
- onloadOK: _sm + '.onload() complete',
- init: _smc + 'init()',
- didInit: _smc + 'init(): Already called?',
- flashJS: _sm + ': Attempting JS to Flash call...',
- secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html',
- badRemove: 'Warning: Failed to remove flash movie.',
- shutdown: _sm + '.disable(): Shutting down',
- queue: _sm + ': Queueing %s handler',
- smFail: _sm + ': Failed to initialise.',
- smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.',
- fbTimeout: 'No flash response, applying .'+_swfCSS.swfTimedout+' CSS...',
- fbLoaded: 'Flash loaded',
- fbHandler: _smc+'flashBlockHandler()',
- manURL: 'SMSound.load(): Using manually-assigned URL',
- onURL: _sm + '.load(): current URL already assigned.',
- badFV: _sm + '.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.',
- as2loop: 'Note: Setting stream:false so looping can work (flash 8 limitation)',
- noNSLoop: 'Note: Looping not implemented for MovieStar formats',
- needfl9: 'Note: Switching to flash 9, required for MP4 formats.',
- mfTimeout: 'Setting flashLoadTimeout = 0 (infinite) for off-screen, mobile flash case',
- mfOn: 'mobileFlash::enabling on-screen flash repositioning',
- policy: 'Enabling usePolicyFile for data access',
- setup: _sm + '.setup(): allowed parameters: %s',
- setupError: _sm + '.setup(): "%s" cannot be assigned with this method.',
- setupUndef: _sm + '.setup(): Could not find option "%s"',
- setupLate: _sm + '.setup(): url + flashVersion changes will not take effect until reboot().',
- h5a: 'creating HTML5 Audio() object'
- // </d>
-
- };
-
- _str = function() {
-
- // internal string replace helper.
- // arguments: o [,items to replace]
- // <d>
-
- // real array, please
- var args = _slice.call(arguments),
-
- // first arg
- o = args.shift(),
-
- str = (_strings && _strings[o]?_strings[o]:''), i, j;
- if (str && args && args.length) {
- for (i = 0, j = args.length; i < j; i++) {
- str = str.replace('%s', args[i]);
- }
- }
-
- return str;
- // </d>
-
- };
-
- _loopFix = function(sOpt) {
-
- // flash 8 requires stream = false for looping to work
- if (_fV === 8 && sOpt.loops > 1 && sOpt.stream) {
- _wDS('as2loop');
- sOpt.stream = false;
- }
-
- return sOpt;
-
- };
-
- _policyFix = function(sOpt, sPre) {
-
- if (sOpt && !sOpt.usePolicyFile && (sOpt.onid3 || sOpt.usePeakData || sOpt.useWaveformData || sOpt.useEQData)) {
- _s._wD((sPre || '') + _str('policy'));
- sOpt.usePolicyFile = true;
- }
-
- return sOpt;
-
- };
-
- _complain = function(sMsg) {
-
- // <d>
- if (typeof console !== 'undefined' && typeof console.warn !== 'undefined') {
- console.warn(sMsg);
- } else {
- _s._wD(sMsg);
- }
- // </d>
-
- };
-
- _doNothing = function() {
-
- return false;
-
- };
-
- _disableObject = function(o) {
-
- var oProp;
-
- for (oProp in o) {
- if (o.hasOwnProperty(oProp) && typeof o[oProp] === 'function') {
- o[oProp] = _doNothing;
- }
- }
-
- oProp = null;
-
- };
-
- _failSafely = function(bNoDisable) {
-
- // general failure exception handler
-
- if (typeof bNoDisable === 'undefined') {
- bNoDisable = false;
- }
-
- if (_disabled || bNoDisable) {
- _wDS('smFail', 2);
- _s.disable(bNoDisable);
- }
-
- };
-
- _normalizeMovieURL = function(smURL) {
-
- var urlParams = null, url;
-
- if (smURL) {
- if (smURL.match(/\.swf(\?.*)?$/i)) {
- urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?') + 4);
- if (urlParams) {
- // assume user knows what they're doing
- return smURL;
- }
- } else if (smURL.lastIndexOf('/') !== smURL.length - 1) {
- // append trailing slash, if needed
- smURL += '/';
- }
- }
-
- url = (smURL && smURL.lastIndexOf('/') !== - 1 ? smURL.substr(0, smURL.lastIndexOf('/') + 1) : './') + _s.movieURL;
-
- if (_s.noSWFCache) {
- url += ('?ts=' + new Date().getTime());
- }
-
- return url;
-
- };
-
- _setVersionInfo = function() {
-
- // short-hand for internal use
-
- _fV = parseInt(_s.flashVersion, 10);
-
- if (_fV !== 8 && _fV !== 9) {
- _s._wD(_str('badFV', _fV, _defaultFlashVersion));
- _s.flashVersion = _fV = _defaultFlashVersion;
- }
-
- // debug flash movie, if applicable
-
- var isDebug = (_s.debugMode || _s.debugFlash?'_debug.swf':'.swf');
-
- if (_s.useHTML5Audio && !_s.html5Only && _s.audioFormats.mp4.required && _fV < 9) {
- _s._wD(_str('needfl9'));
- _s.flashVersion = _fV = 9;
- }
-
- _s.version = _s.versionNumber + (_s.html5Only?' (HTML5-only mode)':(_fV === 9?' (AS3/Flash 9)':' (AS2/Flash 8)'));
-
- // set up default options
- if (_fV > 8) {
- // +flash 9 base options
- _s.defaultOptions = _mixin(_s.defaultOptions, _s.flash9Options);
- _s.features.buffering = true;
- // +moviestar support
- _s.defaultOptions = _mixin(_s.defaultOptions, _s.movieStarOptions);
- _s.filePatterns.flash9 = new RegExp('\\.(mp3|' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i');
- _s.features.movieStar = true;
- } else {
- _s.features.movieStar = false;
- }
-
- // regExp for flash canPlay(), etc.
- _s.filePattern = _s.filePatterns[(_fV !== 8?'flash9':'flash8')];
-
- // if applicable, use _debug versions of SWFs
- _s.movieURL = (_fV === 8?'soundmanager2.swf':'soundmanager2_flash9.swf').replace('.swf', isDebug);
-
- _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_fV > 8);
-
- };
-
- _setPolling = function(bPolling, bHighPerformance) {
-
- if (!_flash) {
- return false;
- }
-
- _flash._setPolling(bPolling, bHighPerformance);
-
- };
-
- _initDebug = function() {
-
- // starts debug mode, creating output <div> for UAs without console object
-
- // allow force of debug mode via URL
- if (_s.debugURLParam.test(_wl)) {
- _s.debugMode = true;
- }
-
- // <d>
- if (_id(_s.debugID)) {
- return false;
- }
-
- var oD, oDebug, oTarget, oToggle, tmp;
-
- if (_s.debugMode && !_id(_s.debugID) && (!_hasConsole || !_s.useConsole || !_s.consoleOnly)) {
-
- oD = _doc.createElement('div');
- oD.id = _s.debugID + '-toggle';
-
- oToggle = {
- 'position': 'fixed',
- 'bottom': '0px',
- 'right': '0px',
- 'width': '1.2em',
- 'height': '1.2em',
- 'lineHeight': '1.2em',
- 'margin': '2px',
- 'textAlign': 'center',
- 'border': '1px solid #999',
- 'cursor': 'pointer',
- 'background': '#fff',
- 'color': '#333',
- 'zIndex': 10001
- };
-
- oD.appendChild(_doc.createTextNode('-'));
- oD.onclick = _toggleDebug;
- oD.title = 'Toggle SM2 debug console';
-
- if (_ua.match(/msie 6/i)) {
- oD.style.position = 'absolute';
- oD.style.cursor = 'hand';
- }
-
- for (tmp in oToggle) {
- if (oToggle.hasOwnProperty(tmp)) {
- oD.style[tmp] = oToggle[tmp];
- }
- }
-
- oDebug = _doc.createElement('div');
- oDebug.id = _s.debugID;
- oDebug.style.display = (_s.debugMode?'block':'none');
-
- if (_s.debugMode && !_id(oD.id)) {
- try {
- oTarget = _getDocument();
- oTarget.appendChild(oD);
- } catch(e2) {
- throw new Error(_str('domError')+' \n'+e2.toString());
- }
- oTarget.appendChild(oDebug);
- }
-
- }
-
- oTarget = null;
- // </d>
-
- };
-
- _idCheck = this.getSoundById;
-
- // <d>
- _wDS = function(o, errorLevel) {
-
- return (!o ? '' : _s._wD(_str(o), errorLevel));
-
- };
-
- // last-resort debugging option
-
- if (_wl.indexOf('sm2-debug=alert') + 1 && _s.debugMode) {
- _s._wD = function(sText) {window.alert(sText);};
- }
-
- _toggleDebug = function() {
-
- var o = _id(_s.debugID),
- oT = _id(_s.debugID + '-toggle');
-
- if (!o) {
- return false;
- }
-
- if (_debugOpen) {
- // minimize
- oT.innerHTML = '+';
- o.style.display = 'none';
- } else {
- oT.innerHTML = '-';
- o.style.display = 'block';
- }
-
- _debugOpen = !_debugOpen;
-
- };
-
- _debugTS = function(sEventType, bSuccess, sMessage) {
-
- // troubleshooter debug hooks
-
- if (typeof sm2Debugger !== 'undefined') {
- try {
- sm2Debugger.handleEvent(sEventType, bSuccess, sMessage);
- } catch(e) {
- // oh well
- }
- }
-
- return true;
-
- };
- // </d>
-
- _getSWFCSS = function() {
-
- var css = [];
-
- if (_s.debugMode) {
- css.push(_swfCSS.sm2Debug);
- }
-
- if (_s.debugFlash) {
- css.push(_swfCSS.flashDebug);
- }
-
- if (_s.useHighPerformance) {
- css.push(_swfCSS.highPerf);
- }
-
- return css.join(' ');
-
- };
-
- _flashBlockHandler = function() {
-
- // *possible* flash block situation.
-
- var name = _str('fbHandler'),
- p = _s.getMoviePercent(),
- css = _swfCSS,
- error = {type:'FLASHBLOCK'};
-
- if (_s.html5Only) {
- return false;
- }
-
- if (!_s.ok()) {
-
- if (_needsFlash) {
- // make the movie more visible, so user can fix
- _s.oMC.className = _getSWFCSS() + ' ' + css.swfDefault + ' ' + (p === null?css.swfTimedout:css.swfError);
- _s._wD(name+': '+_str('fbTimeout')+(p?' ('+_str('fbLoaded')+')':''));
- }
-
- _s.didFlashBlock = true;
-
- // fire onready(), complain lightly
- _processOnEvents({type:'ontimeout', ignoreInit:true, error:error});
- _catchError(error);
-
- } else {
-
- // SM2 loaded OK (or recovered)
-
- // <d>
- if (_s.didFlashBlock) {
- _s._wD(name+': Unblocked');
- }
- // </d>
-
- if (_s.oMC) {
- _s.oMC.className = [_getSWFCSS(), css.swfDefault, css.swfLoaded + (_s.didFlashBlock?' '+css.swfUnblocked:'')].join(' ');
- }
-
- }
-
- };
-
- _addOnEvent = function(sType, oMethod, oScope) {
-
- if (typeof _on_queue[sType] === 'undefined') {
- _on_queue[sType] = [];
- }
-
- _on_queue[sType].push({
- 'method': oMethod,
- 'scope': (oScope || null),
- 'fired': false
- });
-
- };
-
- _processOnEvents = function(oOptions) {
-
- // if unspecified, assume OK/error
-
- if (!oOptions) {
- oOptions = {
- type: (_s.ok() ? 'onready' : 'ontimeout')
- };
- }
-
- if (!_didInit && oOptions && !oOptions.ignoreInit) {
- // not ready yet.
- return false;
- }
-
- if (oOptions.type === 'ontimeout' && (_s.ok() || (_disabled && !oOptions.ignoreInit))) {
- // invalid case
- return false;
- }
-
- var status = {
- success: (oOptions && oOptions.ignoreInit?_s.ok():!_disabled)
- },
-
- // queue specified by type, or none
- srcQueue = (oOptions && oOptions.type?_on_queue[oOptions.type]||[]:[]),
-
- queue = [], i, j,
- args = [status],
- canRetry = (_needsFlash && _s.useFlashBlock && !_s.ok());
-
- if (oOptions.error) {
- args[0].error = oOptions.error;
- }
-
- for (i = 0, j = srcQueue.length; i < j; i++) {
- if (srcQueue[i].fired !== true) {
- queue.push(srcQueue[i]);
- }
- }
-
- if (queue.length) {
- _s._wD(_sm + ': Firing ' + queue.length + ' '+oOptions.type+'() item' + (queue.length === 1?'':'s'));
- for (i = 0, j = queue.length; i < j; i++) {
- if (queue[i].scope) {
- queue[i].method.apply(queue[i].scope, args);
- } else {
- queue[i].method.apply(this, args);
- }
- if (!canRetry) {
- // flashblock case doesn't count here
- queue[i].fired = true;
- }
- }
- }
-
- return true;
-
- };
-
- _initUserOnload = function() {
-
- _win.setTimeout(function() {
-
- if (_s.useFlashBlock) {
- _flashBlockHandler();
- }
-
- _processOnEvents();
-
- // call user-defined "onload", scoped to window
-
- if (typeof _s.onload === 'function') {
- _wDS('onload', 1);
- _s.onload.apply(_win);
- _wDS('onloadOK', 1);
- }
-
- if (_s.waitForWindowLoad) {
- _event.add(_win, 'load', _initUserOnload);
- }
-
- },1);
-
- };
-
- _detectFlash = function() {
-
- // hat tip: Flash Detect library (BSD, (C) 2007) by Carl "DocYes" S. Yestrau - http://featureblend.com/javascript-flash-detection-library.html / http://featureblend.com/license.txt
-
- if (typeof _hasFlash !== 'undefined') {
- // this work has already been done.
- return _hasFlash;
- }
-
- var hasPlugin = false, n = navigator, nP = n.plugins, obj, type, types, AX = _win.ActiveXObject;
-
- if (nP && nP.length) {
- type = 'application/x-shockwave-flash';
- types = n.mimeTypes;
- if (types && types[type] && types[type].enabledPlugin && types[type].enabledPlugin.description) {
- hasPlugin = true;
- }
- } else if (typeof AX !== 'undefined') {
- try {
- obj = new AX('ShockwaveFlash.ShockwaveFlash');
- } catch(e) {
- // oh well
- }
- hasPlugin = (!!obj);
- }
-
- _hasFlash = hasPlugin;
-
- return hasPlugin;
-
- };
-
- _featureCheck = function() {
-
- var needsFlash,
- item,
- result = true,
- formats = _s.audioFormats,
- // iPhone <= 3.1 has broken HTML5 audio(), but firmware 3.2 (original iPad) + iOS4 works.
- isSpecial = (_is_iDevice && !!(_ua.match(/os (1|2|3_0|3_1)/i)));
-
- if (isSpecial) {
-
- // has Audio(), but is broken; let it load links directly.
- _s.hasHTML5 = false;
-
- // ignore flash case, however
- _s.html5Only = true;
-
- if (_s.oMC) {
- _s.oMC.style.display = 'none';
- }
-
- result = false;
-
- } else {
-
- if (_s.useHTML5Audio) {
-
- if (!_s.html5 || !_s.html5.canPlayType) {
- _s._wD('SoundManager: No HTML5 Audio() support detected.');
- _s.hasHTML5 = false;
- } else {
- _s.hasHTML5 = true;
- }
-
- // <d>
- if (_isBadSafari) {
- _s._wD(_smc+'Note: Buggy HTML5 Audio in Safari on this OS X release, see https://bugs.webkit.org/show_bug.cgi?id=32159 - '+(!_hasFlash?' would use flash fallback for MP3/MP4, but none detected.':'will use flash fallback for MP3/MP4, if available'),1);
- }
- // </d>
-
- }
-
- }
-
- if (_s.useHTML5Audio && _s.hasHTML5) {
-
- for (item in formats) {
- if (formats.hasOwnProperty(item)) {
- if ((formats[item].required && !_s.html5.canPlayType(formats[item].type)) || (_s.preferFlash && (_s.flash[item] || _s.flash[formats[item].type]))) {
- // flash may be required, or preferred for this format
- needsFlash = true;
- }
- }
- }
-
- }
-
- // sanity check...
- if (_s.ignoreFlash) {
- needsFlash = false;
- }
-
- _s.html5Only = (_s.hasHTML5 && _s.useHTML5Audio && !needsFlash);
-
- return (!_s.html5Only);
-
- };
-
- _parseURL = function(url) {
-
- /**
- * Internal: Finds and returns the first playable URL (or failing that, the first URL.)
- * @param {string or array} url A single URL string, OR, an array of URL strings or {url:'/path/to/resource', type:'audio/mp3'} objects.
- */
-
- var i, j, urlResult = 0, result;
-
- if (url instanceof Array) {
-
- // find the first good one
- for (i=0, j=url.length; i<j; i++) {
-
- if (url[i] instanceof Object) {
- // MIME check
- if (_s.canPlayMIME(url[i].type)) {
- urlResult = i;
- break;
- }
-
- } else if (_s.canPlayURL(url[i])) {
- // URL string check
- urlResult = i;
- break;
- }
-
- }
-
- // normalize to string
- if (url[urlResult].url) {
- url[urlResult] = url[urlResult].url;
- }
-
- result = url[urlResult];
-
- } else {
-
- // single URL case
- result = url;
-
- }
-
- return result;
-
- };
-
-
- _startTimer = function(oSound) {
-
- /**
- * attach a timer to this sound, and start an interval if needed
- */
-
- if (!oSound._hasTimer) {
-
- oSound._hasTimer = true;
-
- if (!_mobileHTML5 && _s.html5PollingInterval) {
-
- if (_h5IntervalTimer === null && _h5TimerCount === 0) {
-
- _h5IntervalTimer = _win.setInterval(_timerExecute, _s.html5PollingInterval);
-
- }
-
- _h5TimerCount++;
-
- }
-
- }
-
- };
-
- _stopTimer = function(oSound) {
-
- /**
- * detach a timer
- */
-
- if (oSound._hasTimer) {
-
- oSound._hasTimer = false;
-
- if (!_mobileHTML5 && _s.html5PollingInterval) {
-
- // interval will stop itself at next execution.
-
- _h5TimerCount--;
-
- }
-
- }
-
- };
-
- _timerExecute = function() {
-
- /**
- * manual polling for HTML5 progress events, ie., whileplaying() (can achieve greater precision than conservative default HTML5 interval)
- */
-
- var i;
-
- if (_h5IntervalTimer !== null && !_h5TimerCount) {
-
- // no active timers, stop polling interval.
-
- _win.clearInterval(_h5IntervalTimer);
-
- _h5IntervalTimer = null;
-
- return false;
-
- }
-
- // check all HTML5 sounds with timers
-
- for (i = _s.soundIDs.length-1; i >= 0; i--) {
-
- if (_s.sounds[_s.soundIDs[i]].isHTML5 && _s.sounds[_s.soundIDs[i]]._hasTimer) {
-
- _s.sounds[_s.soundIDs[i]]._onTimer();
-
- }
-
- }
-
- };
-
- _catchError = function(options) {
-
- options = (typeof options !== 'undefined' ? options : {});
-
- if (typeof _s.onerror === 'function') {
- _s.onerror.apply(_win, [{type:(typeof options.type !== 'undefined' ? options.type : null)}]);
- }
-
- if (typeof options.fatal !== 'undefined' && options.fatal) {
- _s.disable();
- }
-
- };
-
- _badSafariFix = function() {
-
- // special case: "bad" Safari (OS X 10.3 - 10.7) must fall back to flash for MP3/MP4
- if (!_isBadSafari || !_detectFlash()) {
- // doesn't apply
- return false;
- }
-
- var aF = _s.audioFormats, i, item;
-
- for (item in aF) {
- if (aF.hasOwnProperty(item)) {
- if (item === 'mp3' || item === 'mp4') {
- _s._wD(_sm+': Using flash fallback for '+item+' format');
- _s.html5[item] = false;
- // assign result to related formats, too
- if (aF[item] && aF[item].related) {
- for (i = aF[item].related.length-1; i >= 0; i--) {
- _s.html5[aF[item].related[i]] = false;
- }
- }
- }
- }
- }
-
- };
-
- /**
- * Pseudo-private flash/ExternalInterface methods
- * ----------------------------------------------
- */
-
- this._setSandboxType = function(sandboxType) {
-
- // <d>
- var sb = _s.sandbox;
-
- sb.type = sandboxType;
- sb.description = sb.types[(typeof sb.types[sandboxType] !== 'undefined'?sandboxType:'unknown')];
-
- _s._wD('Flash security sandbox type: ' + sb.type);
-
- if (sb.type === 'localWithFile') {
-
- sb.noRemote = true;
- sb.noLocal = false;
- _wDS('secNote', 2);
-
- } else if (sb.type === 'localWithNetwork') {
-
- sb.noRemote = false;
- sb.noLocal = true;
-
- } else if (sb.type === 'localTrusted') {
-
- sb.noRemote = false;
- sb.noLocal = false;
-
- }
- // </d>
-
- };
-
- this._externalInterfaceOK = function(flashDate, swfVersion) {
-
- // flash callback confirming flash loaded, EI working etc.
- // flashDate = approx. timing/delay info for JS/flash bridge
- // swfVersion: SWF build string
-
- if (_s.swfLoaded) {
- return false;
- }
-
- var e, eiTime = new Date().getTime();
-
- _s._wD(_smc+'externalInterfaceOK()' + (flashDate?' (~' + (eiTime - flashDate) + ' ms)':''));
- _debugTS('swf', true);
- _debugTS('flashtojs', true);
- _s.swfLoaded = true;
- _tryInitOnFocus = false;
-
- if (_isBadSafari) {
- _badSafariFix();
- }
-
- // complain if JS + SWF build/version strings don't match, excluding +DEV builds
- // <d>
- if (!swfVersion || swfVersion.replace(/\+dev/i,'') !== _s.versionNumber.replace(/\+dev/i, '')) {
-
- e = _sm + ': Fatal: JavaScript file build "' + _s.versionNumber + '" does not match Flash SWF build "' + swfVersion + '" at ' + _s.url + '. Ensure both are up-to-date.';
-
- // escape flash -> JS stack so this error fires in window.
- setTimeout(function versionMismatch() {
- throw new Error(e);
- }, 0);
-
- // exit, init will fail with timeout
- return false;
-
- }
- // </d>
-
- // slight delay before init
- setTimeout(_init, _isIE ? 100 : 1);
-
- };
-
- /**
- * Private initialization helpers
- * ------------------------------
- */
-
- _createMovie = function(smID, smURL) {
-
- if (_didAppend && _appendSuccess) {
- // ignore if already succeeded
- return false;
- }
-
- function _initMsg() {
- _s._wD('-- SoundManager 2 ' + _s.version + (!_s.html5Only && _s.useHTML5Audio?(_s.hasHTML5?' + HTML5 audio':', no HTML5 audio support'):'') + (!_s.html5Only ? (_s.useHighPerformance?', high performance mode, ':', ') + (( _s.flashPollingInterval ? 'custom (' + _s.flashPollingInterval + 'ms)' : 'normal') + ' polling') + (_s.wmode?', wmode: ' + _s.wmode:'') + (_s.debugFlash?', flash debug mode':'') + (_s.useFlashBlock?', flashBlock mode':'') : '') + ' --', 1);
- }
-
- if (_s.html5Only) {
-
- // 100% HTML5 mode
- _setVersionInfo();
-
- _initMsg();
- _s.oMC = _id(_s.movieID);
- _init();
-
- // prevent multiple init attempts
- _didAppend = true;
-
- _appendSuccess = true;
-
- return false;
-
- }
-
- // flash path
- var remoteURL = (smURL || _s.url),
- localURL = (_s.altURL || remoteURL),
- swfTitle = 'JS/Flash audio component (SoundManager 2)',
- oEmbed, oMovie, oTarget = _getDocument(), tmp, movieHTML, oEl, extraClass = _getSWFCSS(),
- s, x, sClass, isRTL = null,
- html = _doc.getElementsByTagName('html')[0];
-
- isRTL = (html && html.dir && html.dir.match(/rtl/i));
- smID = (typeof smID === 'undefined'?_s.id:smID);
-
- function param(name, value) {
- return '<param name="'+name+'" value="'+value+'" />';
- }
-
- // safety check for legacy (change to Flash 9 URL)
- _setVersionInfo();
- _s.url = _normalizeMovieURL(_overHTTP?remoteURL:localURL);
- smURL = _s.url;
-
- _s.wmode = (!_s.wmode && _s.useHighPerformance ? 'transparent' : _s.wmode);
-
- if (_s.wmode !== null && (_ua.match(/msie 8/i) || (!_isIE && !_s.useHighPerformance)) && navigator.platform.match(/win32|win64/i)) {
- /**
- * extra-special case: movie doesn't load until scrolled into view when using wmode = anything but 'window' here
- * does not apply when using high performance (position:fixed means on-screen), OR infinite flash load timeout
- * wmode breaks IE 8 on Vista + Win7 too in some cases, as of January 2011 (?)
- */
- _wDS('spcWmode');
- _s.wmode = null;
- }
-
- oEmbed = {
- 'name': smID,
- 'id': smID,
- 'src': smURL,
- 'quality': 'high',
- 'allowScriptAccess': _s.allowScriptAccess,
- 'bgcolor': _s.bgColor,
- 'pluginspage': _http+'www.macromedia.com/go/getflashplayer',
- 'title': swfTitle,
- 'type': 'application/x-shockwave-flash',
- 'wmode': _s.wmode,
- // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
- 'hasPriority': 'true'
- };
-
- if (_s.debugFlash) {
- oEmbed.FlashVars = 'debug=1';
- }
-
- if (!_s.wmode) {
- // don't write empty attribute
- delete oEmbed.wmode;
- }
-
- if (_isIE) {
-
- // IE is "special".
- oMovie = _doc.createElement('div');
- movieHTML = [
- '<object id="' + smID + '" data="' + smURL + '" type="' + oEmbed.type + '" title="' + oEmbed.title +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + _http+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">',
- param('movie', smURL),
- param('AllowScriptAccess', _s.allowScriptAccess),
- param('quality', oEmbed.quality),
- (_s.wmode? param('wmode', _s.wmode): ''),
- param('bgcolor', _s.bgColor),
- param('hasPriority', 'true'),
- (_s.debugFlash ? param('FlashVars', oEmbed.FlashVars) : ''),
- '</object>'
- ].join('');
-
- } else {
-
- oMovie = _doc.createElement('embed');
- for (tmp in oEmbed) {
- if (oEmbed.hasOwnProperty(tmp)) {
- oMovie.setAttribute(tmp, oEmbed[tmp]);
- }
- }
-
- }
-
- _initDebug();
- extraClass = _getSWFCSS();
- oTarget = _getDocument();
-
- if (oTarget) {
-
- _s.oMC = (_id(_s.movieID) || _doc.createElement('div'));
-
- if (!_s.oMC.id) {
-
- _s.oMC.id = _s.movieID;
- _s.oMC.className = _swfCSS.swfDefault + ' ' + extraClass;
- s = null;
- oEl = null;
-
- if (!_s.useFlashBlock) {
- if (_s.useHighPerformance) {
- // on-screen at all times
- s = {
- 'position': 'fixed',
- 'width': '8px',
- 'height': '8px',
- // >= 6px for flash to run fast, >= 8px to start up under Firefox/win32 in some cases. odd? yes.
- 'bottom': '0px',
- 'left': '0px',
- 'overflow': 'hidden'
- };
- } else {
- // hide off-screen, lower priority
- s = {
- 'position': 'absolute',
- 'width': '6px',
- 'height': '6px',
- 'top': '-9999px',
- 'left': '-9999px'
- };
- if (isRTL) {
- s.left = Math.abs(parseInt(s.left,10))+'px';
- }
- }
- }
-
- if (_isWebkit) {
- // soundcloud-reported render/crash fix, safari 5
- _s.oMC.style.zIndex = 10000;
- }
-
- if (!_s.debugFlash) {
- for (x in s) {
- if (s.hasOwnProperty(x)) {
- _s.oMC.style[x] = s[x];
- }
- }
- }
-
- try {
- if (!_isIE) {
- _s.oMC.appendChild(oMovie);
- }
- oTarget.appendChild(_s.oMC);
- if (_isIE) {
- oEl = _s.oMC.appendChild(_doc.createElement('div'));
- oEl.className = _swfCSS.swfBox;
- oEl.innerHTML = movieHTML;
- }
- _appendSuccess = true;
- } catch(e) {
- throw new Error(_str('domError')+' \n'+e.toString());
- }
-
- } else {
-
- // SM2 container is already in the document (eg. flashblock use case)
- sClass = _s.oMC.className;
- _s.oMC.className = (sClass?sClass+' ':_swfCSS.swfDefault) + (extraClass?' '+extraClass:'');
- _s.oMC.appendChild(oMovie);
- if (_isIE) {
- oEl = _s.oMC.appendChild(_doc.createElement('div'));
- oEl.className = _swfCSS.swfBox;
- oEl.innerHTML = movieHTML;
- }
- _appendSuccess = true;
-
- }
-
- }
-
- _didAppend = true;
- _initMsg();
- _s._wD(_smc+'createMovie(): Trying to load ' + smURL + (!_overHTTP && _s.altURL?' (alternate URL)':''), 1);
-
- return true;
-
- };
-
- _initMovie = function() {
-
- if (_s.html5Only) {
- _createMovie();
- return false;
- }
-
- // attempt to get, or create, movie
- // may already exist
- if (_flash) {
- return false;
- }
-
- // inline markup case
- _flash = _s.getMovie(_s.id);
-
- if (!_flash) {
- if (!_oRemoved) {
- // try to create
- _createMovie(_s.id, _s.url);
- } else {
- // try to re-append removed movie after reboot()
- if (!_isIE) {
- _s.oMC.appendChild(_oRemoved);
- } else {
- _s.oMC.innerHTML = _oRemovedHTML;
- }
- _oRemoved = null;
- _didAppend = true;
- }
- _flash = _s.getMovie(_s.id);
- }
-
- // <d>
- if (_flash) {
- _wDS('waitEI');
- }
- // </d>
-
- if (typeof _s.oninitmovie === 'function') {
- setTimeout(_s.oninitmovie, 1);
- }
-
- return true;
-
- };
-
- _delayWaitForEI = function() {
-
- setTimeout(_waitForEI, 1000);
-
- };
-
- _waitForEI = function() {
-
- var p,
- loadIncomplete = false;
-
- if (_waitingForEI) {
- return false;
- }
-
- _waitingForEI = true;
- _event.remove(_win, 'load', _delayWaitForEI);
-
- if (_tryInitOnFocus && !_isFocused) {
- // Safari won't load flash in background tabs, only when focused.
- _wDS('waitFocus');
- return false;
- }
-
- if (!_didInit) {
- p = _s.getMoviePercent();
- _s._wD(_str('waitImpatient', (p > 0 ? ' (SWF ' + p + '% loaded)' : '')));
- if (p > 0 && p < 100) {
- loadIncomplete = true;
- }
- }
-
- setTimeout(function() {
-
- p = _s.getMoviePercent();
-
- if (loadIncomplete) {
- // special case: if movie *partially* loaded, retry until it's 100% before assuming failure.
- _waitingForEI = false;
- _s._wD(_str('waitSWF'));
- _win.setTimeout(_delayWaitForEI, 1);
- return false;
- }
-
- // <d>
- if (!_didInit) {
- _s._wD(_sm + ': No Flash response within expected time.\nLikely causes: ' + (p === 0?'Loading ' + _s.movieURL + ' may have failed (and/or Flash ' + _fV + '+ not present?), ':'') + 'Flash blocked or JS-Flash security error.' + (_s.debugFlash?' ' + _str('checkSWF'):''), 2);
- if (!_overHTTP && p) {
- _wDS('localFail', 2);
- if (!_s.debugFlash) {
- _wDS('tryDebug', 2);
- }
- }
- if (p === 0) {
- // if 0 (not null), probably a 404.
- _s._wD(_str('swf404', _s.url));
- }
- _debugTS('flashtojs', false, ': Timed out' + _overHTTP?' (Check flash security or flash blockers)':' (No plugin/missing SWF?)');
- }
- // </d>
-
- // give up / time-out, depending
-
- if (!_didInit && _okToDisable) {
- if (p === null) {
- // SWF failed. Maybe blocked.
- if (_s.useFlashBlock || _s.flashLoadTimeout === 0) {
- if (_s.useFlashBlock) {
- _flashBlockHandler();
- }
- _wDS('waitForever');
- } else {
- // old SM2 behaviour, simply fail
- _failSafely(true);
- }
- } else {
- // flash loaded? Shouldn't be a blocking issue, then.
- if (_s.flashLoadTimeout === 0) {
- _wDS('waitForever');
- } else {
- _failSafely(true);
- }
- }
- }
-
- }, _s.flashLoadTimeout);
-
- };
-
- _handleFocus = function() {
-
- function cleanup() {
- _event.remove(_win, 'focus', _handleFocus);
- }
-
- if (_isFocused || !_tryInitOnFocus) {
- // already focused, or not special Safari background tab case
- cleanup();
- return true;
- }
-
- _okToDisable = true;
- _isFocused = true;
- _s._wD(_sm+': Got window focus.');
-
- // allow init to restart
- _waitingForEI = false;
-
- // kick off ExternalInterface timeout, now that the SWF has started
- _delayWaitForEI();
-
- cleanup();
- return true;
-
- };
-
- _showSupport = function() {
-
- var item, tests = [];
-
- if (_s.useHTML5Audio && _s.hasHTML5) {
- for (item in _s.audioFormats) {
- if (_s.audioFormats.hasOwnProperty(item)) {
- tests.push(item + ': ' + _s.html5[item] + (!_s.html5[item] && _hasFlash && _s.flash[item] ? ' (using flash)' : (_s.preferFlash && _s.flash[item] && _hasFlash ? ' (preferring flash)': (!_s.html5[item] ? ' (' + (_s.audioFormats[item].required ? 'required, ':'') + 'and no flash support)' : ''))));
- }
- }
- _s._wD('-- SoundManager 2: HTML5 support tests ('+_s.html5Test+'): '+tests.join(', ')+' --',1);
- }
-
- };
-
- _initComplete = function(bNoDisable) {
-
- if (_didInit) {
- return false;
- }
-
- if (_s.html5Only) {
- // all good.
- _s._wD('-- SoundManager 2: loaded --');
- _didInit = true;
- _initUserOnload();
- _debugTS('onload', true);
- return true;
- }
-
- var wasTimeout = (_s.useFlashBlock && _s.flashLoadTimeout && !_s.getMoviePercent()),
- result = true,
- error;
-
- if (!wasTimeout) {
- _didInit = true;
- if (_disabled) {
- error = {type: (!_hasFlash && _needsFlash ? 'NO_FLASH' : 'INIT_TIMEOUT')};
- }
- }
-
- _s._wD('-- SoundManager 2 ' + (_disabled?'failed to load':'loaded') + ' (' + (_disabled?'security/load error':'OK') + ') --', 1);
-
- if (_disabled || bNoDisable) {
- if (_s.useFlashBlock && _s.oMC) {
- _s.oMC.className = _getSWFCSS() + ' ' + (_s.getMoviePercent() === null?_swfCSS.swfTimedout:_swfCSS.swfError);
- }
- _processOnEvents({type:'ontimeout', error:error, ignoreInit: true});
- _debugTS('onload', false);
- _catchError(error);
- result = false;
- } else {
- _debugTS('onload', true);
- }
-
- if (!_disabled) {
- if (_s.waitForWindowLoad && !_windowLoaded) {
- _wDS('waitOnload');
- _event.add(_win, 'load', _initUserOnload);
- } else {
- // <d>
- if (_s.waitForWindowLoad && _windowLoaded) {
- _wDS('docLoaded');
- }
- // </d>
- _initUserOnload();
- }
- }
-
- return result;
-
- };
-
- /**
- * apply top-level setupOptions object as local properties, eg., this.setupOptions.flashVersion -> this.flashVersion (soundManager.flashVersion)
- * this maintains backward compatibility, and allows properties to be defined separately for use by soundManager.setup().
- */
-
- _setProperties = function() {
-
- var i,
- o = _s.setupOptions;
-
- for (i in o) {
-
- if (o.hasOwnProperty(i)) {
-
- // assign local property if not already defined
-
- if (typeof _s[i] === 'undefined') {
-
- _s[i] = o[i];
-
- } else if (_s[i] !== o[i]) {
-
- // legacy support: write manually-assigned property (eg., soundManager.url) back to setupOptions to keep things in sync
- _s.setupOptions[i] = _s[i];
-
- }
-
- }
-
- }
-
- };
-
-
- _init = function() {
-
- _wDS('init');
-
- // called after onload()
-
- if (_didInit) {
- _wDS('didInit');
- return false;
- }
-
- function _cleanup() {
- _event.remove(_win, 'load', _s.beginDelayedInit);
- }
-
- if (_s.html5Only) {
- if (!_didInit) {
- // we don't need no steenking flash!
- _cleanup();
- _s.enabled = true;
- _initComplete();
- }
- return true;
- }
-
- // flash path
- _initMovie();
-
- try {
-
- _wDS('flashJS');
-
- // attempt to talk to Flash
- _flash._externalInterfaceTest(false);
-
- // apply user-specified polling interval, OR, if "high performance" set, faster vs. default polling
- // (determines frequency of whileloading/whileplaying callbacks, effectively driving UI framerates)
- _setPolling(true, (_s.flashPollingInterval || (_s.useHighPerformance ? 10 : 50)));
-
- if (!_s.debugMode) {
- // stop the SWF from making debug output calls to JS
- _flash._disableDebug();
- }
-
- _s.enabled = true;
- _debugTS('jstoflash', true);
-
- if (!_s.html5Only) {
- // prevent browser from showing cached page state (or rather, restoring "suspended" page state) via back button, because flash may be dead
- // http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
- _event.add(_win, 'unload', _doNothing);
- }
-
- } catch(e) {
-
- _s._wD('js/flash exception: ' + e.toString());
- _debugTS('jstoflash', false);
- _catchError({type:'JS_TO_FLASH_EXCEPTION', fatal:true});
- // don't disable, for reboot()
- _failSafely(true);
- _initComplete();
-
- return false;
-
- }
-
- _initComplete();
-
- // disconnect events
- _cleanup();
-
- return true;
-
- };
-
- _domContentLoaded = function() {
-
- if (_didDCLoaded) {
- return false;
- }
-
- _didDCLoaded = true;
-
- // assign top-level soundManager properties eg. soundManager.url
- _setProperties();
-
- _initDebug();
-
- /**
- * Temporary feature: allow force of HTML5 via URL params: sm2-usehtml5audio=0 or 1
- * Ditto for sm2-preferFlash, too.
- */
- // <d>
- (function(){
-
- var a = 'sm2-usehtml5audio=',
- a2 = 'sm2-preferflash=',
- b = null,
- b2 = null,
- hasCon = (typeof console !== 'undefined' && typeof console.log === 'function'),
- l = _wl.toLowerCase();
-
- if (l.indexOf(a) !== -1) {
- b = (l.charAt(l.indexOf(a)+a.length) === '1');
- if (hasCon) {
- console.log((b?'Enabling ':'Disabling ')+'useHTML5Audio via URL parameter');
- }
- _s.setup({
- 'useHTML5Audio': b
- });
- }
-
- if (l.indexOf(a2) !== -1) {
- b2 = (l.charAt(l.indexOf(a2)+a2.length) === '1');
- if (hasCon) {
- console.log((b2?'Enabling ':'Disabling ')+'preferFlash via URL parameter');
- }
- _s.setup({
- 'preferFlash': b2
- });
- }
-
- }());
- // </d>
-
- if (!_hasFlash && _s.hasHTML5) {
- _s._wD('SoundManager: No Flash detected'+(!_s.useHTML5Audio?', enabling HTML5.':'. Trying HTML5-only mode.'));
- _s.setup({
- 'useHTML5Audio': true,
- // make sure we aren't preferring flash, either
- // TODO: preferFlash should not matter if flash is not installed. Currently, stuff breaks without the below tweak.
- 'preferFlash': false
- });
- }
-
- _testHTML5();
- _s.html5.usingFlash = _featureCheck();
- _needsFlash = _s.html5.usingFlash;
- _showSupport();
-
- if (!_hasFlash && _needsFlash) {
- _s._wD('SoundManager: Fatal error: Flash is needed to play some required formats, but is not available.');
- // TODO: Fatal here vs. timeout approach, etc.
- // hack: fail sooner.
- _s.setup({
- 'flashLoadTimeout': 1
- });
- }
-
- if (_doc.removeEventListener) {
- _doc.removeEventListener('DOMContentLoaded', _domContentLoaded, false);
- }
-
- _initMovie();
- return true;
-
- };
-
- _domContentLoadedIE = function() {
-
- if (_doc.readyState === 'complete') {
- _domContentLoaded();
- _doc.detachEvent('onreadystatechange', _domContentLoadedIE);
- }
-
- return true;
-
- };
-
- _winOnLoad = function() {
- // catch edge case of _initComplete() firing after window.load()
- _windowLoaded = true;
- _event.remove(_win, 'load', _winOnLoad);
- };
-
- // sniff up-front
- _detectFlash();
-
- // focus and window load, init (primarily flash-driven)
- _event.add(_win, 'focus', _handleFocus);
- _event.add(_win, 'load', _delayWaitForEI);
- _event.add(_win, 'load', _winOnLoad);
-
- if (_doc.addEventListener) {
-
- _doc.addEventListener('DOMContentLoaded', _domContentLoaded, false);
-
- } else if (_doc.attachEvent) {
-
- _doc.attachEvent('onreadystatechange', _domContentLoadedIE);
-
- } else {
-
- // no add/attachevent support - safe to assume no JS -> Flash either
- _debugTS('onload', false);
- _catchError({type:'NO_DOM2_EVENTS', fatal:true});
-
- }
-
- if (_doc.readyState === 'complete') {
- // DOMReady has already happened.
- setTimeout(_domContentLoaded,100);
- }
-
-} // SoundManager()
-
-// SM2_DEFER details: http://www.schillmania.com/projects/soundmanager2/doc/getstarted/#lazy-loading
-
-if (typeof SM2_DEFER === 'undefined' || !SM2_DEFER) {
- soundManager = new SoundManager();
-}
-
-/**
- * SoundManager public interfaces
- * ------------------------------
- */
-
-window.SoundManager = SoundManager; // constructor
-window.soundManager = soundManager; // public API, flash callbacks etc.
-
-}(window));
\ No newline at end of file
+(function(g,k){function U(U,ka){function V(b){return c.preferFlash&&v&&!c.ignoreFlash&&c.flash[b]!==k&&c.flash[b]}function q(b){return function(c){var d=this._s;return!d||!d._a?null:b.call(this,c)}}this.setupOptions={url:U||null,flashVersion:8,debugMode:!0,debugFlash:!1,useConsole:!0,consoleOnly:!0,waitForWindowLoad:!1,bgColor:"#ffffff",useHighPerformance:!1,flashPollingInterval:null,html5PollingInterval:null,flashLoadTimeout:1E3,wmode:null,allowScriptAccess:"always",useFlashBlock:!1,useHTML5Audio:!0,
+html5Test:/^(probably|maybe)$/i,preferFlash:!1,noSWFCache:!1,idPrefix:"sound"};this.defaultOptions={autoLoad:!1,autoPlay:!1,from:null,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onposition:null,onstop:null,onfailure:null,onfinish:null,multiShot:!0,multiShotEvents:!1,position:null,pan:0,stream:!0,to:null,type:null,usePolicyFile:!1,volume:100};this.flash9Options={isMovieStar:null,usePeakData:!1,useWaveformData:!1,useEQData:!1,onbufferchange:null,
+ondataerror:null};this.movieStarOptions={bufferTime:3,serverURL:null,onconnect:null,duration:null};this.audioFormats={mp3:{type:['audio/mpeg; codecs\x3d"mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:!0},mp4:{related:["aac","m4a","m4b"],type:['audio/mp4; codecs\x3d"mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:!1},ogg:{type:["audio/ogg; codecs\x3dvorbis"],required:!1},opus:{type:["audio/ogg; codecs\x3dopus","audio/opus"],required:!1},
+wav:{type:['audio/wav; codecs\x3d"1"',"audio/wav","audio/wave","audio/x-wav"],required:!1}};this.movieID="sm2-container";this.id=ka||"sm2movie";this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.versionNumber="V2.97a.20131201";this.altURL=this.movieURL=this.version=null;this.enabled=this.swfLoaded=!1;this.oMC=null;this.sounds={};this.soundIDs=[];this.didFlashBlock=this.muted=!1;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.features=
+{buffering:!1,peakData:!1,waveformData:!1,eqData:!1,movieStar:!1};this.sandbox={};this.html5={usingFlash:null};this.flash={};this.ignoreFlash=this.html5Only=!1;var Ja,c=this,Ka=null,l=null,W,s=navigator.userAgent,La=g.location.href.toString(),n=document,la,Ma,ma,m,x=[],K=!1,L=!1,p=!1,y=!1,na=!1,M,w,oa,X,pa,D,E,F,Na,qa,ra,Y,sa,Z,ta,G,ua,N,va,$,H,Oa,wa,Pa,xa,Qa,O=null,ya=null,P,za,I,aa,ba,r,Q=!1,Aa=!1,Ra,Sa,Ta,ca=0,R=null,da,Ua=[],S,u=null,Va,ea,T,z,fa,Ba,Wa,t,fb=Array.prototype.slice,A=!1,Ca,v,Da,
+Xa,B,ga,Ya=0,ha=s.match(/(ipad|iphone|ipod)/i),Za=s.match(/android/i),C=s.match(/msie/i),gb=s.match(/webkit/i),ia=s.match(/safari/i)&&!s.match(/chrome/i),Ea=s.match(/opera/i),Fa=s.match(/(mobile|pre\/|xoom)/i)||ha||Za,$a=!La.match(/usehtml5audio/i)&&!La.match(/sm2\-ignorebadua/i)&&ia&&!s.match(/silk/i)&&s.match(/OS X 10_6_([3-7])/i),Ga=n.hasFocus!==k?n.hasFocus():null,ja=ia&&(n.hasFocus===k||!n.hasFocus()),ab=!ja,bb=/(mp3|mp4|mpa|m4a|m4b)/i,Ha=n.location?n.location.protocol.match(/http/i):null,cb=
+!Ha?"http://":"",db=/^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|m4b|mp4v|3gp|3g2)\s*(?:$|;)/i,eb="mpeg4 aac flv mov mp4 m4v f4v m4a m4b mp4v 3gp 3g2".split(" "),hb=RegExp("\\.("+eb.join("|")+")(\\?.*)?$","i");this.mimePattern=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.useAltURL=!Ha;var Ia;try{Ia=Audio!==k&&(Ea&&opera!==k&&10>opera.version()?new Audio(null):new Audio).canPlayType!==k}catch(ib){Ia=!1}this.hasHTML5=Ia;this.setup=function(b){var e=!c.url;b!==k&&p&&u&&c.ok();oa(b);b&&
+(e&&(N&&b.url!==k)&&c.beginDelayedInit(),!N&&(b.url!==k&&"complete"===n.readyState)&&setTimeout(G,1));return c};this.supported=this.ok=function(){return u?p&&!y:c.useHTML5Audio&&c.hasHTML5};this.getMovie=function(b){return W(b)||n[b]||g[b]};this.createSound=function(b,e){function d(){a=aa(a);c.sounds[a.id]=new Ja(a);c.soundIDs.push(a.id);return c.sounds[a.id]}var a,f=null;if(!p||!c.ok())return!1;e!==k&&(b={id:b,url:e});a=w(b);a.url=da(a.url);void 0===a.id&&(a.id=c.setupOptions.idPrefix+Ya++);if(r(a.id,
+!0))return c.sounds[a.id];if(ea(a))f=d(),f._setup_html5(a);else{if(c.html5Only||c.html5.usingFlash&&a.url&&a.url.match(/data\:/i))return d();8<m&&null===a.isMovieStar&&(a.isMovieStar=!(!a.serverURL&&!(a.type&&a.type.match(db)||a.url&&a.url.match(hb))));a=ba(a,void 0);f=d();8===m?l._createSound(a.id,a.loops||1,a.usePolicyFile):(l._createSound(a.id,a.url,a.usePeakData,a.useWaveformData,a.useEQData,a.isMovieStar,a.isMovieStar?a.bufferTime:!1,a.loops||1,a.serverURL,a.duration||null,a.autoPlay,!0,a.autoLoad,
+a.usePolicyFile),a.serverURL||(f.connected=!0,a.onconnect&&a.onconnect.apply(f)));!a.serverURL&&(a.autoLoad||a.autoPlay)&&f.load(a)}!a.serverURL&&a.autoPlay&&f.play();return f};this.destroySound=function(b,e){if(!r(b))return!1;var d=c.sounds[b],a;d._iO={};d.stop();d.unload();for(a=0;a<c.soundIDs.length;a++)if(c.soundIDs[a]===b){c.soundIDs.splice(a,1);break}e||d.destruct(!0);delete c.sounds[b];return!0};this.load=function(b,e){return!r(b)?!1:c.sounds[b].load(e)};this.unload=function(b){return!r(b)?
+!1:c.sounds[b].unload()};this.onposition=this.onPosition=function(b,e,d,a){return!r(b)?!1:c.sounds[b].onposition(e,d,a)};this.clearOnPosition=function(b,e,d){return!r(b)?!1:c.sounds[b].clearOnPosition(e,d)};this.start=this.play=function(b,e){var d=null,a=e&&!(e instanceof Object);if(!p||!c.ok())return!1;if(r(b,a))a&&(e={url:e});else{if(!a)return!1;a&&(e={url:e});e&&e.url&&(e.id=b,d=c.createSound(e).play())}null===d&&(d=c.sounds[b].play(e));return d};this.setPosition=function(b,e){return!r(b)?!1:c.sounds[b].setPosition(e)};
+this.stop=function(b){return!r(b)?!1:c.sounds[b].stop()};this.stopAll=function(){for(var b in c.sounds)c.sounds.hasOwnProperty(b)&&c.sounds[b].stop()};this.pause=function(b){return!r(b)?!1:c.sounds[b].pause()};this.pauseAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].pause()};this.resume=function(b){return!r(b)?!1:c.sounds[b].resume()};this.resumeAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].resume()};this.togglePause=function(b){return!r(b)?
+!1:c.sounds[b].togglePause()};this.setPan=function(b,e){return!r(b)?!1:c.sounds[b].setPan(e)};this.setVolume=function(b,e){return!r(b)?!1:c.sounds[b].setVolume(e)};this.mute=function(b){var e=0;b instanceof String&&(b=null);if(b)return!r(b)?!1:c.sounds[b].mute();for(e=c.soundIDs.length-1;0<=e;e--)c.sounds[c.soundIDs[e]].mute();return c.muted=!0};this.muteAll=function(){c.mute()};this.unmute=function(b){b instanceof String&&(b=null);if(b)return!r(b)?!1:c.sounds[b].unmute();for(b=c.soundIDs.length-
+1;0<=b;b--)c.sounds[c.soundIDs[b]].unmute();c.muted=!1;return!0};this.unmuteAll=function(){c.unmute()};this.toggleMute=function(b){return!r(b)?!1:c.sounds[b].toggleMute()};this.getMemoryUse=function(){var b=0;l&&8!==m&&(b=parseInt(l._getMemoryUse(),10));return b};this.disable=function(b){var e;b===k&&(b=!1);if(y)return!1;y=!0;for(e=c.soundIDs.length-1;0<=e;e--)Pa(c.sounds[c.soundIDs[e]]);M(b);t.remove(g,"load",E);return!0};this.canPlayMIME=function(b){var e;c.hasHTML5&&(e=T({type:b}));!e&&u&&(e=b&&
+c.ok()?!!(8<m&&b.match(db)||b.match(c.mimePattern)):null);return e};this.canPlayURL=function(b){var e;c.hasHTML5&&(e=T({url:b}));!e&&u&&(e=b&&c.ok()?!!b.match(c.filePattern):null);return e};this.canPlayLink=function(b){return b.type!==k&&b.type&&c.canPlayMIME(b.type)?!0:c.canPlayURL(b.href)};this.getSoundById=function(b,e){return!b?null:c.sounds[b]};this.onready=function(b,c){if("function"===typeof b)c||(c=g),pa("onready",b,c),D();else throw P("needFunction","onready");return!0};this.ontimeout=function(b,
+c){if("function"===typeof b)c||(c=g),pa("ontimeout",b,c),D({type:"ontimeout"});else throw P("needFunction","ontimeout");return!0};this._wD=this._writeDebug=function(b,c){return!0};this._debug=function(){};this.reboot=function(b,e){var d,a,f;for(d=c.soundIDs.length-1;0<=d;d--)c.sounds[c.soundIDs[d]].destruct();if(l)try{C&&(ya=l.innerHTML),O=l.parentNode.removeChild(l)}catch(k){}ya=O=u=l=null;c.enabled=N=p=Q=Aa=K=L=y=A=c.swfLoaded=!1;c.soundIDs=[];c.sounds={};Ya=0;if(b)x=[];else for(d in x)if(x.hasOwnProperty(d)){a=
+0;for(f=x[d].length;a<f;a++)x[d][a].fired=!1}c.html5={usingFlash:null};c.flash={};c.html5Only=!1;c.ignoreFlash=!1;g.setTimeout(function(){ta();e||c.beginDelayedInit()},20);return c};this.reset=function(){return c.reboot(!0,!0)};this.getMoviePercent=function(){return l&&"PercentLoaded"in l?l.PercentLoaded():null};this.beginDelayedInit=function(){na=!0;G();setTimeout(function(){if(Aa)return!1;$();Z();return Aa=!0},20);F()};this.destruct=function(){c.disable(!0)};Ja=function(b){var e,d,a=this,f,h,J,
+g,n,q,s=!1,p=[],u=0,x,y,v=null,z;d=e=null;this.sID=this.id=b.id;this.url=b.url;this._iO=this.instanceOptions=this.options=w(b);this.pan=this.options.pan;this.volume=this.options.volume;this.isHTML5=!1;this._a=null;z=this.url?!1:!0;this.id3={};this._debug=function(){};this.load=function(b){var e=null,d;b!==k?a._iO=w(b,a.options):(b=a.options,a._iO=b,v&&v!==a.url&&(a._iO.url=a.url,a.url=null));a._iO.url||(a._iO.url=a.url);a._iO.url=da(a._iO.url);d=a.instanceOptions=a._iO;if(!d.url&&!a.url)return a;
+if(d.url===a.url&&0!==a.readyState&&2!==a.readyState)return 3===a.readyState&&d.onload&&ga(a,function(){d.onload.apply(a,[!!a.duration])}),a;a.loaded=!1;a.readyState=1;a.playState=0;a.id3={};if(ea(d))e=a._setup_html5(d),e._called_load||(a._html5_canplay=!1,a.url!==d.url&&(a._a.src=d.url,a.setPosition(0)),a._a.autobuffer="auto",a._a.preload="auto",a._a._called_load=!0);else{if(c.html5Only||a._iO.url&&a._iO.url.match(/data\:/i))return a;try{a.isHTML5=!1,a._iO=ba(aa(d)),d=a._iO,8===m?l._load(a.id,d.url,
+d.stream,d.autoPlay,d.usePolicyFile):l._load(a.id,d.url,!!d.stream,!!d.autoPlay,d.loops||1,!!d.autoLoad,d.usePolicyFile)}catch(f){H({type:"SMSOUND_LOAD_JS_EXCEPTION",fatal:!0})}}a.url=d.url;return a};this.unload=function(){0!==a.readyState&&(a.isHTML5?(g(),a._a&&(a._a.pause(),v=fa(a._a))):8===m?l._unload(a.id,"about:blank"):l._unload(a.id),f());return a};this.destruct=function(b){a.isHTML5?(g(),a._a&&(a._a.pause(),fa(a._a),A||J(),a._a._s=null,a._a=null)):(a._iO.onfailure=null,l._destroySound(a.id));
+b||c.destroySound(a.id,!0)};this.start=this.play=function(b,e){var d,f,h,g,J;f=!0;f=null;e=e===k?!0:e;b||(b={});a.url&&(a._iO.url=a.url);a._iO=w(a._iO,a.options);a._iO=w(b,a._iO);a._iO.url=da(a._iO.url);a.instanceOptions=a._iO;if(!a.isHTML5&&a._iO.serverURL&&!a.connected)return a.getAutoPlay()||a.setAutoPlay(!0),a;ea(a._iO)&&(a._setup_html5(a._iO),n());1===a.playState&&!a.paused&&(d=a._iO.multiShot,d||(a.isHTML5&&a.setPosition(a._iO.position),f=a));if(null!==f)return f;b.url&&b.url!==a.url&&(!a.readyState&&
+!a.isHTML5&&8===m&&z?z=!1:a.load(a._iO));a.loaded||(0===a.readyState?(!a.isHTML5&&!c.html5Only?(a._iO.autoPlay=!0,a.load(a._iO)):a.isHTML5?a.load(a._iO):f=a,a.instanceOptions=a._iO):2===a.readyState&&(f=a));if(null!==f)return f;!a.isHTML5&&(9===m&&0<a.position&&a.position===a.duration)&&(b.position=0);if(a.paused&&0<=a.position&&(!a._iO.serverURL||0<a.position))a.resume();else{a._iO=w(b,a._iO);if(null!==a._iO.from&&null!==a._iO.to&&0===a.instanceCount&&0===a.playState&&!a._iO.serverURL){d=function(){a._iO=
+w(b,a._iO);a.play(a._iO)};if(a.isHTML5&&!a._html5_canplay)a.load({_oncanplay:d}),f=!1;else if(!a.isHTML5&&!a.loaded&&(!a.readyState||2!==a.readyState))a.load({onload:d}),f=!1;if(null!==f)return f;a._iO=y()}(!a.instanceCount||a._iO.multiShotEvents||a.isHTML5&&a._iO.multiShot&&!A||!a.isHTML5&&8<m&&!a.getAutoPlay())&&a.instanceCount++;a._iO.onposition&&0===a.playState&&q(a);a.playState=1;a.paused=!1;a.position=a._iO.position!==k&&!isNaN(a._iO.position)?a._iO.position:0;a.isHTML5||(a._iO=ba(aa(a._iO)));
+a._iO.onplay&&e&&(a._iO.onplay.apply(a),s=!0);a.setVolume(a._iO.volume,!0);a.setPan(a._iO.pan,!0);a.isHTML5?2>a.instanceCount?(n(),f=a._setup_html5(),a.setPosition(a._iO.position),f.play()):(h=new Audio(a._iO.url),g=function(){t.remove(h,"ended",g);a._onfinish(a);fa(h);h=null},J=function(){t.remove(h,"canplay",J);try{h.currentTime=a._iO.position/1E3}catch(b){}h.play()},t.add(h,"ended",g),void 0!==a._iO.volume&&(h.volume=Math.max(0,Math.min(1,a._iO.volume/100))),a.muted&&(h.muted=!0),a._iO.position?
+t.add(h,"canplay",J):h.play()):(f=l._start(a.id,a._iO.loops||1,9===m?a.position:a.position/1E3,a._iO.multiShot||!1),9===m&&!f&&a._iO.onplayerror&&a._iO.onplayerror.apply(a))}return a};this.stop=function(b){var c=a._iO;1===a.playState&&(a._onbufferchange(0),a._resetOnPosition(0),a.paused=!1,a.isHTML5||(a.playState=0),x(),c.to&&a.clearOnPosition(c.to),a.isHTML5?a._a&&(b=a.position,a.setPosition(0),a.position=b,a._a.pause(),a.playState=0,a._onTimer(),g()):(l._stop(a.id,b),c.serverURL&&a.unload()),a.instanceCount=
+0,a._iO={},c.onstop&&c.onstop.apply(a));return a};this.setAutoPlay=function(b){a._iO.autoPlay=b;a.isHTML5||(l._setAutoPlay(a.id,b),b&&!a.instanceCount&&1===a.readyState&&a.instanceCount++)};this.getAutoPlay=function(){return a._iO.autoPlay};this.setPosition=function(b){b===k&&(b=0);var c=a.isHTML5?Math.max(b,0):Math.min(a.duration||a._iO.duration,Math.max(b,0));a.position=c;b=a.position/1E3;a._resetOnPosition(a.position);a._iO.position=c;if(a.isHTML5){if(a._a){if(a._html5_canplay){if(a._a.currentTime!==
+b)try{a._a.currentTime=b,(0===a.playState||a.paused)&&a._a.pause()}catch(e){}}else if(b)return a;a.paused&&a._onTimer(!0)}}else b=9===m?a.position:b,a.readyState&&2!==a.readyState&&l._setPosition(a.id,b,a.paused||!a.playState,a._iO.multiShot);return a};this.pause=function(b){if(a.paused||0===a.playState&&1!==a.readyState)return a;a.paused=!0;a.isHTML5?(a._setup_html5().pause(),g()):(b||b===k)&&l._pause(a.id,a._iO.multiShot);a._iO.onpause&&a._iO.onpause.apply(a);return a};this.resume=function(){var b=
+a._iO;if(!a.paused)return a;a.paused=!1;a.playState=1;a.isHTML5?(a._setup_html5().play(),n()):(b.isMovieStar&&!b.serverURL&&a.setPosition(a.position),l._pause(a.id,b.multiShot));!s&&b.onplay?(b.onplay.apply(a),s=!0):b.onresume&&b.onresume.apply(a);return a};this.togglePause=function(){if(0===a.playState)return a.play({position:9===m&&!a.isHTML5?a.position:a.position/1E3}),a;a.paused?a.resume():a.pause();return a};this.setPan=function(b,c){b===k&&(b=0);c===k&&(c=!1);a.isHTML5||l._setPan(a.id,b);a._iO.pan=
+b;c||(a.pan=b,a.options.pan=b);return a};this.setVolume=function(b,e){b===k&&(b=100);e===k&&(e=!1);a.isHTML5?a._a&&(c.muted&&!a.muted&&(a.muted=!0,a._a.muted=!0),a._a.volume=Math.max(0,Math.min(1,b/100))):l._setVolume(a.id,c.muted&&!a.muted||a.muted?0:b);a._iO.volume=b;e||(a.volume=b,a.options.volume=b);return a};this.mute=function(){a.muted=!0;a.isHTML5?a._a&&(a._a.muted=!0):l._setVolume(a.id,0);return a};this.unmute=function(){a.muted=!1;var b=a._iO.volume!==k;a.isHTML5?a._a&&(a._a.muted=!1):l._setVolume(a.id,
+b?a._iO.volume:a.options.volume);return a};this.toggleMute=function(){return a.muted?a.unmute():a.mute()};this.onposition=this.onPosition=function(b,c,e){p.push({position:parseInt(b,10),method:c,scope:e!==k?e:a,fired:!1});return a};this.clearOnPosition=function(a,b){var c;a=parseInt(a,10);if(isNaN(a))return!1;for(c=0;c<p.length;c++)if(a===p[c].position&&(!b||b===p[c].method))p[c].fired&&u--,p.splice(c,1)};this._processOnPosition=function(){var b,c;b=p.length;if(!b||!a.playState||u>=b)return!1;for(b-=
+1;0<=b;b--)c=p[b],!c.fired&&a.position>=c.position&&(c.fired=!0,u++,c.method.apply(c.scope,[c.position]));return!0};this._resetOnPosition=function(a){var b,c;b=p.length;if(!b)return!1;for(b-=1;0<=b;b--)c=p[b],c.fired&&a<=c.position&&(c.fired=!1,u--);return!0};y=function(){var b=a._iO,c=b.from,e=b.to,d,f;f=function(){a.clearOnPosition(e,f);a.stop()};d=function(){if(null!==e&&!isNaN(e))a.onPosition(e,f)};null!==c&&!isNaN(c)&&(b.position=c,b.multiShot=!1,d());return b};q=function(){var b,c=a._iO.onposition;
+if(c)for(b in c)if(c.hasOwnProperty(b))a.onPosition(parseInt(b,10),c[b])};x=function(){var b,c=a._iO.onposition;if(c)for(b in c)c.hasOwnProperty(b)&&a.clearOnPosition(parseInt(b,10))};n=function(){a.isHTML5&&Ra(a)};g=function(){a.isHTML5&&Sa(a)};f=function(b){b||(p=[],u=0);s=!1;a._hasTimer=null;a._a=null;a._html5_canplay=!1;a.bytesLoaded=null;a.bytesTotal=null;a.duration=a._iO&&a._iO.duration?a._iO.duration:null;a.durationEstimate=null;a.buffered=[];a.eqData=[];a.eqData.left=[];a.eqData.right=[];
+a.failures=0;a.isBuffering=!1;a.instanceOptions={};a.instanceCount=0;a.loaded=!1;a.metadata={};a.readyState=0;a.muted=!1;a.paused=!1;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.playState=0;a.position=null;a.id3={}};f();this._onTimer=function(b){var c,f=!1,h={};if(a._hasTimer||b){if(a._a&&(b||(0<a.playState||1===a.readyState)&&!a.paused))c=a._get_html5_duration(),c!==e&&(e=c,a.duration=c,f=!0),a.durationEstimate=a.duration,c=1E3*a._a.currentTime||0,c!==d&&(d=c,f=!0),(f||b)&&a._whileplaying(c,
+h,h,h,h);return f}};this._get_html5_duration=function(){var b=a._iO;return(b=a._a&&a._a.duration?1E3*a._a.duration:b&&b.duration?b.duration:null)&&!isNaN(b)&&Infinity!==b?b:null};this._apply_loop=function(a,b){a.loop=1<b?"loop":""};this._setup_html5=function(b){b=w(a._iO,b);var c=A?Ka:a._a,e=decodeURI(b.url),d;A?e===decodeURI(Ca)&&(d=!0):e===decodeURI(v)&&(d=!0);if(c){if(c._s)if(A)c._s&&(c._s.playState&&!d)&&c._s.stop();else if(!A&&e===decodeURI(v))return a._apply_loop(c,b.loops),c;d||(v&&f(!1),c.src=
+b.url,Ca=v=a.url=b.url,c._called_load=!1)}else b.autoLoad||b.autoPlay?(a._a=new Audio(b.url),a._a.load()):a._a=Ea&&10>opera.version()?new Audio(null):new Audio,c=a._a,c._called_load=!1,A&&(Ka=c);a.isHTML5=!0;a._a=c;c._s=a;h();a._apply_loop(c,b.loops);b.autoLoad||b.autoPlay?a.load():(c.autobuffer=!1,c.preload="auto");return c};h=function(){if(a._a._added_events)return!1;var b;a._a._added_events=!0;for(b in B)B.hasOwnProperty(b)&&a._a&&a._a.addEventListener(b,B[b],!1);return!0};J=function(){var b;a._a._added_events=
+!1;for(b in B)B.hasOwnProperty(b)&&a._a&&a._a.removeEventListener(b,B[b],!1)};this._onload=function(b){var c=!!b||!a.isHTML5&&8===m&&a.duration;a.loaded=c;a.readyState=c?3:2;a._onbufferchange(0);a._iO.onload&&ga(a,function(){a._iO.onload.apply(a,[c])});return!0};this._onbufferchange=function(b){if(0===a.playState||b&&a.isBuffering||!b&&!a.isBuffering)return!1;a.isBuffering=1===b;a._iO.onbufferchange&&a._iO.onbufferchange.apply(a);return!0};this._onsuspend=function(){a._iO.onsuspend&&a._iO.onsuspend.apply(a);
+return!0};this._onfailure=function(b,c,e){a.failures++;if(a._iO.onfailure&&1===a.failures)a._iO.onfailure(a,b,c,e)};this._onfinish=function(){var b=a._iO.onfinish;a._onbufferchange(0);a._resetOnPosition(0);a.instanceCount&&(a.instanceCount--,a.instanceCount||(x(),a.playState=0,a.paused=!1,a.instanceCount=0,a.instanceOptions={},a._iO={},g(),a.isHTML5&&(a.position=0)),(!a.instanceCount||a._iO.multiShotEvents)&&b&&ga(a,function(){b.apply(a)}))};this._whileloading=function(b,c,e,d){var f=a._iO;a.bytesLoaded=
+b;a.bytesTotal=c;a.duration=Math.floor(e);a.bufferLength=d;a.durationEstimate=!a.isHTML5&&!f.isMovieStar?f.duration?a.duration>f.duration?a.duration:f.duration:parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10):a.duration;a.isHTML5||(a.buffered=[{start:0,end:a.duration}]);(3!==a.readyState||a.isHTML5)&&f.whileloading&&f.whileloading.apply(a)};this._whileplaying=function(b,c,e,d,f){var h=a._iO;if(isNaN(b)||null===b)return!1;a.position=Math.max(0,b);a._processOnPosition();!a.isHTML5&&8<m&&(h.usePeakData&&
+(c!==k&&c)&&(a.peakData={left:c.leftPeak,right:c.rightPeak}),h.useWaveformData&&(e!==k&&e)&&(a.waveformData={left:e.split(","),right:d.split(",")}),h.useEQData&&(f!==k&&f&&f.leftEQ)&&(b=f.leftEQ.split(","),a.eqData=b,a.eqData.left=b,f.rightEQ!==k&&f.rightEQ&&(a.eqData.right=f.rightEQ.split(","))));1===a.playState&&(!a.isHTML5&&(8===m&&!a.position&&a.isBuffering)&&a._onbufferchange(0),h.whileplaying&&h.whileplaying.apply(a));return!0};this._oncaptiondata=function(b){a.captiondata=b;a._iO.oncaptiondata&&
+a._iO.oncaptiondata.apply(a,[b])};this._onmetadata=function(b,c){var e={},d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.metadata=e;a._iO.onmetadata&&a._iO.onmetadata.apply(a)};this._onid3=function(b,c){var e=[],d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.id3=w(a.id3,e);a._iO.onid3&&a._iO.onid3.apply(a)};this._onconnect=function(b){b=1===b;if(a.connected=b)a.failures=0,r(a.id)&&(a.getAutoPlay()?a.play(k,a.getAutoPlay()):a._iO.autoLoad&&a.load()),a._iO.onconnect&&a._iO.onconnect.apply(a,[b])};this._ondataerror=
+function(b){0<a.playState&&a._iO.ondataerror&&a._iO.ondataerror.apply(a)}};va=function(){return n.body||n.getElementsByTagName("div")[0]};W=function(b){return n.getElementById(b)};w=function(b,e){var d=b||{},a,f;a=e===k?c.defaultOptions:e;for(f in a)a.hasOwnProperty(f)&&d[f]===k&&(d[f]="object"!==typeof a[f]||null===a[f]?a[f]:w(d[f],a[f]));return d};ga=function(b,c){!b.isHTML5&&8===m?g.setTimeout(c,0):c()};X={onready:1,ontimeout:1,defaultOptions:1,flash9Options:1,movieStarOptions:1};oa=function(b,
+e){var d,a=!0,f=e!==k,h=c.setupOptions;for(d in b)if(b.hasOwnProperty(d))if("object"!==typeof b[d]||null===b[d]||b[d]instanceof Array||b[d]instanceof RegExp)f&&X[e]!==k?c[e][d]=b[d]:h[d]!==k?(c.setupOptions[d]=b[d],c[d]=b[d]):X[d]===k?a=!1:c[d]instanceof Function?c[d].apply(c,b[d]instanceof Array?b[d]:[b[d]]):c[d]=b[d];else if(X[d]===k)a=!1;else return oa(b[d],d);return a};t=function(){function b(a){a=fb.call(a);var b=a.length;d?(a[1]="on"+a[1],3<b&&a.pop()):3===b&&a.push(!1);return a}function c(b,
+e){var k=b.shift(),g=[a[e]];if(d)k[g](b[0],b[1]);else k[g].apply(k,b)}var d=g.attachEvent,a={add:d?"attachEvent":"addEventListener",remove:d?"detachEvent":"removeEventListener"};return{add:function(){c(b(arguments),"add")},remove:function(){c(b(arguments),"remove")}}}();B={abort:q(function(){}),canplay:q(function(){var b=this._s,c;if(b._html5_canplay)return!0;b._html5_canplay=!0;b._onbufferchange(0);c=b._iO.position!==k&&!isNaN(b._iO.position)?b._iO.position/1E3:null;if(b.position&&this.currentTime!==
+c)try{this.currentTime=c}catch(d){}b._iO._oncanplay&&b._iO._oncanplay()}),canplaythrough:q(function(){var b=this._s;b.loaded||(b._onbufferchange(0),b._whileloading(b.bytesLoaded,b.bytesTotal,b._get_html5_duration()),b._onload(!0))}),ended:q(function(){this._s._onfinish()}),error:q(function(){this._s._onload(!1)}),loadeddata:q(function(){var b=this._s;!b._loaded&&!ia&&(b.duration=b._get_html5_duration())}),loadedmetadata:q(function(){}),loadstart:q(function(){this._s._onbufferchange(1)}),play:q(function(){this._s._onbufferchange(0)}),
+playing:q(function(){this._s._onbufferchange(0)}),progress:q(function(b){var c=this._s,d,a,f=0,f=b.target.buffered;d=b.loaded||0;var h=b.total||1;c.buffered=[];if(f&&f.length){d=0;for(a=f.length;d<a;d++)c.buffered.push({start:1E3*f.start(d),end:1E3*f.end(d)});f=1E3*(f.end(0)-f.start(0));d=Math.min(1,f/(1E3*b.target.duration))}isNaN(d)||(c._onbufferchange(0),c._whileloading(d,h,c._get_html5_duration()),d&&(h&&d===h)&&B.canplaythrough.call(this,b))}),ratechange:q(function(){}),suspend:q(function(b){var c=
+this._s;B.progress.call(this,b);c._onsuspend()}),stalled:q(function(){}),timeupdate:q(function(){this._s._onTimer()}),waiting:q(function(){this._s._onbufferchange(1)})};ea=function(b){return!b||!b.type&&!b.url&&!b.serverURL?!1:b.serverURL||b.type&&V(b.type)?!1:b.type?T({type:b.type}):T({url:b.url})||c.html5Only||b.url.match(/data\:/i)};fa=function(b){var e;b&&(e=ia?"about:blank":c.html5.canPlayType("audio/wav")?"data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w\x3d\x3d":
+"about:blank",b.src=e,void 0!==b._called_unload&&(b._called_load=!1));A&&(Ca=null);return e};T=function(b){if(!c.useHTML5Audio||!c.hasHTML5)return!1;var e=b.url||null;b=b.type||null;var d=c.audioFormats,a;if(b&&c.html5[b]!==k)return c.html5[b]&&!V(b);if(!z){z=[];for(a in d)d.hasOwnProperty(a)&&(z.push(a),d[a].related&&(z=z.concat(d[a].related)));z=RegExp("\\.("+z.join("|")+")(\\?.*)?$","i")}a=e?e.toLowerCase().match(z):null;!a||!a.length?b&&(e=b.indexOf(";"),a=(-1!==e?b.substr(0,e):b).substr(6)):
+a=a[1];a&&c.html5[a]!==k?e=c.html5[a]&&!V(a):(b="audio/"+a,e=c.html5.canPlayType({type:b}),e=(c.html5[a]=e)&&c.html5[b]&&!V(b));return e};Wa=function(){function b(a){var b,d=b=!1;if(!e||"function"!==typeof e.canPlayType)return b;if(a instanceof Array){g=0;for(b=a.length;g<b;g++)if(c.html5[a[g]]||e.canPlayType(a[g]).match(c.html5Test))d=!0,c.html5[a[g]]=!0,c.flash[a[g]]=!!a[g].match(bb);b=d}else a=e&&"function"===typeof e.canPlayType?e.canPlayType(a):!1,b=!(!a||!a.match(c.html5Test));return b}if(!c.useHTML5Audio||
+!c.hasHTML5)return u=c.html5.usingFlash=!0,!1;var e=Audio!==k?Ea&&10>opera.version()?new Audio(null):new Audio:null,d,a,f={},h,g;h=c.audioFormats;for(d in h)if(h.hasOwnProperty(d)&&(a="audio/"+d,f[d]=b(h[d].type),f[a]=f[d],d.match(bb)?(c.flash[d]=!0,c.flash[a]=!0):(c.flash[d]=!1,c.flash[a]=!1),h[d]&&h[d].related))for(g=h[d].related.length-1;0<=g;g--)f["audio/"+h[d].related[g]]=f[d],c.html5[h[d].related[g]]=f[d],c.flash[h[d].related[g]]=f[d];f.canPlayType=e?b:null;c.html5=w(c.html5,f);c.html5.usingFlash=
+Va();u=c.html5.usingFlash;return!0};sa={};P=function(){};aa=function(b){8===m&&(1<b.loops&&b.stream)&&(b.stream=!1);return b};ba=function(b,c){if(b&&!b.usePolicyFile&&(b.onid3||b.usePeakData||b.useWaveformData||b.useEQData))b.usePolicyFile=!0;return b};la=function(){return!1};Pa=function(b){for(var c in b)b.hasOwnProperty(c)&&"function"===typeof b[c]&&(b[c]=la)};xa=function(b){b===k&&(b=!1);(y||b)&&c.disable(b)};Qa=function(b){var e=null;if(b)if(b.match(/\.swf(\?.*)?$/i)){if(e=b.substr(b.toLowerCase().lastIndexOf(".swf?")+
+4))return b}else b.lastIndexOf("/")!==b.length-1&&(b+="/");b=(b&&-1!==b.lastIndexOf("/")?b.substr(0,b.lastIndexOf("/")+1):"./")+c.movieURL;c.noSWFCache&&(b+="?ts\x3d"+(new Date).getTime());return b};ra=function(){m=parseInt(c.flashVersion,10);8!==m&&9!==m&&(c.flashVersion=m=8);var b=c.debugMode||c.debugFlash?"_debug.swf":".swf";c.useHTML5Audio&&(!c.html5Only&&c.audioFormats.mp4.required&&9>m)&&(c.flashVersion=m=9);c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===m?" (AS3/Flash 9)":
+" (AS2/Flash 8)");8<m?(c.defaultOptions=w(c.defaultOptions,c.flash9Options),c.features.buffering=!0,c.defaultOptions=w(c.defaultOptions,c.movieStarOptions),c.filePatterns.flash9=RegExp("\\.(mp3|"+eb.join("|")+")(\\?.*)?$","i"),c.features.movieStar=!0):c.features.movieStar=!1;c.filePattern=c.filePatterns[8!==m?"flash9":"flash8"];c.movieURL=(8===m?"soundmanager2.swf":"soundmanager2_flash9.swf").replace(".swf",b);c.features.peakData=c.features.waveformData=c.features.eqData=8<m};Oa=function(b,c){if(!l)return!1;
+l._setPolling(b,c)};wa=function(){};r=this.getSoundById;I=function(){var b=[];c.debugMode&&b.push("sm2_debug");c.debugFlash&&b.push("flash_debug");c.useHighPerformance&&b.push("high_performance");return b.join(" ")};za=function(){P("fbHandler");var b=c.getMoviePercent(),e={type:"FLASHBLOCK"};if(c.html5Only)return!1;c.ok()?c.oMC&&(c.oMC.className=[I(),"movieContainer","swf_loaded"+(c.didFlashBlock?" swf_unblocked":"")].join(" ")):(u&&(c.oMC.className=I()+" movieContainer "+(null===b?"swf_timedout":
+"swf_error")),c.didFlashBlock=!0,D({type:"ontimeout",ignoreInit:!0,error:e}),H(e))};pa=function(b,c,d){x[b]===k&&(x[b]=[]);x[b].push({method:c,scope:d||null,fired:!1})};D=function(b){b||(b={type:c.ok()?"onready":"ontimeout"});if(!p&&b&&!b.ignoreInit||"ontimeout"===b.type&&(c.ok()||y&&!b.ignoreInit))return!1;var e={success:b&&b.ignoreInit?c.ok():!y},d=b&&b.type?x[b.type]||[]:[],a=[],f,e=[e],h=u&&!c.ok();b.error&&(e[0].error=b.error);b=0;for(f=d.length;b<f;b++)!0!==d[b].fired&&a.push(d[b]);if(a.length){b=
+0;for(f=a.length;b<f;b++)a[b].scope?a[b].method.apply(a[b].scope,e):a[b].method.apply(this,e),h||(a[b].fired=!0)}return!0};E=function(){g.setTimeout(function(){c.useFlashBlock&&za();D();"function"===typeof c.onload&&c.onload.apply(g);c.waitForWindowLoad&&t.add(g,"load",E)},1)};Da=function(){if(v!==k)return v;var b=!1,c=navigator,d=c.plugins,a,f=g.ActiveXObject;if(d&&d.length)(c=c.mimeTypes)&&(c["application/x-shockwave-flash"]&&c["application/x-shockwave-flash"].enabledPlugin&&c["application/x-shockwave-flash"].enabledPlugin.description)&&
+(b=!0);else if(f!==k&&!s.match(/MSAppHost/i)){try{a=new f("ShockwaveFlash.ShockwaveFlash")}catch(h){a=null}b=!!a}return v=b};Va=function(){var b,e,d=c.audioFormats;if(ha&&s.match(/os (1|2|3_0|3_1)/i))c.hasHTML5=!1,c.html5Only=!0,c.oMC&&(c.oMC.style.display="none");else if(c.useHTML5Audio&&(!c.html5||!c.html5.canPlayType))c.hasHTML5=!1;if(c.useHTML5Audio&&c.hasHTML5)for(e in S=!0,d)if(d.hasOwnProperty(e)&&d[e].required)if(c.html5.canPlayType(d[e].type)){if(c.preferFlash&&(c.flash[e]||c.flash[d[e].type]))b=
+!0}else S=!1,b=!0;c.ignoreFlash&&(b=!1,S=!0);c.html5Only=c.hasHTML5&&c.useHTML5Audio&&!b;return!c.html5Only};da=function(b){var e,d,a=0;if(b instanceof Array){e=0;for(d=b.length;e<d;e++)if(b[e]instanceof Object){if(c.canPlayMIME(b[e].type)){a=e;break}}else if(c.canPlayURL(b[e])){a=e;break}b[a].url&&(b[a]=b[a].url);b=b[a]}return b};Ra=function(b){b._hasTimer||(b._hasTimer=!0,!Fa&&c.html5PollingInterval&&(null===R&&0===ca&&(R=setInterval(Ta,c.html5PollingInterval)),ca++))};Sa=function(b){b._hasTimer&&
+(b._hasTimer=!1,!Fa&&c.html5PollingInterval&&ca--)};Ta=function(){var b;if(null!==R&&!ca)return clearInterval(R),R=null,!1;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].isHTML5&&c.sounds[c.soundIDs[b]]._hasTimer&&c.sounds[c.soundIDs[b]]._onTimer()};H=function(b){b=b!==k?b:{};"function"===typeof c.onerror&&c.onerror.apply(g,[{type:b.type!==k?b.type:null}]);b.fatal!==k&&b.fatal&&c.disable()};Xa=function(){if(!$a||!Da())return!1;var b=c.audioFormats,e,d;for(d in b)if(b.hasOwnProperty(d)&&
+("mp3"===d||"mp4"===d))if(c.html5[d]=!1,b[d]&&b[d].related)for(e=b[d].related.length-1;0<=e;e--)c.html5[b[d].related[e]]=!1};this._setSandboxType=function(b){};this._externalInterfaceOK=function(b){if(c.swfLoaded)return!1;c.swfLoaded=!0;ja=!1;$a&&Xa();setTimeout(ma,C?100:1)};$=function(b,e){function d(a,b){return'\x3cparam name\x3d"'+a+'" value\x3d"'+b+'" /\x3e'}if(K&&L)return!1;if(c.html5Only)return ra(),c.oMC=W(c.movieID),ma(),L=K=!0,!1;var a=e||c.url,f=c.altURL||a,h=va(),g=I(),l=null,l=n.getElementsByTagName("html")[0],
+m,p,q,l=l&&l.dir&&l.dir.match(/rtl/i);b=b===k?c.id:b;ra();c.url=Qa(Ha?a:f);e=c.url;c.wmode=!c.wmode&&c.useHighPerformance?"transparent":c.wmode;if(null!==c.wmode&&(s.match(/msie 8/i)||!C&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i))Ua.push(sa.spcWmode),c.wmode=null;h={name:b,id:b,src:e,quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:cb+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",
+wmode:c.wmode,hasPriority:"true"};c.debugFlash&&(h.FlashVars="debug\x3d1");c.wmode||delete h.wmode;if(C)a=n.createElement("div"),p=['\x3cobject id\x3d"'+b+'" data\x3d"'+e+'" type\x3d"'+h.type+'" title\x3d"'+h.title+'" classid\x3d"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase\x3d"'+cb+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version\x3d6,0,40,0"\x3e',d("movie",e),d("AllowScriptAccess",c.allowScriptAccess),d("quality",h.quality),c.wmode?d("wmode",c.wmode):"",d("bgcolor",
+c.bgColor),d("hasPriority","true"),c.debugFlash?d("FlashVars",h.FlashVars):"","\x3c/object\x3e"].join("");else for(m in a=n.createElement("embed"),h)h.hasOwnProperty(m)&&a.setAttribute(m,h[m]);wa();g=I();if(h=va())if(c.oMC=W(c.movieID)||n.createElement("div"),c.oMC.id)q=c.oMC.className,c.oMC.className=(q?q+" ":"movieContainer")+(g?" "+g:""),c.oMC.appendChild(a),C&&(m=c.oMC.appendChild(n.createElement("div")),m.className="sm2-object-box",m.innerHTML=p),L=!0;else{c.oMC.id=c.movieID;c.oMC.className=
+"movieContainer "+g;m=g=null;c.useFlashBlock||(c.useHighPerformance?g={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",overflow:"hidden"}:(g={position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"},l&&(g.left=Math.abs(parseInt(g.left,10))+"px")));gb&&(c.oMC.style.zIndex=1E4);if(!c.debugFlash)for(q in g)g.hasOwnProperty(q)&&(c.oMC.style[q]=g[q]);try{C||c.oMC.appendChild(a),h.appendChild(c.oMC),C&&(m=c.oMC.appendChild(n.createElement("div")),m.className="sm2-object-box",
+m.innerHTML=p),L=!0}catch(r){throw Error(P("domError")+" \n"+r.toString());}}return K=!0};Z=function(){if(c.html5Only)return $(),!1;if(l||!c.url)return!1;l=c.getMovie(c.id);l||(O?(C?c.oMC.innerHTML=ya:c.oMC.appendChild(O),O=null,K=!0):$(c.id,c.url),l=c.getMovie(c.id));"function"===typeof c.oninitmovie&&setTimeout(c.oninitmovie,1);return!0};F=function(){setTimeout(Na,1E3)};qa=function(){g.setTimeout(function(){c.setup({preferFlash:!1}).reboot();c.didFlashBlock=!0;c.beginDelayedInit()},1)};Na=function(){var b,
+e=!1;if(!c.url||Q)return!1;Q=!0;t.remove(g,"load",F);if(v&&ja&&!Ga)return!1;p||(b=c.getMoviePercent(),0<b&&100>b&&(e=!0));setTimeout(function(){b=c.getMoviePercent();if(e)return Q=!1,g.setTimeout(F,1),!1;!p&&ab&&(null===b?c.useFlashBlock||0===c.flashLoadTimeout?c.useFlashBlock&&za():!c.useFlashBlock&&S?qa():D({type:"ontimeout",ignoreInit:!0,error:{type:"INIT_FLASHBLOCK"}}):0!==c.flashLoadTimeout&&(!c.useFlashBlock&&S?qa():xa(!0)))},c.flashLoadTimeout)};Y=function(){if(Ga||!ja)return t.remove(g,"focus",
+Y),!0;Ga=ab=!0;Q=!1;F();t.remove(g,"focus",Y);return!0};M=function(b){if(p)return!1;if(c.html5Only)return p=!0,E(),!0;var e=!0,d;if(!c.useFlashBlock||!c.flashLoadTimeout||c.getMoviePercent())p=!0;d={type:!v&&u?"NO_FLASH":"INIT_TIMEOUT"};if(y||b)c.useFlashBlock&&c.oMC&&(c.oMC.className=I()+" "+(null===c.getMoviePercent()?"swf_timedout":"swf_error")),D({type:"ontimeout",error:d,ignoreInit:!0}),H(d),e=!1;y||(c.waitForWindowLoad&&!na?t.add(g,"load",E):E());return e};Ma=function(){var b,e=c.setupOptions;
+for(b in e)e.hasOwnProperty(b)&&(c[b]===k?c[b]=e[b]:c[b]!==e[b]&&(c.setupOptions[b]=c[b]))};ma=function(){if(p)return!1;if(c.html5Only)return p||(t.remove(g,"load",c.beginDelayedInit),c.enabled=!0,M()),!0;Z();try{l._externalInterfaceTest(!1),Oa(!0,c.flashPollingInterval||(c.useHighPerformance?10:50)),c.debugMode||l._disableDebug(),c.enabled=!0,c.html5Only||t.add(g,"unload",la)}catch(b){return H({type:"JS_TO_FLASH_EXCEPTION",fatal:!0}),xa(!0),M(),!1}M();t.remove(g,"load",c.beginDelayedInit);return!0};
+G=function(){if(N)return!1;N=!0;Ma();wa();!v&&c.hasHTML5&&c.setup({useHTML5Audio:!0,preferFlash:!1});Wa();!v&&u&&(Ua.push(sa.needFlash),c.setup({flashLoadTimeout:1}));n.removeEventListener&&n.removeEventListener("DOMContentLoaded",G,!1);Z();return!0};Ba=function(){"complete"===n.readyState&&(G(),n.detachEvent("onreadystatechange",Ba));return!0};ua=function(){na=!0;t.remove(g,"load",ua)};ta=function(){if(Fa&&(c.setupOptions.useHTML5Audio=!0,c.setupOptions.preferFlash=!1,ha||Za&&!s.match(/android\s2\.3/i)))ha&&
+(c.ignoreFlash=!0),A=!0};ta();Da();t.add(g,"focus",Y);t.add(g,"load",F);t.add(g,"load",ua);n.addEventListener?n.addEventListener("DOMContentLoaded",G,!1):n.attachEvent?n.attachEvent("onreadystatechange",Ba):H({type:"NO_DOM2_EVENTS",fatal:!0})}var ka=null;if(void 0===g.SM2_DEFER||!SM2_DEFER)ka=new U;g.SoundManager=U;g.soundManager=ka})(window);
\ No newline at end of file
diff --git a/data/soundmanager2_debug.swf b/data/soundmanager2_debug.swf
deleted file mode 100644
index 4e30adb..0000000
Binary files a/data/soundmanager2_debug.swf and /dev/null differ
|
bjornstar/TumTaster
|
fbc29ae3ce1b8fbcb82f959049177961234b4f42
|
we got soundcloud too.
|
diff --git a/data/background.js b/data/background.js
index 9edf376..8342a8f 100644
--- a/data/background.js
+++ b/data/background.js
@@ -1,70 +1,80 @@
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
-chrome.extension.onRequest.addListener(
- function(message, sender, sendResponse) {
- if (message == 'getSettings') {
- sendResponse({settings: localStorage["settings"]});
- } else {
- addTrack(message);
- sendResponse({});
- }
-});
+function messageHandler(port, message) {
+ if (message === 'getSettings') {
+ return port.postMessage({ settings: settings});
+ }
+
+ if (message.hasOwnProperty('track')) {
+ return addTrack(message.track);
+ }
+}
+
+function connectHandler(port) {
+ port.onMessage.addListener(function onMessageHandler(message) {
+ messageHandler(port, message);
+ });
+
+ port.postMessage({ settings: settings });
+}
+
+chrome.runtime.onConnect.addListener(connectHandler);
function addTrack(newTrack) {
var id = newTrack.postId;
var url = newTrack.streamUrl + '?play_key=' + newTrack.postKey;
var mySoundObject = soundManager.createSound({
id: id,
url: url,
onloadfailed: function(){playnextsong(newTrack.postId)},
onfinish: function(){playnextsong(newTrack.postId)}
});
}
function getJukebox() {
var jukebox = document.getElementsByTagName('audio');
return jukebox;
}
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
document.addEventListener("DOMContentLoaded", function () {
soundManager.setup({"preferFlash": false});
});
\ No newline at end of file
diff --git a/data/script.js b/data/script.js
index cdcdc6d..17eaa93 100644
--- a/data/script.js
+++ b/data/script.js
@@ -1,223 +1,233 @@
// TumTaster v0.5.0
// - By Bjorn Stromberg (@bjornstar)
-var defaultSettings = {
- shuffle: false,
- repeat: true,
- mp3player: 'flash',
- listBlack: [
- 'beatles'
- ],
- listWhite: [
- 'bjorn',
- 'beck'
- ],
- listSites: [
- 'http://*.tumblr.com/*',
- 'http://bjornstar.com/*'
- ],
- version: '0.5.0'
-}; //initialize default values.
+var settings, started;
+
+function messageHandler(message) {
+ if (message.hasOwnProperty('settings')) {
+ settings = message.settings;
+ startTasting();
+ }
+
+ if (message.hasOwnProperty('track')) {
+ console.log(message.track);
+ }
+}
+
+var port = chrome.runtime.connect();
+port.onMessage.addListener(messageHandler);
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
-var settings;
-
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
var tracks = {};
-function makeAudioLink(postId, streamUrl, postKey, artist, track) {
+function makeTumblrLink(dataset) {
+ var postId = dataset.postId;
+
tracks[postId] = {
postId: postId,
- streamUrl: streamUrl,
- postKey: postKey,
- artist: artist,
- track: track
+ streamUrl: dataset.streamUrl,
+ postKey: dataset.postKey,
+ artist: dataset.artist,
+ track: dataset.track
};
- console.log('sending',tracks[postId],'to jukebox.');
- chrome.extension.sendRequest(tracks[postId]);
+ port.postMessage({ track: tracks[postId] });
}
-function extractAudioData(cnt) {
- console.log('extracting from',cnt)
- var postId = cnt.getAttribute('data-post-id');
- if (!postId || posts[postId]) {
+function makeSoundCloudLink(dataset, url) {
+ var qs = url.split('?')[1];
+ var chunks = qs.split('&');
+
+ var url;
+ for (var i = 0; i < chunks.length; i += 1) {
+ if (chunks[i].indexOf('url=') === 0) {
+ url = decodeURIComponent(chunks[i].substring(4));
+ break;
+ }
+ }
+
+ console.log(url + '/download?client_id=0b9cb426e9ffaf2af34e68ae54272549');
+}
+
+function extractAudioData(post) {
+ var postId = post.dataset.postId;
+ if (!postId || tracks[postId]) {
console.log('no post, or we already have it.')
return;
}
- var streamUrl = cnt.getAttribute('data-stream-url');
- if (!streamUrl) {
- console.log('no streamurl')
+ if (!post.dataset.streamUrl) {
+ var soundcloud = post.querySelector('.soundcloud_audio_player');
+
+ if (soundcloud) {
+ return makeSoundCloudLink(post.dataset, soundcloud.src);
+ }
+
+ console.log('no streamUrl')
return;
}
- var postKey = cnt.getAttribute('data-post-key');
- if (!postKey) {
+ if (!post.dataset.dataPostKey) {
console.log('no postkey')
return;
}
- var artist = cnt.getAttribute('data-artist');
- var track = cnt.getAttribute('data-track');
-
- makeAudioLink(postId, streamUrl, postKey, artist, track);
+ makeTumblrLink(post.dataset);
}
function handleNodeInserted(event) {
snarfAudioPlayers(event.target);
}
function snarfAudioPlayers(t) {
- var audioPlayers = t.querySelectorAll('.audio_player_container');
- console.log('found', audioPlayers.length, 'audio players.');
- for (var i = 0; i < audioPlayers.length; i += 1) {
- audioPlayer = audioPlayers[i];
- extractAudioData(audioPlayer);
+ var audioPosts = t.querySelectorAll('.post.is_audio');
+
+ for (var i = 0; i < audioPosts.length; i += 1) {
+ var audioPost = audioPosts[i];
+ extractAudioData(audioPost);
}
}
function addTumtasterStyle() {
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
var cssRules = [];
cssRules.push('a.tumtaster: {ã' + tumtaster_style + ' }');
- addGlobalStyle('tumtaster', cssRules);
+ addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
cssRules[0] = "@keyframes nodeInserted {";
cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[0] += "}";
cssRules[1] = "@-moz-keyframes nodeInserted {";
cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[1] += "}";
cssRules[2] = "@-webkit-keyframes nodeInserted {";
cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[2] += "}";
cssRules[3] = "@-ms-keyframes nodeInserted {";
cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[3] += "}";
cssRules[4] = "@-o-keyframes nodeInserted {";
cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[4] += "}";
cssRules[5] = "ol#posts li {";
cssRules[5] += " animation-duration: 1ms;";
cssRules[5] += " -o-animation-duration: 1ms;";
cssRules[5] += " -ms-animation-duration: 1ms;";
cssRules[5] += " -moz-animation-duration: 1ms;";
cssRules[5] += " -webkit-animation-duration: 1ms;";
cssRules[5] += " animation-name: nodeInserted;";
cssRules[5] += " -o-animation-name: nodeInserted;";
cssRules[5] += " -ms-animation-name: nodeInserted;";
cssRules[5] += " -moz-animation-name: nodeInserted;";
cssRules[5] += " -webkit-animation-name: nodeInserted;";
cssRules[5] += "}";
addGlobalStyle("wires", cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
-function loadSettings() {
- chrome.extension.sendRequest('getSettings', function(response) {
- savedSettings = response.settings;
+// 2013-12-29: Today's soundcloud audio url
+// - https://api.soundcloud.com/tracks/89350110/download?client_id=0b9cb426e9ffaf2af34e68ae54272549
- try {
- settings = JSON.parse(savedSettings);
- } catch (e) {
- settings = defaultSettings;
- }
+function startTasting() {
+ if (document.readyState === 'loading' || !settings || started) {
+ return;
+ }
- if (!checkurl(location.href, settings['listSites'])) {
- console.log('not checking', location.href)
- return;
- }
+ started = true;
- addTumtasterStyle();
- wireupnodes();
+ if (!checkurl(location.href, settings['listSites'])) {
+ console.log('not checking', location.href)
+ return;
+ }
- snarfAudioPlayers(document);
- });
-}
+ console.log('Now tasting', location.href);
-if (document.readyState === 'complete') {
- loadSettings();
-} else {
- console.log(document.readyState, 'waiting for loaded.');
- document.addEventListener("DOMContentLoaded", loadSettings);
+ addTumtasterStyle();
+ wireupnodes();
+
+ snarfAudioPlayers(document);
}
+
+document.addEventListener("DOMContentLoaded", startTasting);
+
+startTasting();
\ No newline at end of file
|
bjornstar/TumTaster
|
22718f96370c39098bece55685524f76623b7c6d
|
remove more flash/html5 stuff, fix width
|
diff --git a/data/background.js b/data/background.js
index 29f7170..9edf376 100644
--- a/data/background.js
+++ b/data/background.js
@@ -1,77 +1,70 @@
-var nowplaying = null;
-
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
chrome.extension.onRequest.addListener(
function(message, sender, sendResponse) {
if (message == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
addTrack(message);
sendResponse({});
}
});
function addTrack(newTrack) {
var id = newTrack.postId;
var url = newTrack.streamUrl + '?play_key=' + newTrack.postKey;
var mySoundObject = soundManager.createSound({
id: id,
url: url,
onloadfailed: function(){playnextsong(newTrack.postId)},
onfinish: function(){playnextsong(newTrack.postId)}
});
}
function getJukebox() {
var jukebox = document.getElementsByTagName('audio');
return jukebox;
}
-function removeSong(rSong) {
- var remove_song = document.getElementById(rSong);
- remove_song.parentNode.removeChild(remove_song);
-}
-
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
-
+
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
document.addEventListener("DOMContentLoaded", function () {
soundManager.setup({"preferFlash": false});
});
\ No newline at end of file
diff --git a/data/popup.html b/data/popup.html
index e101d96..983ca5f 100644
--- a/data/popup.html
+++ b/data/popup.html
@@ -1,190 +1,195 @@
<html>
<head>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
+ min-width:400px;
}
h1{
color:black;
}
a{
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
- div#heading h1{
+ #heading {
+ width:100%;
+ height:64px;
+ }
+ #heading h1{
color: white;
float: left;
line-height:32px;
vertical-align:absmiddle;
margin-left:10px;
}
div#statistics{
position:absolute;
bottom:0%;
}
#controls{
text-align:center;
}
#statusbar{
position:relative;
height:12px;
background-color:#CDD568;
border:2px solid #eaf839;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
overflow:hidden;
margin-top:4px;
}
.remove{
position:absolute;
right:8px;
top:8px;
}
.position, .position2, .loading{
position:absolute;
left:0px;
bottom:0px;
height:12px;
}
.position{
background-color: #3B440F;
border-right:2px solid #3B440F;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
width:20px;
}
.position2{
background-color:#eaf839;
}
-
+
.loading {
background-color:#BBC552;
}
</style>
<script src="popup.js" type="text/javascript"></script>
</head>
<body>
-<div id="heading" style="width:100%;height:64px;"><img src="Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
+<div id="heading"><img src="Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
<div id="statistics"><span> </span></div>
<div id="nowplayingdiv"><span>Now Playing: </span><span id="nowplaying"> </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
<p id="controls">
<a id="stop" href="#">■</a>
<a id="pause" href="#">❙ ❙</a>
<a id="play" href="#">▶</a>
<a id="next" href="#">▶▶</a>
<a id="random" href="#">Random</a></p>
<ol id="playlist" class="playlist">
</ol>
</body>
</html>
\ No newline at end of file
diff --git a/data/popup.js b/data/popup.js
index 0969960..7e928af 100644
--- a/data/popup.js
+++ b/data/popup.js
@@ -1,177 +1,153 @@
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var div_loading, div_position, div_position2, nowplaying;
document.addEventListener("DOMContentLoaded", function () {
var stopLink = document.getElementById("stop");
var pauseLink = document.getElementById("pause");
var playLink = document.getElementById("play");
var nextLink = document.getElementById("next");
var randomLink = document.getElementById("random");
stopLink.addEventListener("click", function(e) {
sm.stopAll();
e.preventDefault();
e.stopPropagation();
}, false);
pauseLink.addEventListener("click", function(e) {
pause();
e.preventDefault();
e.stopPropagation();
}, false);
playLink.addEventListener("click", function(e) {
sm.resumeAll();
e.preventDefault();
e.stopPropagation();
}, false);
nextLink.addEventListener("click", function(e) {
playnextsong();
e.preventDefault();
e.stopPropagation();
}, false);
randomLink.addEventListener("click", function(e) {
playrandomsong();
e.preventDefault();
e.stopPropagation();
}, false);
div_loading = document.getElementById('loading');
div_position = document.getElementById('position');
div_position2 = document.getElementById('position2');
nowplaying = document.getElementById('nowplaying');
var playlist = document.getElementById("playlist");
var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
setInterval(updateStatus, 200);
var pl = sm.sounds;
for (x in pl) {
var liSong = document.createElement('li');
var aSong = document.createElement('a');
aSong.id = pl[x].sID;
aSong.addEventListener("click", function(e) {
play(null, e.target.id);
e.preventDefault();
e.stopPropagation();
}, false);
aSong.href = "#";
- aSong.innerHTML = pl[x].sID;
+ aSong.textContent = pl[x].sID;
var aRemove = document.createElement('a');
aRemove.className = "remove";
aRemove.href = "#";
aRemove.addEventListener("click", function(e) {
console.log(e.target.parentNode.previousSibling.id);
remove(e.target.parentNode.previousSibling.id);
e.preventDefault();
e.stopPropagation();
}, false);
var imgRemove = document.createElement('img');
imgRemove.src = PNGremove;
aRemove.appendChild(imgRemove);
liSong.appendChild(aSong);
liSong.appendChild(aRemove);
playlist.appendChild(liSong);
- //document.write('<li id="'+pl[x].sID+'">');
- //document.write('<a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a>');
- //document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
}
});
function remove(song_id) {
- switch (bg.settings["mp3player"]) {
- case "flash":
- sm.destroySound(song_id);
- var song_li = document.getElementById(song_id);
- song_li.parentNode.parentNode.removeChild(song_li.parentNode);
- break;
- case "html5":
- bg.removeSong(song_id);
- var song_li = document.getElementById(song_id);
- song_li.parentNode.parentNode.removeChild(song_li.parentNode);
- break;
- }
+ sm.destroySound(song_id);
+
+ var song_li = document.getElementById(song_id);
+ song_li.parentNode.parentNode.removeChild(song_li.parentNode);
}
function pause() {
- current_song = get_currentsong();
- current_song.pause();
+ track = getPlaying();
+ track.pause();
}
function play(song_url,post_url) {
- switch (bg.settings["mp3player"]) {
- case "flash":
- sm.stopAll();
- var mySoundObject = sm.getSoundById(post_url);
- mySoundObject.play();
- break;
- case "html5":
- bg.playSong(song_url,post_url);
- break;
- }
+ sm.stopAll();
+
+ var sound = sm.getSoundById(post_url);
+ sound.play();
}
-function get_currentsong() {
- var song_nowplaying = null;
- switch (bg.settings["mp3player"]){
- case "flash":
- for (sound in sm.sounds) {
- if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
- song_nowplaying = sm.sounds[sound];
- }
- }
- break;
- case "html5":
- var pl = bg.getJukebox();
- for (var x=0;x<pl.length;x++) {
- if (pl[x].currentTime<pl[x].duration && pl[x].currentTime>0 && !pl[x].paused) {
- song_nowplaying = pl[x];
- }
+function getPlaying() {
+ for (sound in sm.sounds) {
+ if (sm.sounds[sound].playState == 1) {
+ return sm.sounds[sound];
}
- break;
}
- return song_nowplaying;
}
function playnextsong() {
- var current_song = get_currentsong();
- var current_song_sID;
+ var track = getPlaying();
- if (current_song) {
- current_song.stop();
- current_song_sID = current_song.sID;
+ var track_sID;
+
+ if (track) {
+ track.stop();
+ track_sID = track.sID;
}
- bg.playnextsong(current_song_sID);
+ bg.playnextsong(track_sID);
}
function playrandomsong() {
- var current_song = get_currentsong();
+ var current_song = getPlaying();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
}
function updateStatus() {
- var current_song = get_currentsong();
+ var track = getPlaying();
- if (current_song) {
- if (current_song.bytesTotal) {
- div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
- }
- div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
- div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
+ if (track) {
+ var bytesLoaded = track.bytesLoaded;
+ var bytesTotal = track.bytesTotal;
+ var position = track.position;
+ var durationEstimate = track.durationEstimate;
+
+ if (bytesTotal) {
+ div_loading.style.width = (100 * bytesLoaded / bytesTotal) + '%';
+ }
+
+ div_position.style.left = (100 * position / durationEstimate) + '%';
+ div_position2.style.width = (100 * position / durationEstimate) + '%';
}
- if (current_song && nowplaying.innerHTML != current_song.id) {
- nowplaying.innerHTML = current_song.id;
+ if (track && nowplaying.textContent !== track.id) {
+ nowplaying.textContent = track.id;
}
}
\ No newline at end of file
|
bjornstar/TumTaster
|
5d7c51ce5e37311a28942dc4eb60a7475c927911
|
playback now continues onto the next song.
|
diff --git a/data/background.js b/data/background.js
index 77066cf..29f7170 100644
--- a/data/background.js
+++ b/data/background.js
@@ -1,143 +1,77 @@
var nowplaying = null;
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
chrome.extension.onRequest.addListener(
function(message, sender, sendResponse) {
if (message == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
addTrack(message);
sendResponse({});
}
});
function addTrack(newTrack) {
var id = newTrack.postId;
var url = newTrack.streamUrl + '?play_key=' + newTrack.postKey;
- switch (settings["mp3player"]) {
- case "flash":
- var mySoundObject = soundManager.createSound({
- id: id,
- url: url,
- onloadfailed: function(){playnextsong(newSong.postId)},
- onfinish: function(){playnextsong(newSong.postId)}
- });
- break;
- case "html5":
- var newAudio = document.createElement('audio');
- newAudio.setAttribute('src', url);
- newAudio.setAttribute('id', id);
- var jukebox = document.getElementById('Jukebox');
- jukebox.appendChild(newAudio);
- break;
- }
+ var mySoundObject = soundManager.createSound({
+ id: id,
+ url: url,
+ onloadfailed: function(){playnextsong(newTrack.postId)},
+ onfinish: function(){playnextsong(newTrack.postId)}
+ });
}
function getJukebox() {
var jukebox = document.getElementsByTagName('audio');
return jukebox;
}
function removeSong(rSong) {
var remove_song = document.getElementById(rSong);
remove_song.parentNode.removeChild(remove_song);
}
-function playSong(song_url,post_url) {
- switch (settings["mp3player"]) {
- case "flash":
-
- break;
- case "html5":
- play_song = document.getElementById(post_url);
- play_song.addEventListener('ended',play_song,false);
- play_song.play();
- pl = getJukebox();
- for(var x=0;x<pl.length;x++){
- if(pl[x].id!=post_url){
- pl[x].pause();
- }
- }
- break;
- }
-}
-
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
+ for (x in soundManager.sounds) {
+ if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = soundManager.sounds[x].sID;
+ }
+ bad_idea = soundManager.sounds[x].sID;
+ if (first_song == null) {
+ first_song = soundManager.sounds[x].sID;
+ }
+ }
- switch (settings["mp3player"]) {
- case "flash":
- for (x in soundManager.sounds) {
- if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
- next_song = soundManager.sounds[x].sID;
- }
- bad_idea = soundManager.sounds[x].sID;
- if (first_song == null) {
- first_song = soundManager.sounds[x].sID;
- }
- }
-
- if (settings["shuffle"]) {
- var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- next_song = soundManager.soundIDs[s];
- }
-
- if (settings["repeat"] && bad_idea == previous_song) {
- next_song = first_song;
- }
+ if (settings["shuffle"]) {
+ var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ next_song = soundManager.soundIDs[s];
+ }
+
+ if (settings["repeat"] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
- if (next_song != null) {
- var soundNext = soundManager.getSoundById(next_song);
- soundNext.play();
- }
- break;
- case "html5":
- var playlist = document.getElementsByTagName('audio');
- for (x in playlist) {
- if (playlist[x].src != previous_song && bad_idea == previous_song && next_song == null) {
- next_song = playlist[x];
- }
- bad_idea = playlist[x].song_url;
- if (first_song == null) {
- first_song = playlist[0].song_url;
- }
- }
-
- if (settings["shuffle"]) {
- var s = Math.floor(Math.random()*playlist.length+1);
- next_song = playlist[s];
- }
-
- if (settings["repeat"] && bad_idea == previous_song) {
- next_song = first_song;
- }
-
- if (next_song != null) {
- playlist[x].play();
- }
- break;
+ if (next_song != null) {
+ var soundNext = soundManager.getSoundById(next_song);
+ soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
document.addEventListener("DOMContentLoaded", function () {
soundManager.setup({"preferFlash": false});
-/* if (settings["mp3player"]=="flash") {
- var fileref=document.createElement('script');
- fileref.setAttribute("type","text/javascript");
- fileref.setAttribute("src", "soundmanager2.js");
- document.getElementsByTagName("head")[0].appendChild(fileref);
- } */
});
\ No newline at end of file
diff --git a/data/popup.js b/data/popup.js
index d3e4343..0969960 100644
--- a/data/popup.js
+++ b/data/popup.js
@@ -1,198 +1,177 @@
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var div_loading, div_position, div_position2, nowplaying;
document.addEventListener("DOMContentLoaded", function () {
var stopLink = document.getElementById("stop");
var pauseLink = document.getElementById("pause");
var playLink = document.getElementById("play");
var nextLink = document.getElementById("next");
var randomLink = document.getElementById("random");
stopLink.addEventListener("click", function(e) {
sm.stopAll();
e.preventDefault();
e.stopPropagation();
}, false);
pauseLink.addEventListener("click", function(e) {
pause();
e.preventDefault();
e.stopPropagation();
}, false);
playLink.addEventListener("click", function(e) {
sm.resumeAll();
e.preventDefault();
e.stopPropagation();
}, false);
nextLink.addEventListener("click", function(e) {
playnextsong();
e.preventDefault();
e.stopPropagation();
}, false);
randomLink.addEventListener("click", function(e) {
playrandomsong();
e.preventDefault();
e.stopPropagation();
}, false);
div_loading = document.getElementById('loading');
div_position = document.getElementById('position');
div_position2 = document.getElementById('position2');
nowplaying = document.getElementById('nowplaying');
var playlist = document.getElementById("playlist");
var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
setInterval(updateStatus, 200);
-
- switch (bg.settings["mp3player"]) {
- case "flash":
- var pl = sm.sounds;
- for (x in pl) {
- var liSong = document.createElement('li');
- var aSong = document.createElement('a');
- aSong.id = pl[x].sID;
- aSong.addEventListener("click", function(e) {
- play(null, e.target.id);
- e.preventDefault();
- e.stopPropagation();
- }, false);
- aSong.href = "#";
- aSong.innerHTML = pl[x].sID;
- var aRemove = document.createElement('a');
- aRemove.className = "remove";
- aRemove.href = "#";
- aRemove.addEventListener("click", function(e) {
- console.log(e.target.parentNode.previousSibling.id);
- remove(e.target.parentNode.previousSibling.id);
- e.preventDefault();
- e.stopPropagation();
- }, false);
- var imgRemove = document.createElement('img');
- imgRemove.src = PNGremove;
- aRemove.appendChild(imgRemove);
- liSong.appendChild(aSong);
- liSong.appendChild(aRemove);
- playlist.appendChild(liSong);
- //document.write('<li id="'+pl[x].sID+'">');
- //document.write('<a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a>');
- //document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
- }
- break;
- case "html5":
- var pl = bg.getJukebox();
- for (x in pl) {
- if (pl[x].id!=undefined) {
- //document.write('<li id="'+pl[x].id+'">');
- //document.write('<a href="javascript:void(play(\''+pl[x].src+'\',\''+pl[x].id+'\'))">'+pl[x].id+'</a>');
- //document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].id+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
- }
- }
- break;
+ var pl = sm.sounds;
+ for (x in pl) {
+ var liSong = document.createElement('li');
+ var aSong = document.createElement('a');
+ aSong.id = pl[x].sID;
+ aSong.addEventListener("click", function(e) {
+ play(null, e.target.id);
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+ aSong.href = "#";
+ aSong.innerHTML = pl[x].sID;
+ var aRemove = document.createElement('a');
+ aRemove.className = "remove";
+ aRemove.href = "#";
+ aRemove.addEventListener("click", function(e) {
+ console.log(e.target.parentNode.previousSibling.id);
+ remove(e.target.parentNode.previousSibling.id);
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+ var imgRemove = document.createElement('img');
+ imgRemove.src = PNGremove;
+ aRemove.appendChild(imgRemove);
+ liSong.appendChild(aSong);
+ liSong.appendChild(aRemove);
+ playlist.appendChild(liSong);
+ //document.write('<li id="'+pl[x].sID+'">');
+ //document.write('<a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a>');
+ //document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
}
});
function remove(song_id) {
switch (bg.settings["mp3player"]) {
case "flash":
sm.destroySound(song_id);
var song_li = document.getElementById(song_id);
song_li.parentNode.parentNode.removeChild(song_li.parentNode);
break;
case "html5":
bg.removeSong(song_id);
var song_li = document.getElementById(song_id);
song_li.parentNode.parentNode.removeChild(song_li.parentNode);
break;
}
}
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
switch (bg.settings["mp3player"]) {
case "flash":
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
break;
case "html5":
bg.playSong(song_url,post_url);
break;
}
}
function get_currentsong() {
var song_nowplaying = null;
switch (bg.settings["mp3player"]){
case "flash":
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
break;
case "html5":
var pl = bg.getJukebox();
for (var x=0;x<pl.length;x++) {
if (pl[x].currentTime<pl[x].duration && pl[x].currentTime>0 && !pl[x].paused) {
song_nowplaying = pl[x];
}
}
break;
}
return song_nowplaying;
}
function playnextsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playnextsong(current_song_sID);
}
function playrandomsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
}
function updateStatus() {
var current_song = get_currentsong();
- if (current_song != undefined) {
- switch(bg.settings["mp3player"]) {
- case "flash":
- if (current_song.bytesTotal > 0) {
- div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
- }
- div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
- div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
- break;
- case "html5":
- div_position.style.left = (100 * current_song.currentTime / current_song.duration) + '%';
- div_position2.style.width = (100 * current_song.currentTime / current_song.duration) + '%';
- break;
- }
+
+ if (current_song) {
+ if (current_song.bytesTotal) {
+ div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
+ }
+ div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
+ div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
}
+
if (current_song && nowplaying.innerHTML != current_song.id) {
nowplaying.innerHTML = current_song.id;
}
}
\ No newline at end of file
|
bjornstar/TumTaster
|
f6bad1c100955d7dbea53720ec56ed8835a8b29b
|
Detection works on tumblr hosted audio.
|
diff --git a/data/background.js b/data/background.js
index 9c0cfff..77066cf 100644
--- a/data/background.js
+++ b/data/background.js
@@ -1,141 +1,143 @@
var nowplaying = null;
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
chrome.extension.onRequest.addListener(
function(message, sender, sendResponse) {
if (message == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
- addSong(message);
+ addTrack(message);
sendResponse({});
}
});
-function addSong(newSong) {
+function addTrack(newTrack) {
+ var id = newTrack.postId;
+ var url = newTrack.streamUrl + '?play_key=' + newTrack.postKey;
switch (settings["mp3player"]) {
case "flash":
var mySoundObject = soundManager.createSound({
- id: newSong.post_url,
- url: newSong.song_url,
- onloadfailed: function(){playnextsong(newSong.post_url)},
- onfinish: function(){playnextsong(newSong.post_url)}
+ id: id,
+ url: url,
+ onloadfailed: function(){playnextsong(newSong.postId)},
+ onfinish: function(){playnextsong(newSong.postId)}
});
break;
case "html5":
var newAudio = document.createElement('audio');
- newAudio.setAttribute('src', newSong.song_url);
- newAudio.setAttribute('id', newSong.post_url);
+ newAudio.setAttribute('src', url);
+ newAudio.setAttribute('id', id);
var jukebox = document.getElementById('Jukebox');
jukebox.appendChild(newAudio);
break;
}
}
function getJukebox() {
var jukebox = document.getElementsByTagName('audio');
return jukebox;
}
function removeSong(rSong) {
var remove_song = document.getElementById(rSong);
remove_song.parentNode.removeChild(remove_song);
}
function playSong(song_url,post_url) {
switch (settings["mp3player"]) {
case "flash":
break;
case "html5":
play_song = document.getElementById(post_url);
play_song.addEventListener('ended',play_song,false);
play_song.play();
pl = getJukebox();
for(var x=0;x<pl.length;x++){
if(pl[x].id!=post_url){
pl[x].pause();
}
}
break;
}
}
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
switch (settings["mp3player"]) {
case "flash":
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
break;
case "html5":
var playlist = document.getElementsByTagName('audio');
for (x in playlist) {
if (playlist[x].src != previous_song && bad_idea == previous_song && next_song == null) {
next_song = playlist[x];
}
bad_idea = playlist[x].song_url;
if (first_song == null) {
first_song = playlist[0].song_url;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*playlist.length+1);
next_song = playlist[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
playlist[x].play();
}
break;
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
document.addEventListener("DOMContentLoaded", function () {
soundManager.setup({"preferFlash": false});
/* if (settings["mp3player"]=="flash") {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "soundmanager2.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
} */
});
\ No newline at end of file
diff --git a/data/script.js b/data/script.js
index e76c31e..cdcdc6d 100644
--- a/data/script.js
+++ b/data/script.js
@@ -1,204 +1,223 @@
// TumTaster v0.5.0
// - By Bjorn Stromberg (@bjornstar)
var defaultSettings = {
shuffle: false,
repeat: true,
mp3player: 'flash',
listBlack: [
'beatles'
],
listWhite: [
'bjorn',
'beck'
],
listSites: [
'http://*.tumblr.com/*',
'http://bjornstar.com/*'
],
version: '0.5.0'
}; //initialize default values.
function addGlobalStyle(styleID, newRules) {
var cStyle, elmStyle, elmHead, newRule;
cStyle = document.getElementById(styleID);
elmHead = document.getElementsByTagName('head')[0];
if (elmHead === undefined) {
return false;
}
if (cStyle === undefined || cStyle === null) {
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmStyle.id = styleID;
while (newRules.length > 0) {
newRule = newRules.pop();
if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
elmStyle.sheet.insertRule(newRule, 0);
} else {
elmStyle.appendChild(document.createTextNode(newRule));
}
}
elmHead.appendChild(elmStyle);
} else {
while (cStyle.sheet.cssRules.length > 0) {
cStyle.sheet.deleteRule(0);
}
while (newRules.length > 0) {
newRule = newRules.pop();
if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
cStyle.sheet.insertRule(newRule, 0);
} else {
cStyle.appendChild(document.createTextNode(newRule));
}
}
}
return true;
}
var settings;
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
-var posts = {};
+var tracks = {};
-function addLinks(postId, streamUrl, postKey, artist, track) {
- var postContent = document.getElementById('post_content_' + postId);
-
- var downloadLink = document.createElement('a');
- downloadLink.setAttribute('href', streamUrl.concat('?play_key=', postKey));
- downloadLink.textContent = 'Click to download';
- downloadLink.className = 'tumtaster';
-
- postContent.appendChild(downloadLink);
-
- posts[postId] = {
+function makeAudioLink(postId, streamUrl, postKey, artist, track) {
+ tracks[postId] = {
postId: postId,
streamUrl: streamUrl,
postKey: postKey,
artist: artist,
track: track
};
- chrome.extension.sendRequest(posts[postId]);
+ console.log('sending',tracks[postId],'to jukebox.');
+ chrome.extension.sendRequest(tracks[postId]);
}
-function handleNodeInserted(event) {
- var postId = event.target.getAttribute('data-post-id');
+function extractAudioData(cnt) {
+ console.log('extracting from',cnt)
+ var postId = cnt.getAttribute('data-post-id');
if (!postId || posts[postId]) {
+ console.log('no post, or we already have it.')
return;
}
- var streamUrl = event.target.getAttribute('data-stream-url');
+ var streamUrl = cnt.getAttribute('data-stream-url');
if (!streamUrl) {
+ console.log('no streamurl')
return;
}
- var postKey = event.target.getAttribute('data-post-key');
+ var postKey = cnt.getAttribute('data-post-key');
if (!postKey) {
+ console.log('no postkey')
return;
}
- var artist = event.target.getAttribute('data-artist');
- var track = event.target.getAttribute('data-track');
+ var artist = cnt.getAttribute('data-artist');
+ var track = cnt.getAttribute('data-track');
makeAudioLink(postId, streamUrl, postKey, artist, track);
}
+function handleNodeInserted(event) {
+ snarfAudioPlayers(event.target);
+}
+
+function snarfAudioPlayers(t) {
+ var audioPlayers = t.querySelectorAll('.audio_player_container');
+ console.log('found', audioPlayers.length, 'audio players.');
+ for (var i = 0; i < audioPlayers.length; i += 1) {
+ audioPlayer = audioPlayers[i];
+ extractAudioData(audioPlayer);
+ }
+}
+
function addTumtasterStyle() {
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
var cssRules = [];
cssRules.push('a.tumtaster: {ã' + tumtaster_style + ' }');
addGlobalStyle('tumtaster', cssRules);
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
cssRules[0] = "@keyframes nodeInserted {";
cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[0] += "}";
cssRules[1] = "@-moz-keyframes nodeInserted {";
cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[1] += "}";
cssRules[2] = "@-webkit-keyframes nodeInserted {";
cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[2] += "}";
cssRules[3] = "@-ms-keyframes nodeInserted {";
cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[3] += "}";
cssRules[4] = "@-o-keyframes nodeInserted {";
cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[4] += "}";
cssRules[5] = "ol#posts li {";
cssRules[5] += " animation-duration: 1ms;";
cssRules[5] += " -o-animation-duration: 1ms;";
cssRules[5] += " -ms-animation-duration: 1ms;";
cssRules[5] += " -moz-animation-duration: 1ms;";
cssRules[5] += " -webkit-animation-duration: 1ms;";
cssRules[5] += " animation-name: nodeInserted;";
cssRules[5] += " -o-animation-name: nodeInserted;";
cssRules[5] += " -ms-animation-name: nodeInserted;";
cssRules[5] += " -moz-animation-name: nodeInserted;";
cssRules[5] += " -webkit-animation-name: nodeInserted;";
cssRules[5] += "}";
addGlobalStyle("wires", cssRules);
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
// 2013-12-18: Today's tumblr audio url
// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
function loadSettings() {
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
try {
settings = JSON.parse(savedSettings);
} catch (e) {
settings = defaultSettings;
}
- if (checkurl(location.href, settings['listSites'])) {
- addTumtasterStyle();
- wireupnodes();
+ if (!checkurl(location.href, settings['listSites'])) {
+ console.log('not checking', location.href)
+ return;
}
+
+ addTumtasterStyle();
+ wireupnodes();
+
+ snarfAudioPlayers(document);
});
}
-loadSettings();
\ No newline at end of file
+if (document.readyState === 'complete') {
+ loadSettings();
+} else {
+ console.log(document.readyState, 'waiting for loaded.');
+ document.addEventListener("DOMContentLoaded", loadSettings);
+}
diff --git a/manifest.json b/manifest.json
index 754306c..b05705d 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,29 +1,31 @@
{
"name": "TumTaster",
"version": "0.5.0",
"description": "An extension that creates download links for the MP3s you see on Tumblr.",
"background": {
"page": "index.html"
},
"browser_action": {
"default_icon": "data/Icon-16.png",
"default_popup": "data/popup.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [ "data/script.js" ],
- "matches": [ "http://*/*", "https://*/*" ]
+ "matches": [ "http://*/*", "https://*/*" ],
+ "all_frames": true,
+ "run_at": "document_start"
} ],
"icons": {
"16": "data/Icon-16.png",
"32": "data/Icon-32.png",
"48": "data/Icon-48.png",
"64": "data/Icon-64.png",
"128": "data/Icon-128.png"
},
"manifest_version": 2,
"options_page": "data/options.html",
"permissions": [
"http://*/*"
]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
d49c3f85c4de3d683dd29173ab47fef80ced82f8
|
first pass at v0.5.0
|
diff --git a/config.xml b/config.xml
deleted file mode 100644
index 89d6469..0000000
--- a/config.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<widget xmlns="http://www.w3.org/ns/widgets"
- version="0.4.7">
- <name short="TumTaster">TumTaster for Opera</name>
- <description>An extension that creates download links for the MP3s you see on Tumblr.</description>
- <author href="http://bjornstar.com"
- email="[email protected]">Bjorn Stromberg (@bjornstar)</author>
- <icon src="Icon-64.png"/>
- <update-description href="http://tumtaster.bjornstar.com/tumtaster.xml"/>
-</widget>
\ No newline at end of file
diff --git a/Icon-128.png b/data/Icon-128.png
similarity index 100%
rename from Icon-128.png
rename to data/Icon-128.png
diff --git a/Icon-16.png b/data/Icon-16.png
similarity index 100%
rename from Icon-16.png
rename to data/Icon-16.png
diff --git a/Icon-32.png b/data/Icon-32.png
similarity index 100%
rename from Icon-32.png
rename to data/Icon-32.png
diff --git a/Icon-48.png b/data/Icon-48.png
similarity index 100%
rename from Icon-48.png
rename to data/Icon-48.png
diff --git a/Icon-64.png b/data/Icon-64.png
similarity index 100%
rename from Icon-64.png
rename to data/Icon-64.png
diff --git a/background.js b/data/background.js
similarity index 100%
rename from background.js
rename to data/background.js
diff --git a/defaults.js b/data/defaults.js
similarity index 91%
rename from defaults.js
rename to data/defaults.js
index 7d61f8d..8f475c6 100644
--- a/defaults.js
+++ b/data/defaults.js
@@ -1,17 +1,17 @@
var defaultSettings = { //initialize default values.
- 'version': '0.4.8',
+ 'version': '0.5.0',
'shuffle': false,
'repeat': true,
'mp3player': 'flash',
'listBlack': [
'beatles'
],
'listWhite': [
'bjorn',
'beck'
],
'listSites': [
'http://*.tumblr.com/*',
'http://bjornstar.com/*'
]
};
\ No newline at end of file
diff --git a/options.html b/data/options.html
similarity index 100%
rename from options.html
rename to data/options.html
diff --git a/options.js b/data/options.js
similarity index 100%
rename from options.js
rename to data/options.js
diff --git a/popup.html b/data/popup.html
similarity index 100%
rename from popup.html
rename to data/popup.html
diff --git a/popup.js b/data/popup.js
similarity index 100%
rename from popup.js
rename to data/popup.js
diff --git a/data/script.js b/data/script.js
new file mode 100644
index 0000000..e76c31e
--- /dev/null
+++ b/data/script.js
@@ -0,0 +1,204 @@
+// TumTaster v0.5.0
+// - By Bjorn Stromberg (@bjornstar)
+
+var defaultSettings = {
+ shuffle: false,
+ repeat: true,
+ mp3player: 'flash',
+ listBlack: [
+ 'beatles'
+ ],
+ listWhite: [
+ 'bjorn',
+ 'beck'
+ ],
+ listSites: [
+ 'http://*.tumblr.com/*',
+ 'http://bjornstar.com/*'
+ ],
+ version: '0.5.0'
+}; //initialize default values.
+
+function addGlobalStyle(styleID, newRules) {
+ var cStyle, elmStyle, elmHead, newRule;
+
+ cStyle = document.getElementById(styleID);
+ elmHead = document.getElementsByTagName('head')[0];
+
+ if (elmHead === undefined) {
+ return false;
+ }
+
+ if (cStyle === undefined || cStyle === null) {
+ elmStyle = document.createElement('style');
+ elmStyle.type = 'text/css';
+ elmStyle.id = styleID;
+ while (newRules.length > 0) {
+ newRule = newRules.pop();
+ if (elmStyle.sheet !== undefined && elmStyle.sheet !== null && elmStyle.sheet.cssRules[0] !== null) {
+ elmStyle.sheet.insertRule(newRule, 0);
+ } else {
+ elmStyle.appendChild(document.createTextNode(newRule));
+ }
+ }
+ elmHead.appendChild(elmStyle);
+ } else {
+ while (cStyle.sheet.cssRules.length > 0) {
+ cStyle.sheet.deleteRule(0);
+ }
+ while (newRules.length > 0) {
+ newRule = newRules.pop();
+ if (cStyle.sheet !== undefined && cStyle.sheet.cssRules[0] !== null) {
+ cStyle.sheet.insertRule(newRule, 0);
+ } else {
+ cStyle.appendChild(document.createTextNode(newRule));
+ }
+ }
+ }
+
+ return true;
+}
+
+var settings;
+
+function checkurl(url, filter) {
+ for (var f in filter) {
+ var filterRegex;
+ filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
+ var re = new RegExp(filterRegex);
+ if (url.match(re)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+var posts = {};
+
+function addLinks(postId, streamUrl, postKey, artist, track) {
+ var postContent = document.getElementById('post_content_' + postId);
+
+ var downloadLink = document.createElement('a');
+ downloadLink.setAttribute('href', streamUrl.concat('?play_key=', postKey));
+ downloadLink.textContent = 'Click to download';
+ downloadLink.className = 'tumtaster';
+
+ postContent.appendChild(downloadLink);
+
+ posts[postId] = {
+ postId: postId,
+ streamUrl: streamUrl,
+ postKey: postKey,
+ artist: artist,
+ track: track
+ };
+
+ chrome.extension.sendRequest(posts[postId]);
+}
+
+function handleNodeInserted(event) {
+ var postId = event.target.getAttribute('data-post-id');
+ if (!postId || posts[postId]) {
+ return;
+ }
+
+ var streamUrl = event.target.getAttribute('data-stream-url');
+ if (!streamUrl) {
+ return;
+ }
+
+ var postKey = event.target.getAttribute('data-post-key');
+ if (!postKey) {
+ return;
+ }
+
+ var artist = event.target.getAttribute('data-artist');
+ var track = event.target.getAttribute('data-track');
+
+ makeAudioLink(postId, streamUrl, postKey, artist, track);
+}
+
+
+function addTumtasterStyle() {
+ var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
+ var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
+ var cssRules = [];
+ cssRules.push('a.tumtaster: {ã' + tumtaster_style + ' }');
+
+ addGlobalStyle('tumtaster', cssRules);
+}
+
+function wireupnodes() {
+ var cssRules = [];
+
+ document.addEventListener('animationstart', handleNodeInserted, false);
+ document.addEventListener('MSAnimationStart', handleNodeInserted, false);
+ document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
+ document.addEventListener('OAnimationStart', handleNodeInserted, false);
+
+ cssRules[0] = "@keyframes nodeInserted {";
+ cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[0] += "}";
+
+ cssRules[1] = "@-moz-keyframes nodeInserted {";
+ cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[1] += "}";
+
+ cssRules[2] = "@-webkit-keyframes nodeInserted {";
+ cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[2] += "}";
+
+ cssRules[3] = "@-ms-keyframes nodeInserted {";
+ cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[3] += "}";
+
+ cssRules[4] = "@-o-keyframes nodeInserted {";
+ cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[4] += "}";
+
+ cssRules[5] = "ol#posts li {";
+ cssRules[5] += " animation-duration: 1ms;";
+ cssRules[5] += " -o-animation-duration: 1ms;";
+ cssRules[5] += " -ms-animation-duration: 1ms;";
+ cssRules[5] += " -moz-animation-duration: 1ms;";
+ cssRules[5] += " -webkit-animation-duration: 1ms;";
+ cssRules[5] += " animation-name: nodeInserted;";
+ cssRules[5] += " -o-animation-name: nodeInserted;";
+ cssRules[5] += " -ms-animation-name: nodeInserted;";
+ cssRules[5] += " -moz-animation-name: nodeInserted;";
+ cssRules[5] += " -webkit-animation-name: nodeInserted;";
+ cssRules[5] += "}";
+
+ addGlobalStyle("wires", cssRules);
+}
+
+// 2013-01-31: Today's tumblr audio url
+// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
+// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
+
+// 2013-12-18: Today's tumblr audio url
+// - http://www.tumblr.com/audio_file/no-mosexual/69952464733/tumblr_mxs96tnYi71r721wf?play_key=e6ba8f023e92bbb5aaf06052cd0c6551
+
+function loadSettings() {
+ chrome.extension.sendRequest('getSettings', function(response) {
+ savedSettings = response.settings;
+
+ try {
+ settings = JSON.parse(savedSettings);
+ } catch (e) {
+ settings = defaultSettings;
+ }
+
+ if (checkurl(location.href, settings['listSites'])) {
+ addTumtasterStyle();
+ wireupnodes();
+ }
+ });
+}
+
+loadSettings();
\ No newline at end of file
diff --git a/soundmanager2.js b/data/soundmanager2.js
similarity index 100%
rename from soundmanager2.js
rename to data/soundmanager2.js
diff --git a/soundmanager2_debug.swf b/data/soundmanager2_debug.swf
similarity index 100%
rename from soundmanager2_debug.swf
rename to data/soundmanager2_debug.swf
diff --git a/includes/injected.js b/includes/injected.js
deleted file mode 100644
index f8cf08d..0000000
--- a/includes/injected.js
+++ /dev/null
@@ -1,107 +0,0 @@
-var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
-var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:100%; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:16px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
-
-var posts = {};
-
-function addGlobalStyle(css) {
- var elmHead, elmStyle;
- elmHead = document.getElementsByTagName('head')[0];
- elmStyle = document.createElement('style');
- elmStyle.type = 'text/css';
- elmHead.appendChild(elmStyle);
- elmStyle.innerHTML = css;
-}
-
-function addLinks(config) {
- var postId = config.post_id;
- var postKey = config.post_key;
-
- var postContent = document.getElementById('post_content_' + postId);
-
- for (var i = 0; i < config.tracks.length; i += 1) {
- var track = config.tracks[i];
-
- var downloadLink = document.createElement('a');
- downloadLink.setAttribute('href', track.stream_url.concat('?play_key=', postKey));
- downloadLink.textContent = 'Click to download';
- downloadLink.className = 'tumtaster';
-
- postContent.appendChild(downloadLink);
- }
-}
-
-function makeAudioLinks() {
- var instances = Object.keys(window.audiojs.instances);
-
- for (var i = 0; i < instances.length; i += 1) {
- var instanceName = instances[i];
- var postId = window.audiojs.instances[instanceName].audioplayer.config.post_id;
- if (posts[postId]) {
- continue;
- }
- posts[postId] = true;
- addLinks(window.audiojs.instances[instanceName].audioplayer.config);
- }
-}
-
-function handleNodeInserted(event) {
- var postId = event.target.getAttribute('data-post-id');
- if (!postId || posts[postId]) {
- return;
- }
-
- makeAudioLinks();
-}
-
-function wireupnodes() {
- var cssRules = [];
-
- document.addEventListener('animationstart', handleNodeInserted, false);
- document.addEventListener('MSAnimationStart', handleNodeInserted, false);
- document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
- document.addEventListener('OAnimationStart', handleNodeInserted, false);
-
- cssRules[0] = "@keyframes nodeInserted {";
- cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[0] += "}";
-
- cssRules[1] = "@-moz-keyframes nodeInserted {";
- cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[1] += "}";
-
- cssRules[2] = "@-webkit-keyframes nodeInserted {";
- cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[2] += "}";
-
- cssRules[3] = "@-ms-keyframes nodeInserted {";
- cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[3] += "}";
-
- cssRules[4] = "@-o-keyframes nodeInserted {";
- cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[4] += "}";
-
- cssRules[5] = "ol#posts li {";
- cssRules[5] += " animation-duration: 1ms;";
- cssRules[5] += " -o-animation-duration: 1ms;";
- cssRules[5] += " -ms-animation-duration: 1ms;";
- cssRules[5] += " -moz-animation-duration: 1ms;";
- cssRules[5] += " -webkit-animation-duration: 1ms;";
- cssRules[5] += " animation-name: nodeInserted;";
- cssRules[5] += " -o-animation-name: nodeInserted;";
- cssRules[5] += " -ms-animation-name: nodeInserted;";
- cssRules[5] += " -moz-animation-name: nodeInserted;";
- cssRules[5] += " -webkit-animation-name: nodeInserted;";
- cssRules[5] += "}";
-
- addGlobalStyle("wires", cssRules);
-}
-
-addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
-wireupnodes();
-makeAudioLinks();
\ No newline at end of file
diff --git a/includes/script.js b/includes/script.js
deleted file mode 100644
index 103888f..0000000
--- a/includes/script.js
+++ /dev/null
@@ -1,294 +0,0 @@
-// Tumtaster
-// - By Bjorn Stromberg
-
-var defaultSettings = {
- shuffle: false,
- repeat: true,
- mp3player: 'flash',
- listBlack: [
- 'beatles'
- ],
- listWhite: [
- 'bjorn',
- 'beck'
- ],
- listSites: [
- 'http://*.tumblr.com/*',
- 'http://bjornstar.com/*'
- ],
- version: '0.4.8'
-}; //initialize default values.
-
-function addGlobalStyle(css) {
- var elmHead, elmStyle;
- elmHead = document.getElementsByTagName('head')[0];
- elmStyle = document.createElement('style');
- elmStyle.type = 'text/css';
- elmHead.appendChild(elmStyle);
- elmStyle.innerHTML = css;
-}
-
-var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
-var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
-
-var library = {};
-var settings;
-
-function loadSettings() {
- chrome.extension.sendRequest('getSettings', function(response) {
- savedSettings = response.settings;
- if (savedSettings == undefined) {
- settings = defaultSettings;
- } else {
- settings = JSON.parse(savedSettings);
- }
- if (window.location.href.indexOf('show/audio')>0) {
- fixaudiopagination();
- }
- if (checkurl(location.href, settings['listSites'])) {
- addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
- wireupnodes();
- waitForEmbeds();
- }
- });
-}
-
-function checkurl(url, filter) {
- for (var f in filter) {
- var filterRegex;
- filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
- var re = new RegExp(filterRegex);
- if (url.match(re)) {
- return true;
- }
- }
- return false;
-}
-
-// 2013-01-31: Today's tumblr audio url
-// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
-// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
-
-
-function tasty(embed) {
- var embedSrc = embed.getAttribute('src');
-
- var a = document.createElement('a');
- a.href = embedSrc;
-
- var encodedSongURI = a.search.match(/audio_file=([^&]*)/)[1];
-
- var songURL = decodeURIComponent(encodedSongURI).concat('?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
-
- var songColor = a.search.match(/color=([^&]*)/)[1];
- var songBGColor = '000000';
-
- if (embedSrc.match(/\/audio_player\.swf/)) {
- songBGColor = 'FFFFFF';
- songColor = '5A5A5A';
- }
-
- var post_id = songURL.match(/audio_file\/([^\/]*)\/(\d+)\//)[2];
- var post_url = 'http://www.tumblr.com/';
-
- if (library.hasOwnProperty(post_id)) {
- return;
- }
-
- library[post_id] = songURL;
-
- var dl_a = document.createElement('a');
- dl_a.setAttribute('href', songURL);
- dl_a.setAttribute('style', 'background-color: #'+songBGColor+'; color: #'+songColor+'; text-decoration: none;');
- dl_a.setAttribute('class', 'tumtaster');
- dl_a.innerHTML = 'Click to download ';
-
- var dl_span = document.createElement('span');
- var dl_br = document.createElement('br');
- dl_span.appendChild(dl_br);
- dl_span.appendChild(dl_a);
-
- embed.parentNode.appendChild(dl_span);
- guaranteesize(embed,54,0);
-
- // Find the post's URL.
- var anchors = document.getElementsByTagName('a');
- for (var a in anchors) {
- if (anchors[a].href) {
- if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
- post_url = anchors[a].href;
- }
- }
- }
-
-//Remove # anchors...
- if (post_url.indexOf('#')>=0) {
- post_url = post_url.substring(0,post_url.indexOf('#'));
- }
-
- if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
-
- //We check our white list to see if we should add it to the playlist.
- var whitelisted = false;
- var blacklisted = false;
-
- //Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
-
- if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
- var post = document.getElementById('post_'+post_id);
-
- for (itemWhite in settings['listWhite']) {
- if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
- whitelisted = true;
- break;
- }
- }
-
- // If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
- if (!whitelisted) {
- for (itemBlack in settings['listBlack']) {
- if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
- blacklisted = true;
- break;
- }
- }
- }
- }
- if (!blacklisted) {
- console.log("sending "+songURL);
- chrome.extension.sendRequest({song_url: songURL, post_id: post_id, post_url: post_url});
- }
- }
-}
-
-function guaranteesize(start_here,at_least_height,at_least_width) {
- while (start_here.parentNode !== null || start_here.parentNode !== start_here.parentNode) {
- if (start_here.parentNode === null || start_here.parentNode === undefined) {
- return;
- }
- if (start_here.parentNode.offsetHeight < at_least_height && start_here.parentNode.className !== "post_content" && start_here.parentNode.style.getPropertyValue('display') !== 'none') {
- start_here.parentNode.style.height = at_least_height + 'px';
- }
- if (start_here.parentNode.offsetWidth < at_least_width && start_here.parentNode.className !== "post_content" && start_here.parentNode.style.getPropertyValue('display') !== 'none') {
- start_here.parentNode.style.width = at_least_width + 'px';
- }
- start_here = start_here.parentNode;
- }
-}
-
-function fixaudiopagination() {
- var nextpagelink = document.getElementById('next_page_link');
- var prevpagelink = document.getElementById('previous_page_link');
- var currentpage = window.location.href;
-
- var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
-
- if (isNaN(pagenumber)) {
- nextpagelink.href = currentpage+'/2';
- } else {
- nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
- }
-
- if (prevpagelink) {
- prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
- }
-
- var dashboard_controls = document.getElementById('dashboard_controls');
-
- if (dashboard_controls) {
- dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
- dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
- dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
- }
-}
-
-function handleNodeInserted(event) {
- var newEmbeds = event.target.getElementsByTagName('EMBED');
-
- if (!newEmbeds.length) {
- return;
- }
-
- for (var i = 0, len = newEmbeds.length; i < len; i += 1) {
- var newEmbed = newEmbeds[i];
- if (hasSong(newEmbed)) {
- tasty(newEmbed);
- }
- }
-}
-
-function wireupnodes() {
- var cssRules = [];
-
- document.addEventListener('animationstart', handleNodeInserted, false);
- document.addEventListener('MSAnimationStart', handleNodeInserted, false);
- document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
- document.addEventListener('OAnimationStart', handleNodeInserted, false);
-
- cssRules[0] = "@keyframes nodeInserted {";
- cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[0] += "}";
-
- cssRules[1] = "@-moz-keyframes nodeInserted {";
- cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[1] += "}";
-
- cssRules[2] = "@-webkit-keyframes nodeInserted {";
- cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[2] += "}";
-
- cssRules[3] = "@-ms-keyframes nodeInserted {";
- cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[3] += "}";
-
- cssRules[4] = "@-o-keyframes nodeInserted {";
- cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
- cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
- cssRules[4] += "}";
-
- cssRules[5] = "ol#posts li {";
- cssRules[5] += " animation-duration: 1ms;";
- cssRules[5] += " -o-animation-duration: 1ms;";
- cssRules[5] += " -ms-animation-duration: 1ms;";
- cssRules[5] += " -moz-animation-duration: 1ms;";
- cssRules[5] += " -webkit-animation-duration: 1ms;";
- cssRules[5] += " animation-name: nodeInserted;";
- cssRules[5] += " -o-animation-name: nodeInserted;";
- cssRules[5] += " -ms-animation-name: nodeInserted;";
- cssRules[5] += " -moz-animation-name: nodeInserted;";
- cssRules[5] += " -webkit-animation-name: nodeInserted;";
- cssRules[5] += "}";
-
- addGlobalStyle("wires", cssRules);
-}
-
-var embeds;
-
-function hasSong(embed) {
- return embed.getAttribute('src').indexOf('/swf/audio_player') >= 0;
-}
-
-function waitForEmbeds() {
- var embeds = document.getElementsByTagName('EMBED');
- if (!embeds.length) {
- setTimeout(waitForEmbeds, 10);
- } else {
- for (var i = 0, len = embeds.length; i < len; i += 1) {
- var embed = embeds[i];
- if (hasSong(embed)) {
- tasty(embed);
- }
- }
- }
-}
-
-loadSettings();
-
-var s = document.createElement('script');
-s.src = chrome.extension.getURL("includes/injected.js");
-(document.head||document.documentElement).appendChild(s);
-s.parentNode.removeChild(s);
\ No newline at end of file
diff --git a/index.html b/index.html
index de8b017..f9cb79d 100644
--- a/index.html
+++ b/index.html
@@ -1,14 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
-<script src="defaults.js" type="text/javascript"></script>
-<script src="soundmanager2.js" type="text/javascript"></script>
-<script src="background.js" type="text/javascript"></script>
+<script src="data/defaults.js" type="text/javascript"></script>
+<script src="data/soundmanager2.js" type="text/javascript"></script>
+<script src="data/background.js" type="text/javascript"></script>
</head>
<body>
<h1>TumTaster</h1>
<div id="Jukebox">
</div>
</body>
</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index c723ac4..754306c 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,30 +1,29 @@
{
"name": "TumTaster",
- "version": "0.4.9",
+ "version": "0.5.0",
"description": "An extension that creates download links for the MP3s you see on Tumblr.",
"background": {
"page": "index.html"
},
"browser_action": {
- "default_icon": "Icon-16.png",
- "default_popup": "popup.html",
+ "default_icon": "data/Icon-16.png",
+ "default_popup": "data/popup.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
- "js": [ "/includes/script.js" ],
+ "js": [ "data/script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"icons": {
- "16": "Icon-16.png",
- "32": "Icon-32.png",
- "48": "Icon-48.png",
- "64": "Icon-64.png",
- "128": "Icon-128.png"
+ "16": "data/Icon-16.png",
+ "32": "data/Icon-32.png",
+ "48": "data/Icon-48.png",
+ "64": "data/Icon-64.png",
+ "128": "data/Icon-128.png"
},
"manifest_version": 2,
- "options_page": "options.html",
+ "options_page": "data/options.html",
"permissions": [
"http://*/*"
- ],
- "web_accessible_resources": [ "includes/injected.js" ]
+ ]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
6dcfec63ba54bfa8c1d6d3aba70a3bc70978dbca
|
v0.4.9: inject script so you can snarf tumblr's data.
|
diff --git a/includes/injected.js b/includes/injected.js
new file mode 100644
index 0000000..f8cf08d
--- /dev/null
+++ b/includes/injected.js
@@ -0,0 +1,107 @@
+var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
+var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:100%; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:16px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
+
+var posts = {};
+
+function addGlobalStyle(css) {
+ var elmHead, elmStyle;
+ elmHead = document.getElementsByTagName('head')[0];
+ elmStyle = document.createElement('style');
+ elmStyle.type = 'text/css';
+ elmHead.appendChild(elmStyle);
+ elmStyle.innerHTML = css;
+}
+
+function addLinks(config) {
+ var postId = config.post_id;
+ var postKey = config.post_key;
+
+ var postContent = document.getElementById('post_content_' + postId);
+
+ for (var i = 0; i < config.tracks.length; i += 1) {
+ var track = config.tracks[i];
+
+ var downloadLink = document.createElement('a');
+ downloadLink.setAttribute('href', track.stream_url.concat('?play_key=', postKey));
+ downloadLink.textContent = 'Click to download';
+ downloadLink.className = 'tumtaster';
+
+ postContent.appendChild(downloadLink);
+ }
+}
+
+function makeAudioLinks() {
+ var instances = Object.keys(window.audiojs.instances);
+
+ for (var i = 0; i < instances.length; i += 1) {
+ var instanceName = instances[i];
+ var postId = window.audiojs.instances[instanceName].audioplayer.config.post_id;
+ if (posts[postId]) {
+ continue;
+ }
+ posts[postId] = true;
+ addLinks(window.audiojs.instances[instanceName].audioplayer.config);
+ }
+}
+
+function handleNodeInserted(event) {
+ var postId = event.target.getAttribute('data-post-id');
+ if (!postId || posts[postId]) {
+ return;
+ }
+
+ makeAudioLinks();
+}
+
+function wireupnodes() {
+ var cssRules = [];
+
+ document.addEventListener('animationstart', handleNodeInserted, false);
+ document.addEventListener('MSAnimationStart', handleNodeInserted, false);
+ document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
+ document.addEventListener('OAnimationStart', handleNodeInserted, false);
+
+ cssRules[0] = "@keyframes nodeInserted {";
+ cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[0] += "}";
+
+ cssRules[1] = "@-moz-keyframes nodeInserted {";
+ cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[1] += "}";
+
+ cssRules[2] = "@-webkit-keyframes nodeInserted {";
+ cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[2] += "}";
+
+ cssRules[3] = "@-ms-keyframes nodeInserted {";
+ cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[3] += "}";
+
+ cssRules[4] = "@-o-keyframes nodeInserted {";
+ cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[4] += "}";
+
+ cssRules[5] = "ol#posts li {";
+ cssRules[5] += " animation-duration: 1ms;";
+ cssRules[5] += " -o-animation-duration: 1ms;";
+ cssRules[5] += " -ms-animation-duration: 1ms;";
+ cssRules[5] += " -moz-animation-duration: 1ms;";
+ cssRules[5] += " -webkit-animation-duration: 1ms;";
+ cssRules[5] += " animation-name: nodeInserted;";
+ cssRules[5] += " -o-animation-name: nodeInserted;";
+ cssRules[5] += " -ms-animation-name: nodeInserted;";
+ cssRules[5] += " -moz-animation-name: nodeInserted;";
+ cssRules[5] += " -webkit-animation-name: nodeInserted;";
+ cssRules[5] += "}";
+
+ addGlobalStyle("wires", cssRules);
+}
+
+addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
+wireupnodes();
+makeAudioLinks();
\ No newline at end of file
diff --git a/includes/script.js b/includes/script.js
index 9babc1a..103888f 100644
--- a/includes/script.js
+++ b/includes/script.js
@@ -1,289 +1,294 @@
// Tumtaster
// - By Bjorn Stromberg
var defaultSettings = {
shuffle: false,
repeat: true,
mp3player: 'flash',
listBlack: [
'beatles'
],
listWhite: [
'bjorn',
'beck'
],
listSites: [
'http://*.tumblr.com/*',
'http://bjornstar.com/*'
],
version: '0.4.8'
}; //initialize default values.
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
var library = {};
var settings;
function loadSettings() {
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
if (window.location.href.indexOf('show/audio')>0) {
fixaudiopagination();
}
if (checkurl(location.href, settings['listSites'])) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
wireupnodes();
waitForEmbeds();
}
});
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
// 2013-01-31: Today's tumblr audio url
// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
function tasty(embed) {
var embedSrc = embed.getAttribute('src');
var a = document.createElement('a');
a.href = embedSrc;
var encodedSongURI = a.search.match(/audio_file=([^&]*)/)[1];
var songURL = decodeURIComponent(encodedSongURI).concat('?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
var songColor = a.search.match(/color=([^&]*)/)[1];
var songBGColor = '000000';
if (embedSrc.match(/\/audio_player\.swf/)) {
songBGColor = 'FFFFFF';
songColor = '5A5A5A';
}
var post_id = songURL.match(/audio_file\/([^\/]*)\/(\d+)\//)[2];
var post_url = 'http://www.tumblr.com/';
if (library.hasOwnProperty(post_id)) {
return;
}
library[post_id] = songURL;
var dl_a = document.createElement('a');
dl_a.setAttribute('href', songURL);
dl_a.setAttribute('style', 'background-color: #'+songBGColor+'; color: #'+songColor+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
embed.parentNode.appendChild(dl_span);
guaranteesize(embed,54,0);
// Find the post's URL.
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
post_url = anchors[a].href;
}
}
}
//Remove # anchors...
if (post_url.indexOf('#')>=0) {
post_url = post_url.substring(0,post_url.indexOf('#'));
}
if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
//We check our white list to see if we should add it to the playlist.
var whitelisted = false;
var blacklisted = false;
//Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
var post = document.getElementById('post_'+post_id);
for (itemWhite in settings['listWhite']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
whitelisted = true;
break;
}
}
// If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
if (!whitelisted) {
for (itemBlack in settings['listBlack']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
blacklisted = true;
break;
}
}
}
}
if (!blacklisted) {
console.log("sending "+songURL);
chrome.extension.sendRequest({song_url: songURL, post_id: post_id, post_url: post_url});
}
}
}
function guaranteesize(start_here,at_least_height,at_least_width) {
while (start_here.parentNode !== null || start_here.parentNode !== start_here.parentNode) {
if (start_here.parentNode === null || start_here.parentNode === undefined) {
return;
}
if (start_here.parentNode.offsetHeight < at_least_height && start_here.parentNode.className !== "post_content" && start_here.parentNode.style.getPropertyValue('display') !== 'none') {
start_here.parentNode.style.height = at_least_height + 'px';
}
if (start_here.parentNode.offsetWidth < at_least_width && start_here.parentNode.className !== "post_content" && start_here.parentNode.style.getPropertyValue('display') !== 'none') {
start_here.parentNode.style.width = at_least_width + 'px';
}
start_here = start_here.parentNode;
}
}
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
function handleNodeInserted(event) {
var newEmbeds = event.target.getElementsByTagName('EMBED');
if (!newEmbeds.length) {
return;
}
for (var i = 0, len = newEmbeds.length; i < len; i += 1) {
var newEmbed = newEmbeds[i];
if (hasSong(newEmbed)) {
tasty(newEmbed);
}
}
}
function wireupnodes() {
var cssRules = [];
document.addEventListener('animationstart', handleNodeInserted, false);
document.addEventListener('MSAnimationStart', handleNodeInserted, false);
document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
document.addEventListener('OAnimationStart', handleNodeInserted, false);
cssRules[0] = "@keyframes nodeInserted {";
cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[0] += "}";
cssRules[1] = "@-moz-keyframes nodeInserted {";
cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[1] += "}";
cssRules[2] = "@-webkit-keyframes nodeInserted {";
cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[2] += "}";
cssRules[3] = "@-ms-keyframes nodeInserted {";
cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[3] += "}";
cssRules[4] = "@-o-keyframes nodeInserted {";
cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
cssRules[4] += "}";
cssRules[5] = "ol#posts li {";
cssRules[5] += " animation-duration: 1ms;";
cssRules[5] += " -o-animation-duration: 1ms;";
cssRules[5] += " -ms-animation-duration: 1ms;";
cssRules[5] += " -moz-animation-duration: 1ms;";
cssRules[5] += " -webkit-animation-duration: 1ms;";
cssRules[5] += " animation-name: nodeInserted;";
cssRules[5] += " -o-animation-name: nodeInserted;";
cssRules[5] += " -ms-animation-name: nodeInserted;";
cssRules[5] += " -moz-animation-name: nodeInserted;";
cssRules[5] += " -webkit-animation-name: nodeInserted;";
cssRules[5] += "}";
addGlobalStyle("wires", cssRules);
}
var embeds;
function hasSong(embed) {
return embed.getAttribute('src').indexOf('/swf/audio_player') >= 0;
}
function waitForEmbeds() {
var embeds = document.getElementsByTagName('EMBED');
if (!embeds.length) {
setTimeout(waitForEmbeds, 10);
} else {
for (var i = 0, len = embeds.length; i < len; i += 1) {
var embed = embeds[i];
if (hasSong(embed)) {
tasty(embed);
}
}
}
}
-loadSettings();
\ No newline at end of file
+loadSettings();
+
+var s = document.createElement('script');
+s.src = chrome.extension.getURL("includes/injected.js");
+(document.head||document.documentElement).appendChild(s);
+s.parentNode.removeChild(s);
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index 048e69a..c723ac4 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,29 +1,30 @@
{
"name": "TumTaster",
- "version": "0.4.8",
+ "version": "0.4.9",
"description": "An extension that creates download links for the MP3s you see on Tumblr.",
"background": {
"page": "index.html"
},
"browser_action": {
"default_icon": "Icon-16.png",
"default_popup": "popup.html",
"default_title": "TumTaster"
},
"content_scripts": [ {
"js": [ "/includes/script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"icons": {
"16": "Icon-16.png",
"32": "Icon-32.png",
"48": "Icon-48.png",
"64": "Icon-64.png",
"128": "Icon-128.png"
},
"manifest_version": 2,
"options_page": "options.html",
"permissions": [
"http://*/*"
- ]
+ ],
+ "web_accessible_resources": [ "includes/injected.js" ]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
e4a1ff2eb45fd8afdd6b08ef3f6f9736646db2d0
|
v0.4.8: Updated for the new Tumblr layout. Also uses new sexy detection for new posts.
|
diff --git a/background.js b/background.js
new file mode 100644
index 0000000..9c0cfff
--- /dev/null
+++ b/background.js
@@ -0,0 +1,141 @@
+var nowplaying = null;
+
+if (localStorage["settings"] == undefined) {
+ settings = defaultSettings;
+} else {
+ settings = JSON.parse(localStorage["settings"]);
+}
+
+chrome.extension.onRequest.addListener(
+ function(message, sender, sendResponse) {
+ if (message == 'getSettings') {
+ sendResponse({settings: localStorage["settings"]});
+ } else {
+ addSong(message);
+ sendResponse({});
+ }
+});
+
+function addSong(newSong) {
+ switch (settings["mp3player"]) {
+ case "flash":
+ var mySoundObject = soundManager.createSound({
+ id: newSong.post_url,
+ url: newSong.song_url,
+ onloadfailed: function(){playnextsong(newSong.post_url)},
+ onfinish: function(){playnextsong(newSong.post_url)}
+ });
+ break;
+ case "html5":
+ var newAudio = document.createElement('audio');
+ newAudio.setAttribute('src', newSong.song_url);
+ newAudio.setAttribute('id', newSong.post_url);
+ var jukebox = document.getElementById('Jukebox');
+ jukebox.appendChild(newAudio);
+ break;
+ }
+}
+
+function getJukebox() {
+ var jukebox = document.getElementsByTagName('audio');
+ return jukebox;
+}
+
+function removeSong(rSong) {
+ var remove_song = document.getElementById(rSong);
+ remove_song.parentNode.removeChild(remove_song);
+}
+
+function playSong(song_url,post_url) {
+ switch (settings["mp3player"]) {
+ case "flash":
+
+ break;
+ case "html5":
+ play_song = document.getElementById(post_url);
+ play_song.addEventListener('ended',play_song,false);
+ play_song.play();
+ pl = getJukebox();
+ for(var x=0;x<pl.length;x++){
+ if(pl[x].id!=post_url){
+ pl[x].pause();
+ }
+ }
+ break;
+ }
+}
+
+function playnextsong(previous_song) {
+ var bad_idea = null;
+ var first_song = null;
+ var next_song = null;
+
+ switch (settings["mp3player"]) {
+ case "flash":
+ for (x in soundManager.sounds) {
+ if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = soundManager.sounds[x].sID;
+ }
+ bad_idea = soundManager.sounds[x].sID;
+ if (first_song == null) {
+ first_song = soundManager.sounds[x].sID;
+ }
+ }
+
+ if (settings["shuffle"]) {
+ var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ next_song = soundManager.soundIDs[s];
+ }
+
+ if (settings["repeat"] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
+
+ if (next_song != null) {
+ var soundNext = soundManager.getSoundById(next_song);
+ soundNext.play();
+ }
+ break;
+ case "html5":
+ var playlist = document.getElementsByTagName('audio');
+ for (x in playlist) {
+ if (playlist[x].src != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = playlist[x];
+ }
+ bad_idea = playlist[x].song_url;
+ if (first_song == null) {
+ first_song = playlist[0].song_url;
+ }
+ }
+
+ if (settings["shuffle"]) {
+ var s = Math.floor(Math.random()*playlist.length+1);
+ next_song = playlist[s];
+ }
+
+ if (settings["repeat"] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
+
+ if (next_song != null) {
+ playlist[x].play();
+ }
+ break;
+ }
+}
+
+function playrandomsong(previous_song) {
+ var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
+ mySoundObject.play();
+}
+
+document.addEventListener("DOMContentLoaded", function () {
+ soundManager.setup({"preferFlash": false});
+/* if (settings["mp3player"]=="flash") {
+ var fileref=document.createElement('script');
+ fileref.setAttribute("type","text/javascript");
+ fileref.setAttribute("src", "soundmanager2.js");
+ document.getElementsByTagName("head")[0].appendChild(fileref);
+ } */
+});
\ No newline at end of file
diff --git a/defaults.js b/defaults.js
new file mode 100644
index 0000000..7d61f8d
--- /dev/null
+++ b/defaults.js
@@ -0,0 +1,17 @@
+var defaultSettings = { //initialize default values.
+ 'version': '0.4.8',
+ 'shuffle': false,
+ 'repeat': true,
+ 'mp3player': 'flash',
+ 'listBlack': [
+ 'beatles'
+ ],
+ 'listWhite': [
+ 'bjorn',
+ 'beck'
+ ],
+ 'listSites': [
+ 'http://*.tumblr.com/*',
+ 'http://bjornstar.com/*'
+ ]
+};
\ No newline at end of file
diff --git a/includes/script.js b/includes/script.js
index 74007c6..9babc1a 100644
--- a/includes/script.js
+++ b/includes/script.js
@@ -1,173 +1,289 @@
+// Tumtaster
+// - By Bjorn Stromberg
+
+var defaultSettings = {
+ shuffle: false,
+ repeat: true,
+ mp3player: 'flash',
+ listBlack: [
+ 'beatles'
+ ],
+ listWhite: [
+ 'bjorn',
+ 'beck'
+ ],
+ listSites: [
+ 'http://*.tumblr.com/*',
+ 'http://bjornstar.com/*'
+ ],
+ version: '0.4.8'
+}; //initialize default values.
+
function addGlobalStyle(css) {
- var elmHead, elmStyle;
- elmHead = document.getElementsByTagName('head')[0];
- elmStyle = document.createElement('style');
- elmStyle.type = 'text/css';
- elmHead.appendChild(elmStyle);
- elmStyle.innerHTML = css;
+ var elmHead, elmStyle;
+ elmHead = document.getElementsByTagName('head')[0];
+ elmStyle = document.createElement('style');
+ elmStyle.type = 'text/css';
+ elmHead.appendChild(elmStyle);
+ elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
+var library = {};
var settings;
-var last_embed = 0;
-var song_embed = document.getElementsByTagName('embed');
function loadSettings() {
- var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
if (window.location.href.indexOf('show/audio')>0) {
- fixaudiopagination();
+ fixaudiopagination();
}
if (checkurl(location.href, settings['listSites'])) {
- try {
- document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
- } catch (e) {
- addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
- }
- setInterval(taste, 200);
- }
+ addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
+ wireupnodes();
+ waitForEmbeds();
+ }
});
}
function checkurl(url, filter) {
- for (var f in filter) {
- var filterRegex;
- filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
- var re = new RegExp(filterRegex);
- if (url.match(re)) {
- return true;
- }
- }
- return false;
+ for (var f in filter) {
+ var filterRegex;
+ filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
+ var re = new RegExp(filterRegex);
+ if (url.match(re)) {
+ return true;
+ }
+ }
+ return false;
}
-function taste() {
- for (var i=last_embed;i<song_embed.length;i++) {
- if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
- var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11,song_embed[i].getAttribute('src').indexOf('&color=')+13);
-
- var song_bgcolor = song_url.substr(song_url.indexOf("&color=")+7,6);
- var song_color = '777777';
-
- song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
-
- if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
- song_bgcolor = '000000';
- song_color = 'FFFFFF';
+// 2013-01-31: Today's tumblr audio url
+// - http://assets.tumblr.com/swf/audio_player_black.swf?audio_file=http%3A%2F%2Fwww.tumblr.com%2Faudio_file%2Fdnoeringi%2F41940197205%2Ftumblr_mhhof5DU8p1qbb49b&color=FFFFFF&logo=soundcloud
+// audio_file=http://www.tumblr.com/audio_file/dnoeringi/41940197205/tumblr_mhhof5DU8p1qbb49b
+
+
+function tasty(embed) {
+ var embedSrc = embed.getAttribute('src');
+
+ var a = document.createElement('a');
+ a.href = embedSrc;
+
+ var encodedSongURI = a.search.match(/audio_file=([^&]*)/)[1];
+
+ var songURL = decodeURIComponent(encodedSongURI).concat('?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
+
+ var songColor = a.search.match(/color=([^&]*)/)[1];
+ var songBGColor = '000000';
+
+ if (embedSrc.match(/\/audio_player\.swf/)) {
+ songBGColor = 'FFFFFF';
+ songColor = '5A5A5A';
+ }
+
+ var post_id = songURL.match(/audio_file\/([^\/]*)\/(\d+)\//)[2];
+ var post_url = 'http://www.tumblr.com/';
+
+ if (library.hasOwnProperty(post_id)) {
+ return;
+ }
+
+ library[post_id] = songURL;
+
+ var dl_a = document.createElement('a');
+ dl_a.setAttribute('href', songURL);
+ dl_a.setAttribute('style', 'background-color: #'+songBGColor+'; color: #'+songColor+'; text-decoration: none;');
+ dl_a.setAttribute('class', 'tumtaster');
+ dl_a.innerHTML = 'Click to download ';
+
+ var dl_span = document.createElement('span');
+ var dl_br = document.createElement('br');
+ dl_span.appendChild(dl_br);
+ dl_span.appendChild(dl_a);
+
+ embed.parentNode.appendChild(dl_span);
+ guaranteesize(embed,54,0);
+
+ // Find the post's URL.
+ var anchors = document.getElementsByTagName('a');
+ for (var a in anchors) {
+ if (anchors[a].href) {
+ if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
+ post_url = anchors[a].href;
}
+ }
+ }
- var post_id = song_url.match(/audio_file\/([\w\-]+)\/(\d+)\//)[2];
- var post_url = 'http://www.tumblr.com/';
-
- var dl_a = document.createElement('a');
- dl_a.setAttribute('href', song_url);
- dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
- dl_a.setAttribute('class', 'tumtaster');
- dl_a.innerHTML = 'Click to download ';
-
- var dl_span = document.createElement('span');
- var dl_br = document.createElement('br');
- dl_span.appendChild(dl_br);
- dl_span.appendChild(dl_a);
-
- song_embed[i].parentNode.appendChild(dl_span);
- guaranteesize(song_embed[i],54,0);
-
- // Find the post's URL.
- var anchors = document.getElementsByTagName('a');
- for (var a in anchors) {
- if (anchors[a].href) {
- if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
- post_url = anchors[a].href;
- }
+//Remove # anchors...
+ if (post_url.indexOf('#')>=0) {
+ post_url = post_url.substring(0,post_url.indexOf('#'));
+ }
+
+ if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
+
+ //We check our white list to see if we should add it to the playlist.
+ var whitelisted = false;
+ var blacklisted = false;
+
+ //Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
+
+ if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
+ var post = document.getElementById('post_'+post_id);
+
+ for (itemWhite in settings['listWhite']) {
+ if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
+ whitelisted = true;
+ break;
}
}
- //Remove # anchors...
- if (post_url.indexOf('#')>=0) {
- post_url = post_url.substring(0,post_url.indexOf('#'));
- }
-
- if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
-
- //We check our white list to see if we should add it to the playlist.
- var whitelisted = false;
- var blacklisted = false;
-
- //Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
-
- if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
- var post = document.getElementById('post_'+post_id);
-
- for (itemWhite in settings['listWhite']) {
- if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
- whitelisted = true;
- break;
- }
- }
-
- // If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
- if (!whitelisted) {
- for (itemBlack in settings['listBlack']) {
- if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
- blacklisted = true;
- break;
- }
- }
+ // If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
+ if (!whitelisted) {
+ for (itemBlack in settings['listBlack']) {
+ if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
+ blacklisted = true;
+ break;
}
}
- if (!blacklisted) {
- chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
- }
}
}
+ if (!blacklisted) {
+ console.log("sending "+songURL);
+ chrome.extension.sendRequest({song_url: songURL, post_id: post_id, post_url: post_url});
+ }
}
- last_embed = song_embed.length;
}
function guaranteesize(start_here,at_least_height,at_least_width) {
- while(start_here.parentNode!=undefined||start_here.parentNode!=start_here.parentNode) {
- if(start_here.parentNode.offsetHeight<at_least_height&&start_here.parentNode.className!="post_content"&&start_here.parentNode.style.getPropertyValue('display')!='none') {
- start_here.parentNode.style.height=at_least_height+'px';
- }
- if(start_here.parentNode.offsetWidth<at_least_width&&start_here.parentNode.className!="post_content"&&start_here.parentNode.style.getPropertyValue('display')!='none') {
- start_here.parentNode.style.width=at_least_width+'px';
- }
- start_here=start_here.parentNode;
- }
+ while (start_here.parentNode !== null || start_here.parentNode !== start_here.parentNode) {
+ if (start_here.parentNode === null || start_here.parentNode === undefined) {
+ return;
+ }
+ if (start_here.parentNode.offsetHeight < at_least_height && start_here.parentNode.className !== "post_content" && start_here.parentNode.style.getPropertyValue('display') !== 'none') {
+ start_here.parentNode.style.height = at_least_height + 'px';
+ }
+ if (start_here.parentNode.offsetWidth < at_least_width && start_here.parentNode.className !== "post_content" && start_here.parentNode.style.getPropertyValue('display') !== 'none') {
+ start_here.parentNode.style.width = at_least_width + 'px';
+ }
+ start_here = start_here.parentNode;
+ }
}
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
- var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
- if (isNaN(pagenumber)) {
- nextpagelink.href = currentpage+'/2';
- } else {
- nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
- }
-
- if (prevpagelink) {
- prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
- }
-
- var dashboard_controls = document.getElementById('dashboard_controls');
- if (dashboard_controls) {
- dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
- dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
- dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
- }
-
+ var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
+
+ if (isNaN(pagenumber)) {
+ nextpagelink.href = currentpage+'/2';
+ } else {
+ nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
+ }
+
+ if (prevpagelink) {
+ prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
+ }
+
+ var dashboard_controls = document.getElementById('dashboard_controls');
+
+ if (dashboard_controls) {
+ dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
+ dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
+ dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
+ }
+}
+
+function handleNodeInserted(event) {
+ var newEmbeds = event.target.getElementsByTagName('EMBED');
+
+ if (!newEmbeds.length) {
+ return;
+ }
+
+ for (var i = 0, len = newEmbeds.length; i < len; i += 1) {
+ var newEmbed = newEmbeds[i];
+ if (hasSong(newEmbed)) {
+ tasty(newEmbed);
+ }
+ }
+}
+
+function wireupnodes() {
+ var cssRules = [];
+
+ document.addEventListener('animationstart', handleNodeInserted, false);
+ document.addEventListener('MSAnimationStart', handleNodeInserted, false);
+ document.addEventListener('webkitAnimationStart', handleNodeInserted, false);
+ document.addEventListener('OAnimationStart', handleNodeInserted, false);
+
+ cssRules[0] = "@keyframes nodeInserted {";
+ cssRules[0] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[0] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[0] += "}";
+
+ cssRules[1] = "@-moz-keyframes nodeInserted {";
+ cssRules[1] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[1] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[1] += "}";
+
+ cssRules[2] = "@-webkit-keyframes nodeInserted {";
+ cssRules[2] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[2] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[2] += "}";
+
+ cssRules[3] = "@-ms-keyframes nodeInserted {";
+ cssRules[3] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[3] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[3] += "}";
+
+ cssRules[4] = "@-o-keyframes nodeInserted {";
+ cssRules[4] += " from { clip: rect(1px, auto, auto, auto); }";
+ cssRules[4] += " to { clip: rect(0px, auto, auto, auto); }";
+ cssRules[4] += "}";
+
+ cssRules[5] = "ol#posts li {";
+ cssRules[5] += " animation-duration: 1ms;";
+ cssRules[5] += " -o-animation-duration: 1ms;";
+ cssRules[5] += " -ms-animation-duration: 1ms;";
+ cssRules[5] += " -moz-animation-duration: 1ms;";
+ cssRules[5] += " -webkit-animation-duration: 1ms;";
+ cssRules[5] += " animation-name: nodeInserted;";
+ cssRules[5] += " -o-animation-name: nodeInserted;";
+ cssRules[5] += " -ms-animation-name: nodeInserted;";
+ cssRules[5] += " -moz-animation-name: nodeInserted;";
+ cssRules[5] += " -webkit-animation-name: nodeInserted;";
+ cssRules[5] += "}";
+
+ addGlobalStyle("wires", cssRules);
+}
+
+var embeds;
+
+function hasSong(embed) {
+ return embed.getAttribute('src').indexOf('/swf/audio_player') >= 0;
+}
+
+function waitForEmbeds() {
+ var embeds = document.getElementsByTagName('EMBED');
+ if (!embeds.length) {
+ setTimeout(waitForEmbeds, 10);
+ } else {
+ for (var i = 0, len = embeds.length; i < len; i += 1) {
+ var embed = embeds[i];
+ if (hasSong(embed)) {
+ tasty(embed);
+ }
+ }
+ }
}
loadSettings();
\ No newline at end of file
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..de8b017
--- /dev/null
+++ b/index.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<script src="defaults.js" type="text/javascript"></script>
+<script src="soundmanager2.js" type="text/javascript"></script>
+<script src="background.js" type="text/javascript"></script>
+</head>
+<body>
+<h1>TumTaster</h1>
+<div id="Jukebox">
+</div>
+</body>
+</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index 49fcee9..048e69a 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,29 @@
{
- "name": "TumTaster",
- "version": "0.4.7",
- "description": "An extension that creates download links for the MP3s you see on Tumblr.",
- "browser_action": {
- "default_icon": "Icon-16.png",
- "default_title": "TumTaster",
- "popup": "popup.html"
- },
- "icons": {
- "16": "Icon-16.png",
- "32": "Icon-32.png",
- "48": "Icon-48.png",
- "64": "Icon-64.png",
- "128": "Icon-128.png"
- },
- "background_page": "background.html",
- "options_page" : "options.html",
- "content_scripts": [ {
- "js": [ "/includes/script.js" ],
- "matches": [ "http://*/*", "https://*/*" ]
- } ]
+ "name": "TumTaster",
+ "version": "0.4.8",
+ "description": "An extension that creates download links for the MP3s you see on Tumblr.",
+ "background": {
+ "page": "index.html"
+ },
+ "browser_action": {
+ "default_icon": "Icon-16.png",
+ "default_popup": "popup.html",
+ "default_title": "TumTaster"
+ },
+ "content_scripts": [ {
+ "js": [ "/includes/script.js" ],
+ "matches": [ "http://*/*", "https://*/*" ]
+ } ],
+ "icons": {
+ "16": "Icon-16.png",
+ "32": "Icon-32.png",
+ "48": "Icon-48.png",
+ "64": "Icon-64.png",
+ "128": "Icon-128.png"
+ },
+ "manifest_version": 2,
+ "options_page": "options.html",
+ "permissions": [
+ "http://*/*"
+ ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 98fdee3..135d246 100644
--- a/options.html
+++ b/options.html
@@ -1,240 +1,112 @@
<html>
<head>
<title>Options for TumTaster</title>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:10px 30px 30px 10px;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
color:#4F545A;
width:640px;
}
h1{
color:black;
}
h2{
margin:0;
}
p{
margin:0;
}
a{
color:#4F545A;
text-decoration:none;
}
#content{
background: white;
display: block;
margin: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
padding-top: 5px;
width: 570px;
-webkit-border-radius: 10px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .46);
}
#repeat_div,#player_div{
margin-bottom:25px;
}
#listBlack,#listWhite{
float:left;
width:240px;
margin-bottom:25px;
}
#listSites{
clear:left;
width:540px;
}
#listSites input{
width:400px;
}
#version_div{
color:#A8B1BA;
font: 11px 'Lucida Grande',Verdana,sans-serif;
text-align:right;
}
#browser_span{
color:#A8B1BA;
font: 11px 'Lucida Grande',Verdana,sans-serif;
vertical-align:top;
}
</style>
- <script type="text/javascript">
- var defaultSettings = { 'version': '0.4.5', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
- var browser;
-
- function loadOptions() {
- var settings = localStorage['settings'];
-
- if (settings == undefined) {
- settings = defaultSettings;
- } else {
- settings = JSON.parse(settings);
- }
-
- var cbShuffle = document.getElementById("optionShuffle");
- cbShuffle.checked = settings['shuffle'];
-
- var cbRepeat = document.getElementById("optionRepeat");
- cbRepeat.checked = settings['repeat'];
-
- var select = document.getElementById("optionMP3Player");
- for (var i = 0; i < select.children.length; i++) {
- var child = select.children[i];
- if (child.value == settings['mp3player']) {
- child.selected = "true";
- break;
- }
- }
-
- for (var itemBlack in settings['listBlack']) {
- addInput("Black", settings['listBlack'][itemBlack]);
- }
-
- for (var itemWhite in settings['listWhite']) {
- addInput("White", settings['listWhite'][itemWhite]);
- }
-
- for (var itemSites in settings['listSites']) {
- addInput("Sites", settings['listSites'][itemSites]);
- }
-
- addInput("Black"); //prepare a blank input box.
- addInput("White"); //prepare a blank input box.
- addInput("Sites"); //prepare a blank input box.
-
- var version_div = document.getElementById('version_div');
- version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
-
- if (typeof opera != 'undefined') {
- var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Opera™";
- }
-
- if (typeof chrome != 'undefined') {
- var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Chrome™";
- }
-
- if (typeof safari != 'undefined') {
- var browser_span = document.getElementById('browser_span');
- browser_span.innerHTML = "for Safari™";
- }
- }
-
- function addInput(whichList, itemValue) {
- if (itemValue == undefined) {
- itemValue = "";
- }
-
- var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
- var listDiv = document.getElementById('list'+whichList);
- var listAdd = document.getElementById('list'+whichList+'Add');
-
- garbageInput = document.createElement('input');
- garbageInput.value = itemValue;
- garbageInput.name = 'option'+whichList;
- garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
- garbageAdd = document.createElement('a');
- garbageAdd.href = "#";
- garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
- garbageAdd.innerHTML = '<img src="'+PNGremove+'" /> ';
- garbageLinebreak = document.createElement('br');
- listDiv.insertBefore(garbageAdd,listAdd);
- listDiv.insertBefore(garbageInput,listAdd);
- listDiv.insertBefore(garbageLinebreak,listAdd);
- }
-
- function removeInput(garbageWhich) {
- var garbageInput = document.getElementById(garbageWhich);
- garbageInput.parentNode.removeChild(garbageInput.previousSibling);
- garbageInput.parentNode.removeChild(garbageInput.nextSibling);
- garbageInput.parentNode.removeChild(garbageInput);
- }
-
- function saveOptions() {
- var settings = {};
-
- var cbShuffle = document.getElementById('optionShuffle');
- settings['shuffle'] = cbShuffle.checked;
-
- var cbRepeat = document.getElementById('optionRepeat');
- settings['repeat'] = cbRepeat.checked;
-
- var selectMP3Player = document.getElementById('optionMP3Player');
- settings['mp3player'] = selectMP3Player.children[selectMP3Player.selectedIndex].value;
-
- settings['listWhite'] = [];
- settings['listBlack'] = [];
- settings['listSites'] = [];
-
- var garbages = document.getElementsByTagName('input');
- for (var i = 0; i< garbages.length; i++) {
- if (garbages[i].value != "") {
- if (garbages[i].name.substring(0,11) == "optionWhite") {
- settings['listWhite'].push(garbages[i].value);
- } else if (garbages[i].name.substring(0,11) == "optionBlack") {
- settings['listBlack'].push(garbages[i].value);
- } else if (garbages[i].name.substring(0,11) == "optionSites") {
- settings['listSites'].push(garbages[i].value);
- }
- }
- }
- localStorage['settings'] = JSON.stringify(settings);
- location.reload();
- }
-
- function eraseOptions() {
- localStorage.removeItem('settings');
- location.reload();
- }
- </script>
+ <script src="defaults.js" type="text/javascript"></script>
+ <script src="options.js" type="text/javascript"></script>
</head>
- <body onload="loadOptions()">
+ <body>
<div id="content">
<img style="float:left;" src="Icon-64.png">
<h1 style="line-height:32px;height:32px;margin-top:16px;">TumTaster Options <span id="browser_span"> </span></h1>
<div id="shuffle_div">
<input type="checkbox" id="optionShuffle" name="optionShuffle" /> <label for="optionShuffle"> Shuffle</label>
</div>
<div id="repeat_div">
<input type="checkbox" id="optionRepeat" name="optionRepeat" /> <label for="optionRepeat"> Repeat</label>
</div>
<div id="player_div">
<label for="optionMP3Player">MP3 Player Method: </label>
<select id="optionMP3Player" name="optionMP3Player" />
<option value="flash">Flash</option>
<option value="html5">HTML5</option>
</select>
</div>
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
- <a href="#" onclick="addInput('Black'); return false;" id="listBlackAdd">add</a><br />
+ <a href="#" id="listBlackAdd">add</a><br />
</div>
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
- <a href="#" onclick="addInput('White'); return false;" id="listWhiteAdd">add</a><br />
+ <a href="#" id="listWhiteAdd">add</a><br />
</div>
<div id="listSites">
<h2>Site List</h2>
<p>Run ChromeTaster on these sites:</p>
- <a href="#" onclick="addInput('Sites'); return false;" id="listSitesAdd">add</a><br />
+ <a href="#" id="listSitesAdd">add</a><br />
</div>
<br />
- <input onclick="saveOptions()" type="button" value="Save" />
- <input onclick="if (confirm('Are you sure you want to restore defaults?')) {eraseOptions();};" type="button" value="Restore default" />
+ <input id="save_btn" type="button" value="Save" />
+ <input id="reset_btn" type="button" value="Restore default" />
<div id="version_div"> </div>
</div>
</body>
</html>
\ No newline at end of file
diff --git a/options.js b/options.js
new file mode 100644
index 0000000..e34f66f
--- /dev/null
+++ b/options.js
@@ -0,0 +1,156 @@
+document.addEventListener("DOMContentLoaded", function () {
+ var save_btn = document.getElementById("save_btn");
+ var reset_btn = document.getElementById("reset_btn");
+ var listWhiteAdd = document.getElementById("listWhiteAdd");
+ var listBlackAdd = document.getElementById("listBlackAdd");
+ var listSitesAdd = document.getElementById("listSitesAdd");
+
+ save_btn.addEventListener("click", saveOptions);
+ reset_btn.addEventListener("click", function() { if (confirm("Are you sure you want to restore defaults?")) {eraseOptions()} });
+
+ listWhiteAdd.addEventListener("click", function(e) {
+ addInput("White");
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ listBlackAdd.addEventListener("click", function(e) {
+ addInput("Black");
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ listSitesAdd.addEventListener("click", function(e) {
+ addInput("Sites");
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ loadOptions();
+});
+
+function loadOptions() {
+ var settings = localStorage['settings'];
+
+ if (settings == undefined) {
+ settings = defaultSettings;
+ } else {
+ settings = JSON.parse(settings);
+ }
+
+ var cbShuffle = document.getElementById("optionShuffle");
+ cbShuffle.checked = settings['shuffle'];
+
+ var cbRepeat = document.getElementById("optionRepeat");
+ cbRepeat.checked = settings['repeat'];
+
+ var select = document.getElementById("optionMP3Player");
+ for (var i = 0; i < select.children.length; i++) {
+ var child = select.children[i];
+ if (child.value == settings['mp3player']) {
+ child.selected = "true";
+ break;
+ }
+ }
+
+ for (var itemBlack in settings['listBlack']) {
+ addInput("Black", settings['listBlack'][itemBlack]);
+ }
+
+ for (var itemWhite in settings['listWhite']) {
+ addInput("White", settings['listWhite'][itemWhite]);
+ }
+
+ for (var itemSites in settings['listSites']) {
+ addInput("Sites", settings['listSites'][itemSites]);
+ }
+
+ addInput("Black"); //prepare a blank input box.
+ addInput("White"); //prepare a blank input box.
+ addInput("Sites"); //prepare a blank input box.
+
+ var version_div = document.getElementById('version_div');
+ version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
+
+ if (typeof opera != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = "for Opera™";
+ }
+
+ if (typeof chrome != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = "for Chrome™";
+ }
+
+ if (typeof safari != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = "for Safari™";
+ }
+}
+
+function addInput(whichList, itemValue) {
+ if (itemValue == undefined) {
+ itemValue = "";
+ }
+
+ var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
+ var listDiv = document.getElementById('list'+whichList);
+ var listAdd = document.getElementById('list'+whichList+'Add');
+
+ garbageInput = document.createElement('input');
+ garbageInput.value = itemValue;
+ garbageInput.name = 'option'+whichList;
+ garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
+ garbageAdd = document.createElement('a');
+ garbageAdd.href = "#";
+ garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
+ garbageAdd.innerHTML = '<img src="'+PNGremove+'" /> ';
+ garbageLinebreak = document.createElement('br');
+ listDiv.insertBefore(garbageAdd,listAdd);
+ listDiv.insertBefore(garbageInput,listAdd);
+ listDiv.insertBefore(garbageLinebreak,listAdd);
+}
+
+function removeInput(garbageWhich) {
+ var garbageInput = document.getElementById(garbageWhich);
+ garbageInput.parentNode.removeChild(garbageInput.previousSibling);
+ garbageInput.parentNode.removeChild(garbageInput.nextSibling);
+ garbageInput.parentNode.removeChild(garbageInput);
+}
+
+function saveOptions() {
+ var settings = {};
+
+ var cbShuffle = document.getElementById('optionShuffle');
+ settings['shuffle'] = cbShuffle.checked;
+
+ var cbRepeat = document.getElementById('optionRepeat');
+ settings['repeat'] = cbRepeat.checked;
+
+ var selectMP3Player = document.getElementById('optionMP3Player');
+ settings['mp3player'] = selectMP3Player.children[selectMP3Player.selectedIndex].value;
+
+ settings['listWhite'] = [];
+ settings['listBlack'] = [];
+ settings['listSites'] = [];
+
+ var garbages = document.getElementsByTagName('input');
+ for (var i = 0; i< garbages.length; i++) {
+ if (garbages[i].value != "") {
+ if (garbages[i].name.substring(0,11) == "optionWhite") {
+ settings['listWhite'].push(garbages[i].value);
+ } else if (garbages[i].name.substring(0,11) == "optionBlack") {
+ settings['listBlack'].push(garbages[i].value);
+ } else if (garbages[i].name.substring(0,11) == "optionSites") {
+ settings['listSites'].push(garbages[i].value);
+ }
+ }
+ }
+ localStorage['settings'] = JSON.stringify(settings);
+ location.reload();
+}
+
+function eraseOptions() {
+ localStorage.removeItem('settings');
+ location.reload();
+}
diff --git a/popup.html b/popup.html
index 0baae99..e101d96 100644
--- a/popup.html
+++ b/popup.html
@@ -1,331 +1,190 @@
<html>
+<head>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a{
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
div#heading h1{
color: white;
float: left;
line-height:32px;
vertical-align:absmiddle;
margin-left:10px;
}
div#statistics{
position:absolute;
bottom:0%;
}
#controls{
text-align:center;
}
#statusbar{
position:relative;
height:12px;
background-color:#CDD568;
border:2px solid #eaf839;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
overflow:hidden;
margin-top:4px;
}
.remove{
position:absolute;
right:8px;
top:8px;
}
.position, .position2, .loading{
position:absolute;
left:0px;
bottom:0px;
height:12px;
}
.position{
background-color: #3B440F;
border-right:2px solid #3B440F;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
width:20px;
}
.position2{
background-color:#eaf839;
}
.loading {
background-color:#BBC552;
}
</style>
+<script src="popup.js" type="text/javascript"></script>
+</head>
+<body>
<div id="heading" style="width:100%;height:64px;"><img src="Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
<div id="statistics"><span> </span></div>
-<div id="nowplayingdiv"><span id="nowplaying">Now Playing: </span>
+<div id="nowplayingdiv"><span>Now Playing: </span><span id="nowplaying"> </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
<p id="controls">
-<a href="javascript:void(sm.stopAll())">■</a>
-<a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
-<script type="text/javascript">
-var bg = chrome.extension.getBackgroundPage();
-var sm = bg.soundManager;
+<a id="stop" href="#">■</a>
+<a id="pause" href="#">❙ ❙</a>
+<a id="play" href="#">▶</a>
+<a id="next" href="#">▶▶</a>
+<a id="random" href="#">Random</a></p>
-function remove(song_id) {
- switch (bg.settings["mp3player"]) {
- case "flash":
- sm.destroySound(song_id);
- var song_li = document.getElementById(song_id);
- song_li.parentNode.removeChild(song_li);
- break;
- case "html5":
- bg.removeSong(song_id);
- var song_li = document.getElementById(song_id);
- song_li.parentNode.removeChild(song_li);
- break;
- }
-}
-
-function pause() {
- current_song = get_currentsong();
- current_song.pause();
-}
-
-function play(song_url,post_url) {
- switch (bg.settings["mp3player"]) {
- case "flash":
- sm.stopAll();
- var mySoundObject = sm.getSoundById(post_url);
- mySoundObject.play();
- update_nowplaying();
- break;
- case "html5":
- bg.playSong(song_url,post_url);
- update_nowplaying();
- break;
- }
-}
-
-function get_currentsong() {
- var song_nowplaying = null;
- switch (bg.settings["mp3player"]){
- case "flash":
- for (sound in sm.sounds) {
- if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
- song_nowplaying = sm.sounds[sound];
- }
- }
- break;
- case "html5":
- var pl = bg.getJukebox();
- for (var x=0;x<pl.length;x++) {
- if (pl[x].currentTime<pl[x].duration && pl[x].currentTime>0 && !pl[x].paused) {
- song_nowplaying = pl[x];
- }
- }
- break;
- }
- return song_nowplaying;
-}
-
-function update_nowplaying() {
- var current_song = get_currentsong();
- if (current_song) {
- var nowplaying = document.getElementById('nowplaying');
- nowplaying.innerHTML = 'Now Playing: '+current_song.id;
- }
-}
-
-function update_statistics() {
- var count_songs = 0;
- count_songs = sm.soundIDs.length;
- var statistics = document.getElementById('statistics');
- //statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
-}
-
-function playnextsong() {
- var current_song = get_currentsong();
- var current_song_sID;
- if (current_song) {
- current_song.stop();
- current_song_sID = current_song.sID;
- }
- bg.playnextsong(current_song_sID);
- update_nowplaying();
-}
-
-function playrandomsong() {
- var current_song = get_currentsong();
- var current_song_sID;
- if (current_song) {
- current_song.stop();
- current_song_sID = current_song.sID;
- }
- bg.playrandomsong(current_song_sID);
- update_nowplaying();
-}
-
-document.write('<ol class="playlist">');
-
-var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
-
-switch (bg.settings["mp3player"]) {
- case "flash":
- var pl = sm.sounds;
- for (x in pl) {
- document.write('<li id="'+pl[x].sID+'">');
- document.write('<a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a>');
- document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
- }
- document.write('</ol>');
- break;
- case "html5":
- var pl = bg.getJukebox();
- for (x in pl) {
- if (pl[x].id!=undefined) {
- document.write('<li id="'+pl[x].id+'">');
- document.write('<a href="javascript:void(play(\''+pl[x].src+'\',\''+pl[x].id+'\'))">'+pl[x].id+'</a>');
- document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].id+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
- }
- }
- break;
-}
-
-document.write('</ol>');
-
-var div_loading = document.getElementById('loading');
-var div_position = document.getElementById('position');
-var div_position2 = document.getElementById('position2');
-
-function updateStatus() {
- var current_song = get_currentsong();
- if (current_song != undefined) {
- switch(bg.settings["mp3player"]) {
- case "flash":
- if (current_song.bytesTotal > 0) {
- div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
- }
- div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
- div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
- break;
- case "html5":
- div_position.style.left = (100 * current_song.currentTime / current_song.duration) + '%';
- div_position2.style.width = (100 * current_song.currentTime / current_song.duration) + '%';
- break;
- }
- }
-}
-
-setInterval(updateStatus, 200);
+<ol id="playlist" class="playlist">
+</ol>
-update_nowplaying();
-</script>
+</body>
</html>
\ No newline at end of file
diff --git a/popup.js b/popup.js
new file mode 100644
index 0000000..d3e4343
--- /dev/null
+++ b/popup.js
@@ -0,0 +1,198 @@
+var bg = chrome.extension.getBackgroundPage();
+var sm = bg.soundManager;
+
+var div_loading, div_position, div_position2, nowplaying;
+
+document.addEventListener("DOMContentLoaded", function () {
+ var stopLink = document.getElementById("stop");
+ var pauseLink = document.getElementById("pause");
+ var playLink = document.getElementById("play");
+ var nextLink = document.getElementById("next");
+ var randomLink = document.getElementById("random");
+
+ stopLink.addEventListener("click", function(e) {
+ sm.stopAll();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ pauseLink.addEventListener("click", function(e) {
+ pause();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ playLink.addEventListener("click", function(e) {
+ sm.resumeAll();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ nextLink.addEventListener("click", function(e) {
+ playnextsong();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ randomLink.addEventListener("click", function(e) {
+ playrandomsong();
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+
+ div_loading = document.getElementById('loading');
+ div_position = document.getElementById('position');
+ div_position2 = document.getElementById('position2');
+ nowplaying = document.getElementById('nowplaying');
+
+ var playlist = document.getElementById("playlist");
+
+ var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
+
+ setInterval(updateStatus, 200);
+
+ switch (bg.settings["mp3player"]) {
+ case "flash":
+ var pl = sm.sounds;
+ for (x in pl) {
+ var liSong = document.createElement('li');
+ var aSong = document.createElement('a');
+ aSong.id = pl[x].sID;
+ aSong.addEventListener("click", function(e) {
+ play(null, e.target.id);
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+ aSong.href = "#";
+ aSong.innerHTML = pl[x].sID;
+ var aRemove = document.createElement('a');
+ aRemove.className = "remove";
+ aRemove.href = "#";
+ aRemove.addEventListener("click", function(e) {
+ console.log(e.target.parentNode.previousSibling.id);
+ remove(e.target.parentNode.previousSibling.id);
+ e.preventDefault();
+ e.stopPropagation();
+ }, false);
+ var imgRemove = document.createElement('img');
+ imgRemove.src = PNGremove;
+ aRemove.appendChild(imgRemove);
+ liSong.appendChild(aSong);
+ liSong.appendChild(aRemove);
+ playlist.appendChild(liSong);
+ //document.write('<li id="'+pl[x].sID+'">');
+ //document.write('<a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a>');
+ //document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
+ }
+ break;
+ case "html5":
+ var pl = bg.getJukebox();
+ for (x in pl) {
+ if (pl[x].id!=undefined) {
+ //document.write('<li id="'+pl[x].id+'">');
+ //document.write('<a href="javascript:void(play(\''+pl[x].src+'\',\''+pl[x].id+'\'))">'+pl[x].id+'</a>');
+ //document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].id+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
+ }
+ }
+ break;
+ }
+});
+
+function remove(song_id) {
+ switch (bg.settings["mp3player"]) {
+ case "flash":
+ sm.destroySound(song_id);
+ var song_li = document.getElementById(song_id);
+ song_li.parentNode.parentNode.removeChild(song_li.parentNode);
+ break;
+ case "html5":
+ bg.removeSong(song_id);
+ var song_li = document.getElementById(song_id);
+ song_li.parentNode.parentNode.removeChild(song_li.parentNode);
+ break;
+ }
+}
+
+function pause() {
+ current_song = get_currentsong();
+ current_song.pause();
+}
+
+function play(song_url,post_url) {
+ switch (bg.settings["mp3player"]) {
+ case "flash":
+ sm.stopAll();
+ var mySoundObject = sm.getSoundById(post_url);
+ mySoundObject.play();
+ break;
+ case "html5":
+ bg.playSong(song_url,post_url);
+ break;
+ }
+}
+
+function get_currentsong() {
+ var song_nowplaying = null;
+ switch (bg.settings["mp3player"]){
+ case "flash":
+ for (sound in sm.sounds) {
+ if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
+ song_nowplaying = sm.sounds[sound];
+ }
+ }
+ break;
+ case "html5":
+ var pl = bg.getJukebox();
+ for (var x=0;x<pl.length;x++) {
+ if (pl[x].currentTime<pl[x].duration && pl[x].currentTime>0 && !pl[x].paused) {
+ song_nowplaying = pl[x];
+ }
+ }
+ break;
+ }
+ return song_nowplaying;
+}
+
+function playnextsong() {
+ var current_song = get_currentsong();
+ var current_song_sID;
+
+ if (current_song) {
+ current_song.stop();
+ current_song_sID = current_song.sID;
+ }
+
+ bg.playnextsong(current_song_sID);
+}
+
+function playrandomsong() {
+ var current_song = get_currentsong();
+ var current_song_sID;
+ if (current_song) {
+ current_song.stop();
+ current_song_sID = current_song.sID;
+ }
+ bg.playrandomsong(current_song_sID);
+}
+
+function updateStatus() {
+ var current_song = get_currentsong();
+ if (current_song != undefined) {
+ switch(bg.settings["mp3player"]) {
+ case "flash":
+ if (current_song.bytesTotal > 0) {
+ div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
+ }
+ div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
+ div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
+ break;
+ case "html5":
+ div_position.style.left = (100 * current_song.currentTime / current_song.duration) + '%';
+ div_position2.style.width = (100 * current_song.currentTime / current_song.duration) + '%';
+ break;
+ }
+ }
+ if (current_song && nowplaying.innerHTML != current_song.id) {
+ nowplaying.innerHTML = current_song.id;
+ }
+}
\ No newline at end of file
diff --git a/soundmanager2.js b/soundmanager2.js
index 8415e40..455df4f 100644
--- a/soundmanager2.js
+++ b/soundmanager2.js
@@ -1,1957 +1,5466 @@
-/*!
- SoundManager 2: Javascript Sound for the Web
- --------------------------------------------
- http://schillmania.com/projects/soundmanager2/
+/** @license
+ *
+ * SoundManager 2: JavaScript Sound for the Web
+ * ----------------------------------------------
+ * http://schillmania.com/projects/soundmanager2/
+ *
+ * Copyright (c) 2007, Scott Schiller. All rights reserved.
+ * Code provided under the BSD License:
+ * http://schillmania.com/projects/soundmanager2/license.txt
+ *
+ * V2.97a.20120624
+ */
+
+/*global window, SM2_DEFER, sm2Debugger, console, document, navigator, setTimeout, setInterval, clearInterval, Audio */
+/*jslint regexp: true, sloppy: true, white: true, nomen: true, plusplus: true */
+
+/**
+ * About this file
+ * ---------------
+ * This is the fully-commented source version of the SoundManager 2 API,
+ * recommended for use during development and testing.
+ *
+ * See soundmanager2-nodebug-jsmin.js for an optimized build (~10KB with gzip.)
+ * http://schillmania.com/projects/soundmanager2/doc/getstarted/#basic-inclusion
+ * Alternately, serve this file with gzip for 75% compression savings (~30KB over HTTP.)
+ *
+ * You may notice <d> and </d> comments in this source; these are delimiters for
+ * debug blocks which are removed in the -nodebug builds, further optimizing code size.
+ *
+ * Also, as you may note: Whoa, reliable cross-platform/device audio support is hard! ;)
+ */
+
+(function(window) {
- Copyright (c) 2007, Scott Schiller. All rights reserved.
- Code provided under the BSD License:
- http://schillmania.com/projects/soundmanager2/license.txt
+var soundManager = null;
- V2.95b.20100101
-*/
+/**
+ * The SoundManager constructor.
+ *
+ * @constructor
+ * @param {string} smURL Optional: Path to SWF files
+ * @param {string} smID Optional: The ID to use for the SWF container element
+ * @this {SoundManager}
+ * @return {SoundManager} The new SoundManager instance
+ */
-/*jslint undef: true, bitwise: true, newcap: true, immed: true */
+function SoundManager(smURL, smID) {
-var soundManager = null;
+ /**
+ * soundManager configuration options list
+ * defines top-level configuration properties to be applied to the soundManager instance (eg. soundManager.flashVersion)
+ * to set these properties, use the setup() method - eg., soundManager.setup({url: '/swf/', flashVersion: 9})
+ */
-function SoundManager(smURL, smID) {
+ this.setupOptions = {
+
+ 'url': (smURL || null), // path (directory) where SoundManager 2 SWFs exist, eg., /path/to/swfs/
+ 'flashVersion': 8, // flash build to use (8 or 9.) Some API features require 9.
+ 'debugMode': true, // enable debugging output (console.log() with HTML fallback)
+ 'debugFlash': false, // enable debugging output inside SWF, troubleshoot Flash/browser issues
+ 'useConsole': true, // use console.log() if available (otherwise, writes to #soundmanager-debug element)
+ 'consoleOnly': true, // if console is being used, do not create/write to #soundmanager-debug
+ 'waitForWindowLoad': false, // force SM2 to wait for window.onload() before trying to call soundManager.onload()
+ 'bgColor': '#ffffff', // SWF background color. N/A when wmode = 'transparent'
+ 'useHighPerformance': false, // position:fixed flash movie can help increase js/flash speed, minimize lag
+ 'flashPollingInterval': null, // msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used.
+ 'html5PollingInterval': null, // msec affecting whileplaying() for HTML5 audio, excluding mobile devices. If null, native HTML5 update events are used.
+ 'flashLoadTimeout': 1000, // msec to wait for flash movie to load before failing (0 = infinity)
+ 'wmode': null, // flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index to work)
+ 'allowScriptAccess': 'always', // for scripting the SWF (object/embed property), 'always' or 'sameDomain'
+ 'useFlashBlock': false, // *requires flashblock.css, see demos* - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable.
+ 'useHTML5Audio': true, // use HTML5 Audio() where API is supported (most Safari, Chrome versions), Firefox (no MP3/MP4.) Ideally, transparent vs. Flash API where possible.
+ 'html5Test': /^(probably|maybe)$/i, // HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative.
+ 'preferFlash': false, // overrides useHTML5audio. if true and flash support present, will try to use flash for MP3/MP4 as needed since HTML5 audio support is still quirky in browsers.
+ 'noSWFCache': false // if true, appends ?ts={date} to break aggressive SWF caching.
- this.flashVersion = 8; // version of flash to require, either 8 or 9. Some API features require Flash 9.
- this.debugMode = true; // enable debugging output (div#soundmanager-debug, OR console if available+configured)
- this.debugFlash = false; // enable debugging output inside SWF, troubleshoot Flash/browser issues
- this.useConsole = true; // use firebug/safari console.log()-type debug console if available
- this.consoleOnly = false; // if console is being used, do not create/write to #soundmanager-debug
- this.waitForWindowLoad = false; // force SM2 to wait for window.onload() before trying to call soundManager.onload()
- this.nullURL = 'null.mp3'; // path to "null" (empty) MP3 file, used to unload sounds (Flash 8 only)
- this.allowPolling = true; // allow flash to poll for status update (required for whileplaying() events, peak, sound spectrum functions to work.)
- this.useFastPolling = false; // uses 1 msec flash timer interval (vs. default of 20) for higher callback frequency, best combined with useHighPerformance
- this.useMovieStar = false; // enable support for Flash 9.0r115+ (codename "MovieStar") MPEG4 audio+video formats (AAC, M4V, FLV, MOV etc.)
- this.bgColor = '#ffffff'; // movie (.swf) background color, '#000000' useful if showing on-screen/full-screen video etc.
- this.useHighPerformance = false; // position:fixed flash movie can help increase js/flash speed, minimize lag
- this.flashLoadTimeout = 1000; // msec to wait for flash movie to load before failing (0 = infinity)
- this.wmode = null; // mode to render the flash movie in - null, transparent, opaque (last two allow layering of HTML on top)
- this.allowFullScreen = true; // enter full-screen (via double-click on movie) for flash 9+ video
- this.allowScriptAccess = 'always'; // for scripting the SWF (object/embed property), either 'always' or 'sameDomain'
+ };
this.defaultOptions = {
- 'autoLoad': false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can)
- 'stream': true, // allows playing before entire file has loaded (recommended)
- 'autoPlay': false, // enable playing of file as soon as possible (much faster if "stream" is true)
- 'onid3': null, // callback function for "ID3 data is added/available"
- 'onload': null, // callback function for "load finished"
- 'onloadfailed': null, // callback function for "load failed"
- 'whileloading': null, // callback function for "download progress update" (X of Y bytes received)
- 'onplay': null, // callback for "play" start
- 'onpause': null, // callback for "pause"
- 'onresume': null, // callback for "resume" (pause toggle)
- 'whileplaying': null, // callback during play (position update)
- 'onstop': null, // callback for "user stop"
- 'onfinish': null, // callback function for "sound finished playing"
- 'onbeforefinish': null, // callback for "before sound finished playing (at [time])"
- 'onbeforefinishtime': 5000, // offset (milliseconds) before end of sound to trigger beforefinish (eg. 1000 msec = 1 second)
- 'onbeforefinishcomplete':null, // function to call when said sound finishes playing
- 'onjustbeforefinish':null, // callback for [n] msec before end of current sound
- 'onjustbeforefinishtime':200, // [n] - if not using, set to 0 (or null handler) and event will not fire.
- 'multiShot': true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time
- 'multiShotEvents': false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled
- 'position': null, // offset (milliseconds) to seek to within loaded sound data.
- 'pan': 0, // "pan" settings, left-to-right, -100 to 100
- 'volume': 100 // self-explanatory. 0-100, the latter being the max.
- };
-
- this.flash9Options = { // flash 9-only options, merged into defaultOptions if flash 9 is being used
- 'isMovieStar': null, // "MovieStar" MPEG4 audio/video mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
- 'usePeakData': false, // enable left/right channel peak (level) data
- 'useWaveformData': false, // enable sound spectrum (raw waveform data) - WARNING: CPU-INTENSIVE: may set CPUs on fire.
- 'useEQData': false, // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.
- 'onbufferchange': null, // callback for "isBuffering" property change
- 'ondataerror': null // callback for waveform/eq data access error (flash playing audio in other tabs/domains)
- };
-
- this.movieStarOptions = { // flash 9.0r115+ MPEG4 audio/video options, merged into defaultOptions if flash 9+movieStar mode is enabled
- 'onmetadata': null, // callback for when video width/height etc. are received
- 'useVideo': false, // if loading movieStar content, whether to show video
- 'bufferTime': null // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try up to 3 seconds)
- };
-
- // jslint global declarations
- /*global SM2_DEFER, sm2Debugger, alert, console, document, navigator, setTimeout, window */
-
- var SMSound = null; // defined later
- var _s = this;
- var _sm = 'soundManager';
+
+ /**
+ * the default configuration for sound objects made with createSound() and related methods
+ * eg., volume, auto-load behaviour and so forth
+ */
+
+ 'autoLoad': false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can)
+ 'autoPlay': false, // enable playing of file as soon as possible (much faster if "stream" is true)
+ 'from': null, // position to start playback within a sound (msec), default = beginning
+ 'loops': 1, // how many times to repeat the sound (position will wrap around to 0, setPosition() will break out of loop when >0)
+ 'onid3': null, // callback function for "ID3 data is added/available"
+ 'onload': null, // callback function for "load finished"
+ 'whileloading': null, // callback function for "download progress update" (X of Y bytes received)
+ 'onplay': null, // callback for "play" start
+ 'onpause': null, // callback for "pause"
+ 'onresume': null, // callback for "resume" (pause toggle)
+ 'whileplaying': null, // callback during play (position update)
+ 'onposition': null, // object containing times and function callbacks for positions of interest
+ 'onstop': null, // callback for "user stop"
+ 'onfailure': null, // callback function for when playing fails
+ 'onfinish': null, // callback function for "sound finished playing"
+ 'multiShot': true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time
+ 'multiShotEvents': false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled
+ 'position': null, // offset (milliseconds) to seek to within loaded sound data.
+ 'pan': 0, // "pan" settings, left-to-right, -100 to 100
+ 'stream': true, // allows playing before entire file has loaded (recommended)
+ 'to': null, // position to end playback within a sound (msec), default = end
+ 'type': null, // MIME-like hint for file pattern / canPlay() tests, eg. audio/mp3
+ 'usePolicyFile': false, // enable crossdomain.xml request for audio on remote domains (for ID3/waveform access)
+ 'volume': 100 // self-explanatory. 0-100, the latter being the max.
+
+ };
+
+ this.flash9Options = {
+
+ /**
+ * flash 9-only options,
+ * merged into defaultOptions if flash 9 is being used
+ */
+
+ 'isMovieStar': null, // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
+ 'usePeakData': false, // enable left/right channel peak (level) data
+ 'useWaveformData': false, // enable sound spectrum (raw waveform data) - NOTE: May increase CPU load.
+ 'useEQData': false, // enable sound EQ (frequency spectrum data) - NOTE: May increase CPU load.
+ 'onbufferchange': null, // callback for "isBuffering" property change
+ 'ondataerror': null // callback for waveform/eq data access error (flash playing audio in other tabs/domains)
+
+ };
+
+ this.movieStarOptions = {
+
+ /**
+ * flash 9.0r115+ MPEG4 audio options,
+ * merged into defaultOptions if flash 9+movieStar mode is enabled
+ */
+
+ 'bufferTime': 3, // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try increasing.)
+ 'serverURL': null, // rtmp: FMS or FMIS server to connect to, required when requesting media via RTMP or one of its variants
+ 'onconnect': null, // rtmp: callback for connection to flash media server
+ 'duration': null // rtmp: song duration (msec)
+
+ };
+
+ this.audioFormats = {
+
+ /**
+ * determines HTML5 support + flash requirements.
+ * if no support (via flash and/or HTML5) for a "required" format, SM2 will fail to start.
+ * flash fallback is used for MP3 or MP4 if HTML5 can't play it (or if preferFlash = true)
+ * multiple MIME types may be tested while trying to get a positive canPlayType() response.
+ */
+
+ 'mp3': {
+ 'type': ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'],
+ 'required': true
+ },
+
+ 'mp4': {
+ 'related': ['aac','m4a'], // additional formats under the MP4 container
+ 'type': ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'],
+ 'required': false
+ },
+
+ 'ogg': {
+ 'type': ['audio/ogg; codecs=vorbis'],
+ 'required': false
+ },
+
+ 'wav': {
+ 'type': ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'],
+ 'required': false
+ }
+
+ };
+
+ // HTML attributes (id + class names) for the SWF container
+
+ this.movieID = 'sm2-container';
+ this.id = (smID || 'sm2movie');
+
+ this.debugID = 'soundmanager-debug';
+ this.debugURLParam = /([#?&])debug=1/i;
+
+ // dynamic attributes
+
+ this.versionNumber = 'V2.97a.20120624';
this.version = null;
- this.versionNumber = 'V2.95b.20100101';
this.movieURL = null;
- this.url = null;
this.altURL = null;
this.swfLoaded = false;
this.enabled = false;
- this.o = null;
- this.id = (smID || 'sm2movie');
this.oMC = null;
this.sounds = {};
this.soundIDs = [];
this.muted = false;
- this.isFullScreen = false; // set later by flash 9+
- this.isIE = (navigator.userAgent.match(/MSIE/i));
- this.isSafari = (navigator.userAgent.match(/safari/i));
- this.debugID = 'soundmanager-debug';
- this.debugURLParam = /([#?&])debug=1/i;
- this.specialWmodeCase = false;
- this._onready = [];
- this._debugOpen = true;
- this._didAppend = false;
- this._appendSuccess = false;
- this._didInit = false;
- this._disabled = false;
- this._windowLoaded = false;
- this._hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');
- this._debugLevels = ['log', 'info', 'warn', 'error'];
- this._defaultFlashVersion = 8;
- this._oRemoved = null;
- this._oRemovedHTML = null;
-
- var _$ = function(sID) {
- return document.getElementById(sID);
- };
+ this.didFlashBlock = false;
+ this.filePattern = null;
this.filePatterns = {
- flash8: /\.mp3(\?.*)?$/i,
- flash9: /\.mp3(\?.*)?$/i
+
+ 'flash8': /\.mp3(\?.*)?$/i,
+ 'flash9': /\.mp3(\?.*)?$/i
+
};
- this.netStreamTypes = ['aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'mp4v', '3gp', '3g2']; // Flash v9.0r115+ "moviestar" formats
- this.netStreamPattern = new RegExp('\\.('+this.netStreamTypes.join('|')+')(\\?.*)?$', 'i');
+ // support indicators, set at init
- this.filePattern = null;
this.features = {
- buffering: false,
- peakData: false,
- waveformData: false,
- eqData: false,
- movieStar: false
+
+ 'buffering': false,
+ 'peakData': false,
+ 'waveformData': false,
+ 'eqData': false,
+ 'movieStar': false
+
};
+ // flash sandbox info, used primarily in troubleshooting
+
this.sandbox = {
+
+ // <d>
'type': null,
'types': {
'remote': 'remote (domain-based) rules',
'localWithFile': 'local with file access (no internet access)',
'localWithNetwork': 'local with network (internet access only, no local access)',
'localTrusted': 'local, trusted (local+internet access)'
},
'description': null,
'noRemote': null,
'noLocal': null
+ // </d>
+
};
- this._setVersionInfo = function() {
- if (_s.flashVersion != 8 && _s.flashVersion != 9) {
- alert(_s._str('badFV',_s.flashVersion,_s._defaultFlashVersion));
- _s.flashVersion = _s._defaultFlashVersion;
+ /**
+ * basic HTML5 Audio() support test
+ * try...catch because of IE 9 "not implemented" nonsense
+ * https://github.com/Modernizr/Modernizr/issues/224
+ */
+
+ this.hasHTML5 = (function() {
+ try {
+ return (typeof Audio !== 'undefined' && typeof new Audio().canPlayType !== 'undefined');
+ } catch(e) {
+ return false;
}
- _s.version = _s.versionNumber+(_s.flashVersion == 9?' (AS3/Flash 9)':' (AS2/Flash 8)');
- // set up default options
- if (_s.flashVersion > 8) {
- _s.defaultOptions = _s._mergeObjects(_s.defaultOptions, _s.flash9Options);
- _s.features.buffering = true;
+ }());
+
+ /**
+ * format support (html5/flash)
+ * stores canPlayType() results based on audioFormats.
+ * eg. { mp3: boolean, mp4: boolean }
+ * treat as read-only.
+ */
+
+ this.html5 = {
+ 'usingFlash': null // set if/when flash fallback is needed
+ };
+
+ // file type support hash
+ this.flash = {};
+
+ // determined at init time
+ this.html5Only = false;
+
+ // used for special cases (eg. iPad/iPhone/palm OS?)
+ this.ignoreFlash = false;
+
+ /**
+ * a few private internals (OK, a lot. :D)
+ */
+
+ var SMSound,
+ _s = this, _flash = null, _sm = 'soundManager', _smc = _sm+'::', _h5 = 'HTML5::', _id, _ua = navigator.userAgent, _win = window, _wl = _win.location.href.toString(), _doc = document, _doNothing, _setProperties, _init, _fV, _on_queue = [], _debugOpen = true, _debugTS, _didAppend = false, _appendSuccess = false, _didInit = false, _disabled = false, _windowLoaded = false, _wDS, _wdCount = 0, _initComplete, _mixin, _assign, _extraOptions, _addOnEvent, _processOnEvents, _initUserOnload, _delayWaitForEI, _waitForEI, _setVersionInfo, _handleFocus, _strings, _initMovie, _domContentLoaded, _winOnLoad, _didDCLoaded, _getDocument, _createMovie, _catchError, _setPolling, _initDebug, _debugLevels = ['log', 'info', 'warn', 'error'], _defaultFlashVersion = 8, _disableObject, _failSafely, _normalizeMovieURL, _oRemoved = null, _oRemovedHTML = null, _str, _flashBlockHandler, _getSWFCSS, _swfCSS, _toggleDebug, _loopFix, _policyFix, _complain, _idCheck, _waitingForEI = false, _initPending = false, _startTimer, _stopTimer, _timerExecute, _h5TimerCount = 0, _h5IntervalTimer = null, _parseURL,
+ _needsFlash = null, _featureCheck, _html5OK, _html5CanPlay, _html5Ext, _html5Unload, _domContentLoadedIE, _testHTML5, _event, _slice = Array.prototype.slice, _useGlobalHTML5Audio = false, _hasFlash, _detectFlash, _badSafariFix, _html5_events, _showSupport,
+ _is_iDevice = _ua.match(/(ipad|iphone|ipod)/i), _isIE = _ua.match(/msie/i), _isWebkit = _ua.match(/webkit/i), _isSafari = (_ua.match(/safari/i) && !_ua.match(/chrome/i)), _isOpera = (_ua.match(/opera/i)),
+ _mobileHTML5 = (_ua.match(/(mobile|pre\/|xoom)/i) || _is_iDevice),
+ _isBadSafari = (!_wl.match(/usehtml5audio/i) && !_wl.match(/sm2\-ignorebadua/i) && _isSafari && !_ua.match(/silk/i) && _ua.match(/OS X 10_6_([3-7])/i)), // Safari 4 and 5 (excluding Kindle Fire, "Silk") occasionally fail to load/play HTML5 audio on Snow Leopard 10.6.3 through 10.6.7 due to bug(s) in QuickTime X and/or other underlying frameworks. :/ Confirmed bug. https://bugs.webkit.org/show_bug.cgi?id=32159
+ _hasConsole = (typeof console !== 'undefined' && typeof console.log !== 'undefined'), _isFocused = (typeof _doc.hasFocus !== 'undefined'?_doc.hasFocus():null), _tryInitOnFocus = (_isSafari && (typeof _doc.hasFocus === 'undefined' || !_doc.hasFocus())), _okToDisable = !_tryInitOnFocus, _flashMIME = /(mp3|mp4|mpa|m4a)/i,
+ _emptyURL = 'about:blank', // safe URL to unload, or load nothing from (flash 8 + most HTML5 UAs)
+ _overHTTP = (_doc.location?_doc.location.protocol.match(/http/i):null),
+ _http = (!_overHTTP ? 'http:/'+'/' : ''),
+ // mp3, mp4, aac etc.
+ _netStreamMimeTypes = /^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|mp4v|3gp|3g2)\s*(?:$|;)/i,
+ // Flash v9.0r115+ "moviestar" formats
+ _netStreamTypes = ['mpeg4', 'aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'mp4v', '3gp', '3g2'],
+ _netStreamPattern = new RegExp('\\.(' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i');
+
+ this.mimePattern = /^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i; // default mp3 set
+
+ // use altURL if not "online"
+ this.useAltURL = !_overHTTP;
+
+ this._global_a = null;
+
+ _swfCSS = {
+
+ 'swfBox': 'sm2-object-box',
+ 'swfDefault': 'movieContainer',
+ 'swfError': 'swf_error', // SWF loaded, but SM2 couldn't start (other error)
+ 'swfTimedout': 'swf_timedout',
+ 'swfLoaded': 'swf_loaded',
+ 'swfUnblocked': 'swf_unblocked', // or loaded OK
+ 'sm2Debug': 'sm2_debug',
+ 'highPerf': 'high_performance',
+ 'flashDebug': 'flash_debug'
+
+ };
+
+ if (_mobileHTML5) {
+
+ // prefer HTML5 for mobile + tablet-like devices, probably more reliable vs. flash at this point.
+ _s.useHTML5Audio = true;
+ _s.preferFlash = false;
+
+ if (_is_iDevice) {
+ // by default, use global feature. iOS onfinish() -> next may fail otherwise.
+ _s.ignoreFlash = true;
+ _useGlobalHTML5Audio = true;
}
- if (_s.flashVersion > 8 && _s.useMovieStar) {
- // flash 9+ support for movieStar formats as well as MP3
- _s.defaultOptions = _s._mergeObjects(_s.defaultOptions, _s.movieStarOptions);
- _s.filePatterns.flash9 = new RegExp('\\.(mp3|'+_s.netStreamTypes.join('|')+')(\\?.*)?$', 'i');
- _s.features.movieStar = true;
- } else {
- _s.useMovieStar = false;
- _s.features.movieStar = false;
+
+ }
+
+ /**
+ * Public SoundManager API
+ * -----------------------
+ */
+
+ /**
+ * Configures top-level soundManager properties.
+ *
+ * @param {object} options Option parameters, eg. { flashVersion: 9, url: '/path/to/swfs/' }
+ * onready and ontimeout are also accepted parameters. call soundManager.setup() to see the full list.
+ */
+
+ this.setup = function(options) {
+
+ // warn if flash options have already been applied
+
+ if (typeof options !== 'undefined' && _didInit && _needsFlash && _s.ok() && (typeof options.flashVersion !== 'undefined' || typeof options.url !== 'undefined')) {
+ _complain(_str('setupLate'));
}
- _s.filePattern = _s.filePatterns[(_s.flashVersion != 8?'flash9':'flash8')];
- _s.movieURL = (_s.flashVersion == 8?'soundmanager2.swf':'soundmanager2_flash9.swf');
- _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_s.flashVersion > 8);
- };
- this._overHTTP = (document.location?document.location.protocol.match(/http/i):null);
- this._waitingforEI = false;
- this._initPending = false;
- this._tryInitOnFocus = (this.isSafari && typeof document.hasFocus == 'undefined');
- this._isFocused = (typeof document.hasFocus != 'undefined'?document.hasFocus():null);
- this._okToDisable = !this._tryInitOnFocus;
+ // TODO: defer: true?
- this.useAltURL = !this._overHTTP; // use altURL if not "online"
- var flashCPLink = 'http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html';
+ _assign(options);
+
+ return _s;
- this.strings = {
- notReady: 'Not loaded yet - wait for soundManager.onload() before calling sound-related methods',
- appXHTML: _sm+'_createMovie(): appendChild/innerHTML set failed. May be app/xhtml+xml DOM-related.',
- swf404: _sm+': Verify that %s is a valid path.',
- tryDebug: 'Try '+_sm+'.debugFlash = true for more security details (output goes to SWF.)',
- checkSWF: 'See SWF output for more debug info.',
- localFail: _sm+': Non-HTTP page ('+document.location.protocol+' URL?) Review Flash player security settings for this special case:\n'+flashCPLink+'\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/',
- waitFocus: _sm+': Special case: Waiting for focus-related event..',
- waitImpatient: _sm+': Getting impatient, still waiting for Flash%s...',
- waitForever: _sm+': Waiting indefinitely for Flash...',
- needFunction: _sm+'.onready(): Function object expected',
- badID: 'Warning: Sound ID "%s" should be a string, starting with a non-numeric character',
- fl9Vid: 'flash 9 required for video. Exiting.',
- noMS: 'MovieStar mode not enabled. Exiting.',
- spcWmode: _sm+'._createMovie(): Removing wmode, preventing win32 below-the-fold SWF loading issue',
- currentObj: '--- '+_sm+'._debug(): Current sound objects ---',
- waitEI: _sm+'._initMovie(): Waiting for ExternalInterface call from Flash..',
- waitOnload: _sm+': Waiting for window.onload()',
- docLoaded: _sm+': Document already loaded',
- onload: _sm+'.initComplete(): calling soundManager.onload()',
- onloadOK: _sm+'.onload() complete',
- init: '-- '+_sm+'.init() --',
- didInit: _sm+'.init(): Already called?',
- flashJS: _sm+': Attempting to call Flash from JS..',
- noPolling: _sm+': Polling (whileloading()/whileplaying() support) is disabled.',
- secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html',
- badRemove: 'Warning: Failed to remove flash movie.',
- peakWave: 'Warning: peak/waveform/eqData features unsupported for non-MP3 formats',
- shutdown: _sm+'.disable(): Shutting down',
- queue: _sm+'.onready(): Queueing handler',
- smFail: _sm+': Failed to initialise.',
- smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.',
- manURL: 'SMSound.load(): Using manually-assigned URL',
- onURL: _sm+'.load(): current URL already assigned.',
- badFV: 'soundManager.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.'
- };
-
- this._str = function() { // o [,items to replace]
- var params = Array.prototype.slice.call(arguments); // real array, please
- var o = params.shift(); // first arg
- var str = _s.strings && _s.strings[o]?_s.strings[o]:'';
- if (str && params && params.length) {
- for (var i=0, j=params.length; i<j; i++) {
- str = str.replace('%s',params[i]);
- }
- }
- return str;
};
- // --- public methods ---
- this.supported = function() {
- return (_s._didInit && !_s._disabled);
+ this.ok = function() {
+
+ return (_needsFlash?(_didInit && !_disabled):(_s.useHTML5Audio && _s.hasHTML5));
+
};
+ this.supported = this.ok; // legacy
+
this.getMovie = function(smID) {
- return _s.isIE?window[smID]:(_s.isSafari?_$(smID) || document[smID]:_$(smID));
- };
- this.loadFromXML = function(sXmlUrl) {
- try {
- _s.o._loadFromXML(sXmlUrl);
- } catch(e) {
- _s._failSafely();
- return true;
- }
+ // safety net: some old browsers differ on SWF references, possibly related to ExternalInterface / flash version
+ return _id(smID) || _doc[smID] || _win[smID];
+
};
- this.createSound = function(oOptions) {
- var _cs = 'soundManager.createSound(): ';
- if (!_s._didInit) {
- throw _s._complain(_cs+_s._str('notReady'), arguments.callee.caller);
+ /**
+ * Creates a SMSound sound object instance.
+ *
+ * @param {object} oOptions Sound options (at minimum, id and url parameters are required.)
+ * @return {object} SMSound The new SMSound object.
+ */
+
+ this.createSound = function(oOptions, _url) {
+
+ var _cs, _cs_string, thisOptions = null, oSound = null, _tO = null;
+
+ // <d>
+ _cs = _sm+'.createSound(): ';
+ _cs_string = _cs + _str(!_didInit?'notReady':'notOK');
+ // </d>
+
+ if (!_didInit || !_s.ok()) {
+ _complain(_cs_string);
+ return false;
}
- if (arguments.length == 2) {
+
+ if (typeof _url !== 'undefined') {
// function overloading in JS! :) ..assume simple createSound(id,url) use case
oOptions = {
- 'id': arguments[0],
- 'url': arguments[1]
+ 'id': oOptions,
+ 'url': _url
};
}
- var thisOptions = _s._mergeObjects(oOptions); // inherit SM2 defaults
- var _tO = thisOptions; // alias
- if (_tO.id.toString().charAt(0).match(/^[0-9]$/)) { // hopefully this isn't buggy regexp-fu. :D
- _s._wD(_cs+_s._str('badID',_tO.id), 2);
+
+ // inherit from defaultOptions
+ thisOptions = _mixin(oOptions);
+
+ thisOptions.url = _parseURL(thisOptions.url);
+
+ // local shortcut
+ _tO = thisOptions;
+
+ // <d>
+ if (_tO.id.toString().charAt(0).match(/^[0-9]$/)) {
+ _s._wD(_cs + _str('badID', _tO.id), 2);
}
- _s._wD(_cs+_tO.id+' ('+_tO.url+')', 1);
- if (_s._idCheck(_tO.id, true)) {
- _s._wD(_cs+_tO.id+' exists', 1);
+
+ _s._wD(_cs + _tO.id + ' (' + _tO.url + ')', 1);
+ // </d>
+
+ if (_idCheck(_tO.id, true)) {
+ _s._wD(_cs + _tO.id + ' exists', 1);
return _s.sounds[_tO.id];
}
- if (_s.flashVersion > 8 && _s.useMovieStar) {
- if (_tO.isMovieStar === null) {
- _tO.isMovieStar = (_tO.url.match(_s.netStreamPattern)?true:false);
- }
- if (_tO.isMovieStar) {
- _s._wD(_cs+'using MovieStar handling');
- }
- if (_tO.isMovieStar && (_tO.usePeakData || _tO.useWaveformData || _tO.useEQData)) {
- _s._wDS('peakWave');
- _tO.usePeakData = false;
- _tO.useWaveformData = false;
- _tO.useEQData = false;
- }
+
+ function make() {
+
+ thisOptions = _loopFix(thisOptions);
+ _s.sounds[_tO.id] = new SMSound(_tO);
+ _s.soundIDs.push(_tO.id);
+ return _s.sounds[_tO.id];
+
}
- _s.sounds[_tO.id] = new SMSound(_tO);
- _s.soundIDs[_s.soundIDs.length] = _tO.id;
- // AS2:
- if (_s.flashVersion == 8) {
- _s.o._createSound(_tO.id, _tO.onjustbeforefinishtime);
+
+ if (_html5OK(_tO)) {
+
+ oSound = make();
+ _s._wD('Creating sound '+_tO.id+', using HTML5');
+ oSound._setup_html5(_tO);
+
} else {
- _s.o._createSound(_tO.id, _tO.url, _tO.onjustbeforefinishtime, _tO.usePeakData, _tO.useWaveformData, _tO.useEQData, _tO.isMovieStar, (_tO.isMovieStar?_tO.useVideo:false), (_tO.isMovieStar?_tO.bufferTime:false));
- }
- if (_tO.autoLoad || _tO.autoPlay) {
- // TODO: does removing timeout here cause problems?
- if (_s.sounds[_tO.id]) {
- _s.sounds[_tO.id].load(_tO);
+
+ if (_fV > 8) {
+ if (_tO.isMovieStar === null) {
+ // attempt to detect MPEG-4 formats
+ _tO.isMovieStar = !!(_tO.serverURL || (_tO.type ? _tO.type.match(_netStreamMimeTypes) : false) || _tO.url.match(_netStreamPattern));
+ }
+ // <d>
+ if (_tO.isMovieStar) {
+ _s._wD(_cs + 'using MovieStar handling');
+ if (_tO.loops > 1) {
+ _wDS('noNSLoop');
+ }
+ }
+ // </d>
+ }
+
+ _tO = _policyFix(_tO, _cs);
+ oSound = make();
+
+ if (_fV === 8) {
+ _flash._createSound(_tO.id, _tO.loops||1, _tO.usePolicyFile);
+ } else {
+ _flash._createSound(_tO.id, _tO.url, _tO.usePeakData, _tO.useWaveformData, _tO.useEQData, _tO.isMovieStar, (_tO.isMovieStar?_tO.bufferTime:false), _tO.loops||1, _tO.serverURL, _tO.duration||null, _tO.autoPlay, true, _tO.autoLoad, _tO.usePolicyFile);
+ if (!_tO.serverURL) {
+ // We are connected immediately
+ oSound.connected = true;
+ if (_tO.onconnect) {
+ _tO.onconnect.apply(oSound);
+ }
+ }
+ }
+
+ if (!_tO.serverURL && (_tO.autoLoad || _tO.autoPlay)) {
+ // call load for non-rtmp streams
+ oSound.load(_tO);
}
- }
- if (_tO.autoPlay) {
- _s.sounds[_tO.id].play();
- }
- return _s.sounds[_tO.id];
- };
- this.createVideo = function(oOptions) {
- var fN = 'soundManager.createVideo(): ';
- if (arguments.length == 2) {
- oOptions = {
- 'id': arguments[0],
- 'url': arguments[1]
- };
- }
- if (_s.flashVersion >= 9) {
- oOptions.isMovieStar = true;
- oOptions.useVideo = true;
- } else {
- _s._wD(fN+_s._str('f9Vid'), 2);
- return false;
}
- if (!_s.useMovieStar) {
- _s._wD(fN+_s._str('noMS'), 2);
+
+ // rtmp will play in onconnect
+ if (!_tO.serverURL && _tO.autoPlay) {
+ oSound.play();
}
- return _s.createSound(oOptions);
+
+ return oSound;
+
};
- this.destroySound = function(sID, bFromSound) {
+ /**
+ * Destroys a SMSound sound object instance.
+ *
+ * @param {string} sID The ID of the sound to destroy
+ */
+
+ this.destroySound = function(sID, _bFromSound) {
+
// explicitly destroy a sound before normal page unload, etc.
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- for (var i=0; i<_s.soundIDs.length; i++) {
- if (_s.soundIDs[i] == sID) {
+
+ var oS = _s.sounds[sID], i;
+
+ // Disable all callbacks while the sound is being destroyed
+ oS._iO = {};
+
+ oS.stop();
+ oS.unload();
+
+ for (i = 0; i < _s.soundIDs.length; i++) {
+ if (_s.soundIDs[i] === sID) {
_s.soundIDs.splice(i, 1);
- continue;
+ break;
}
}
- // conservative option: avoid crash with flash 8
- // calling destroySound() within a sound onload() might crash firefox, certain flavours of winXP+flash 8??
- // if (_s.flashVersion != 8) {
- _s.sounds[sID].unload();
- // }
- if (!bFromSound) {
+
+ if (!_bFromSound) {
// ignore if being called from SMSound instance
- _s.sounds[sID].destruct();
+ oS.destruct(true);
}
+
+ oS = null;
delete _s.sounds[sID];
+
+ return true;
+
};
- this.destroyVideo = this.destroySound;
+ /**
+ * Calls the load() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {object} oOptions Optional: Sound options
+ */
this.load = function(sID, oOptions) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].load(oOptions);
+ return _s.sounds[sID].load(oOptions);
+
};
+ /**
+ * Calls the unload() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ */
+
this.unload = function(sID) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
+ return false;
+ }
+ return _s.sounds[sID].unload();
+
+ };
+
+ /**
+ * Calls the onPosition() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {number} nPosition The position to watch for
+ * @param {function} oMethod The relevant callback to fire
+ * @param {object} oScope Optional: The scope to apply the callback to
+ * @return {SMSound} The SMSound object
+ */
+
+ this.onPosition = function(sID, nPosition, oMethod, oScope) {
+
+ if (!_idCheck(sID)) {
+ return false;
+ }
+ return _s.sounds[sID].onposition(nPosition, oMethod, oScope);
+
+ };
+
+ // legacy/backwards-compability: lower-case method name
+ this.onposition = this.onPosition;
+
+ /**
+ * Calls the clearOnPosition() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {number} nPosition The position to watch for
+ * @param {function} oMethod Optional: The relevant callback to fire
+ * @return {SMSound} The SMSound object
+ */
+
+ this.clearOnPosition = function(sID, nPosition, oMethod) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].unload();
+ return _s.sounds[sID].clearOnPosition(nPosition, oMethod);
+
};
+ /**
+ * Calls the play() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {object} oOptions Optional: Sound options
+ * @return {SMSound} The SMSound object
+ */
+
this.play = function(sID, oOptions) {
- var fN = 'soundManager.play(): ';
- if (!_s._didInit) {
- throw _s._complain(fN+_s._str('notReady'), arguments.callee.caller);
+
+ var result = false;
+
+ if (!_didInit || !_s.ok()) {
+ _complain(_sm+'.play(): ' + _str(!_didInit?'notReady':'notOK'));
+ return result;
}
- if (!_s._idCheck(sID)) {
- if (typeof oOptions != 'Object') {
+
+ if (!_idCheck(sID)) {
+ if (!(oOptions instanceof Object)) {
+ // overloading use case: play('mySound','/path/to/some.mp3');
oOptions = {
url: oOptions
- }; // overloading use case: play('mySound','/path/to/some.mp3');
+ };
}
if (oOptions && oOptions.url) {
- // overloading use case, creation+playing of sound: .play('someID',{url:'/path/to.mp3'});
- _s._wD(fN+'attempting to create "'+sID+'"', 1);
+ // overloading use case, create+play: .play('someID',{url:'/path/to.mp3'});
+ _s._wD(_sm+'.play(): attempting to create "' + sID + '"', 1);
oOptions.id = sID;
- _s.createSound(oOptions);
- } else {
- return false;
+ result = _s.createSound(oOptions).play();
}
+ return result;
}
- _s.sounds[sID].play(oOptions);
+
+ return _s.sounds[sID].play(oOptions);
+
};
this.start = this.play; // just for convenience
+ /**
+ * Calls the setPosition() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {number} nMsecOffset Position (milliseconds)
+ * @return {SMSound} The SMSound object
+ */
+
this.setPosition = function(sID, nMsecOffset) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].setPosition(nMsecOffset);
+ return _s.sounds[sID].setPosition(nMsecOffset);
+
};
+ /**
+ * Calls the stop() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @return {SMSound} The SMSound object
+ */
+
this.stop = function(sID) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s._wD('soundManager.stop('+sID+')', 1);
- _s.sounds[sID].stop();
+
+ _s._wD(_sm+'.stop(' + sID + ')', 1);
+ return _s.sounds[sID].stop();
+
};
+ /**
+ * Stops all currently-playing sounds.
+ */
+
this.stopAll = function() {
- _s._wD('soundManager.stopAll()', 1);
- for (var oSound in _s.sounds) {
- if (_s.sounds[oSound] instanceof SMSound) {
- _s.sounds[oSound].stop(); // apply only to sound objects
+
+ var oSound;
+ _s._wD(_sm+'.stopAll()', 1);
+
+ for (oSound in _s.sounds) {
+ if (_s.sounds.hasOwnProperty(oSound)) {
+ // apply only to sound objects
+ _s.sounds[oSound].stop();
}
}
+
};
+ /**
+ * Calls the pause() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @return {SMSound} The SMSound object
+ */
+
this.pause = function(sID) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].pause();
+ return _s.sounds[sID].pause();
+
};
+ /**
+ * Pauses all currently-playing sounds.
+ */
+
this.pauseAll = function() {
- for (var i=_s.soundIDs.length; i--;) {
+
+ var i;
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
_s.sounds[_s.soundIDs[i]].pause();
}
+
};
+ /**
+ * Calls the resume() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @return {SMSound} The SMSound object
+ */
+
this.resume = function(sID) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].resume();
+ return _s.sounds[sID].resume();
+
};
+ /**
+ * Resumes all currently-paused sounds.
+ */
+
this.resumeAll = function() {
- for (var i=_s.soundIDs.length; i--;) {
+
+ var i;
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
_s.sounds[_s.soundIDs[i]].resume();
}
+
};
+ /**
+ * Calls the togglePause() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @return {SMSound} The SMSound object
+ */
+
this.togglePause = function(sID) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].togglePause();
+ return _s.sounds[sID].togglePause();
+
};
+ /**
+ * Calls the setPan() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {number} nPan The pan value (-100 to 100)
+ * @return {SMSound} The SMSound object
+ */
+
this.setPan = function(sID, nPan) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].setPan(nPan);
+ return _s.sounds[sID].setPan(nPan);
+
};
+ /**
+ * Calls the setVolume() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @param {number} nVol The volume value (0 to 100)
+ * @return {SMSound} The SMSound object
+ */
+
this.setVolume = function(sID, nVol) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].setVolume(nVol);
+ return _s.sounds[sID].setVolume(nVol);
+
};
+ /**
+ * Calls the mute() method of either a single SMSound object by ID, or all sound objects.
+ *
+ * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.)
+ */
+
this.mute = function(sID) {
- var fN = 'soundManager.mute(): ';
- if (typeof sID != 'string') {
+
+ var i = 0;
+
+ if (typeof sID !== 'string') {
sID = null;
}
+
if (!sID) {
- _s._wD(fN+'Muting all sounds');
- for (var i=_s.soundIDs.length; i--;) {
+ _s._wD(_sm+'.mute(): Muting all sounds');
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
_s.sounds[_s.soundIDs[i]].mute();
}
_s.muted = true;
} else {
- if (!_s._idCheck(sID)) {
+ if (!_idCheck(sID)) {
return false;
}
- _s._wD(fN+'Muting "'+sID+'"');
- _s.sounds[sID].mute();
+ _s._wD(_sm+'.mute(): Muting "' + sID + '"');
+ return _s.sounds[sID].mute();
}
+
+ return true;
+
};
+ /**
+ * Mutes all sounds.
+ */
+
this.muteAll = function() {
+
_s.mute();
+
};
+ /**
+ * Calls the unmute() method of either a single SMSound object by ID, or all sound objects.
+ *
+ * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.)
+ */
+
this.unmute = function(sID) {
- var fN = 'soundManager.unmute(): ';
- if (typeof sID != 'string') {
+
+ var i;
+
+ if (typeof sID !== 'string') {
sID = null;
}
+
if (!sID) {
- _s._wD(fN+'Unmuting all sounds');
- for (var i=_s.soundIDs.length; i--;) {
+
+ _s._wD(_sm+'.unmute(): Unmuting all sounds');
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
_s.sounds[_s.soundIDs[i]].unmute();
}
_s.muted = false;
+
} else {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s._wD(fN+'Unmuting "'+sID+'"');
- _s.sounds[sID].unmute();
+ _s._wD(_sm+'.unmute(): Unmuting "' + sID + '"');
+ return _s.sounds[sID].unmute();
+
}
+
+ return true;
+
};
+ /**
+ * Unmutes all sounds.
+ */
+
this.unmuteAll = function() {
+
_s.unmute();
+
};
+ /**
+ * Calls the toggleMute() method of a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @return {SMSound} The SMSound object
+ */
+
this.toggleMute = function(sID) {
- if (!_s._idCheck(sID)) {
+
+ if (!_idCheck(sID)) {
return false;
}
- _s.sounds[sID].toggleMute();
+ return _s.sounds[sID].toggleMute();
+
};
+ /**
+ * Retrieves the memory used by the flash plugin.
+ *
+ * @return {number} The amount of memory in use
+ */
+
this.getMemoryUse = function() {
- if (_s.flashVersion == 8) {
- // not supported in Flash 8
- return 0;
- }
- if (_s.o) {
- return parseInt(_s.o._getMemoryUse(), 10);
+
+ // flash-only
+ var ram = 0;
+
+ if (_flash && _fV !== 8) {
+ ram = parseInt(_flash._getMemoryUse(), 10);
}
+
+ return ram;
+
};
+ /**
+ * Undocumented: NOPs soundManager and all SMSound objects.
+ */
+
this.disable = function(bNoDisable) {
+
// destroy all functions
- if (typeof bNoDisable == 'undefined') {
+ var i;
+
+ if (typeof bNoDisable === 'undefined') {
bNoDisable = false;
}
- if (_s._disabled) {
+
+ if (_disabled) {
return false;
}
- _s._disabled = true;
- _s._wDS('shutdown', 1);
- for (var i=_s.soundIDs.length; i--;) {
- _s._disableObject(_s.sounds[_s.soundIDs[i]]);
- }
- _s.initComplete(bNoDisable); // fire "complete", despite fail
- // _s._disableObject(_s); // taken out to allow reboot()
- };
- this.canPlayURL = function(sURL) {
- return (sURL?(sURL.match(_s.filePattern)?true:false):null);
- };
+ _disabled = true;
+ _wDS('shutdown', 1);
- this.getSoundById = function(sID, suppressDebug) {
- if (!sID) {
- throw new Error('SoundManager.getSoundById(): sID is null/undefined');
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
+ _disableObject(_s.sounds[_s.soundIDs[i]]);
}
- var result = _s.sounds[sID];
- if (!result && !suppressDebug) {
- _s._wD('"'+sID+'" is an invalid sound ID.', 2);
- // soundManager._wD('trace: '+arguments.callee.caller);
- }
- return result;
- };
- this.onready = function(oMethod, oScope) {
- // queue a callback, with optional scope
- // a status object will be passed to your handler
- /*
- soundManager.onready(function(oStatus) {
- alert('SM2 init success: '+oStatus.success);
- });
- */
- if (oMethod && oMethod instanceof Function) {
- if (_s._didInit) {
- _s._wDS('queue');
- }
- if (!oScope) {
- oScope = window;
- }
- _s._addOnReady(oMethod, oScope);
- _s._processOnReady();
- return true;
- } else {
- throw _s._str('needFunction');
- }
- };
+ // fire "complete", despite fail
+ _initComplete(bNoDisable);
+ _event.remove(_win, 'load', _initUserOnload);
- this.oninitmovie = function() {
- // called after SWF has been appended to the DOM via JS (or retrieved from HTML)
- // this is a stub for your own scripts.
- };
+ return true;
- this.onload = function() {
- // window.onload() equivalent for SM2, ready to create sounds etc.
- // this is a stub for your own scripts.
- soundManager._wD('soundManager.onload()', 1);
};
- this.onerror = function() {
- // stub for user handler, called when SM2 fails to load/init
- };
+ /**
+ * Determines playability of a MIME type, eg. 'audio/mp3'.
+ */
- // --- "private" methods ---
- this._idCheck = this.getSoundById;
+ this.canPlayMIME = function(sMIME) {
- this._complain = function(sMsg, oCaller) {
- // Try to create meaningful custom errors, w/stack trace to the "offending" line
- var sPre = 'Error: ';
- if (!oCaller) {
- return new Error(sPre+sMsg);
- }
- var e = new Error(''); // make a mistake.
- var stackMsg = null;
- if (e.stack) {
- // potentially dangerous: Try to return a meaningful stacktrace where provided (Mozilla)
- try {
- var splitChar = '@';
- var stackTmp = e.stack.split(splitChar);
- stackMsg = stackTmp[4]; // try to return only the relevant bit, skipping internal SM2 shiz
- } catch(ee) {
- // oops.
- stackMsg = e.stack;
- }
+ var result;
+
+ if (_s.hasHTML5) {
+ result = _html5CanPlay({type:sMIME});
}
- if (typeof console != 'undefined' && typeof console.trace != 'undefined') {
- console.trace();
+
+ if (!result && _needsFlash) {
+ // if flash 9, test netStream (movieStar) types as well.
+ result = (sMIME && _s.ok() ? !!((_fV > 8 ? sMIME.match(_netStreamMimeTypes) : null) || sMIME.match(_s.mimePattern)) : null);
}
- var errorDesc = sPre+sMsg+'. \nCaller: '+oCaller.toString()+(e.stack?' \nTop of stacktrace: '+stackMsg:(e.message?' \nMessage: '+e.message:''));
- // See JS error/debug/console output for real error source, stack trace / message detail where possible.
- return new Error(errorDesc);
- };
- var _doNothing = function() {
- return false;
+ return result;
+
};
- _doNothing._protected = true;
+ /**
+ * Determines playability of a URL based on audio support.
+ *
+ * @param {string} sURL The URL to test
+ * @return {boolean} URL playability
+ */
- this._disableObject = function(o) {
- for (var oProp in o) {
- if (typeof o[oProp] == 'function' && typeof o[oProp]._protected == 'undefined') {
- o[oProp] = _doNothing;
- }
- }
- oProp = null;
- };
+ this.canPlayURL = function(sURL) {
- this._failSafely = function(bNoDisable) {
- // general failure exception handler
- if (typeof bNoDisable == 'undefined') {
- bNoDisable = false;
+ var result;
+
+ if (_s.hasHTML5) {
+ result = _html5CanPlay({url: sURL});
}
- if (!_s._disabled || bNoDisable) {
- _s._wDS('smFail', 2);
- _s.disable(bNoDisable);
+
+ if (!result && _needsFlash) {
+ result = (sURL && _s.ok() ? !!(sURL.match(_s.filePattern)) : null);
}
+
+ return result;
+
};
- this._normalizeMovieURL = function(smURL) {
- var urlParams = null;
- if (smURL) {
- if (smURL.match(/\.swf(\?.*)?$/i)) {
- urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?')+4);
- if (urlParams) {
- return smURL; // assume user knows what they're doing
- }
- } else if (smURL.lastIndexOf('/') != smURL.length - 1) {
- smURL = smURL+'/';
+ /**
+ * Determines playability of an HTML DOM <a> object (or similar object literal) based on audio support.
+ *
+ * @param {object} oLink an HTML DOM <a> object or object literal including href and/or type attributes
+ * @return {boolean} URL playability
+ */
+
+ this.canPlayLink = function(oLink) {
+
+ if (typeof oLink.type !== 'undefined' && oLink.type) {
+ if (_s.canPlayMIME(oLink.type)) {
+ return true;
}
}
- return (smURL && smURL.lastIndexOf('/') != -1?smURL.substr(0, smURL.lastIndexOf('/')+1):'./')+_s.movieURL;
- };
- this._getDocument = function() {
- return (document.body?document.body:(document.documentElement?document.documentElement:document.getElementsByTagName('div')[0]));
+ return _s.canPlayURL(oLink.href);
+
};
- this._getDocument._protected = true;
+ /**
+ * Retrieves a SMSound object by ID.
+ *
+ * @param {string} sID The ID of the sound
+ * @return {SMSound} The SMSound object
+ */
- this._setPolling = function(bPolling, bHighPerformance) {
- if (!_s.o || !_s.allowPolling) {
- return false;
- }
- _s.o._setPolling(bPolling, bHighPerformance);
- };
+ this.getSoundById = function(sID, _suppressDebug) {
- this._createMovie = function(smID, smURL) {
- var specialCase = null;
- var remoteURL = (smURL?smURL:_s.url);
- var localURL = (_s.altURL?_s.altURL:remoteURL);
- if (_s.debugURLParam.test(window.location.href.toString())) {
- _s.debugMode = true; // allow force of debug mode via URL
- }
- if (_s._didAppend && _s._appendSuccess) {
- return false; // ignore if already succeeded
+ if (!sID) {
+ throw new Error(_sm+'.getSoundById(): sID is null/undefined');
}
- _s._didAppend = true;
- // safety check for legacy (change to Flash 9 URL)
- _s._setVersionInfo();
- _s.url = _s._normalizeMovieURL(_s._overHTTP?remoteURL:localURL);
- smURL = _s.url;
+ var result = _s.sounds[sID];
- if (_s.useHighPerformance && _s.useMovieStar && _s.defaultOptions.useVideo === true) {
- specialCase = 'soundManager note: disabling highPerformance, not applicable with movieStar mode+useVideo';
- _s.useHighPerformance = false;
+ // <d>
+ if (!result && !_suppressDebug) {
+ _s._wD('"' + sID + '" is an invalid sound ID.', 2);
}
+ // </d>
- _s.wmode = (!_s.wmode && _s.useHighPerformance && !_s.useMovieStar?'transparent':_s.wmode);
-
+ return result;
- if (_s.wmode !== null && _s.flashLoadTimeout !== 0 && (!_s.useHighPerformance || _s.debugFlash) && !_s.isIE && navigator.platform.match(/win32/i)) {
- _s.specialWmodeCase = true;
- // extra-special case: movie doesn't load until scrolled into view when using wmode = anything but 'window' here
- // does not apply when using high performance (position:fixed means on-screen), OR infinite flash load timeout
- _s._wDS('spcWmode');
- _s.wmode = null;
- }
+ };
- if (_s.flashVersion == 8) {
- _s.allowFullScreen = false;
- }
+ /**
+ * Queues a callback for execution when SoundManager has successfully initialized.
+ *
+ * @param {function} oMethod The callback method to fire
+ * @param {object} oScope Optional: The scope to apply to the callback
+ */
- var oEmbed = {
- name: smID,
- id: smID,
- src: smURL,
- width: '100%',
- height: '100%',
- quality: 'high',
- allowScriptAccess: _s.allowScriptAccess,
- bgcolor: _s.bgColor,
- pluginspage: 'http://www.macromedia.com/go/getflashplayer',
- type: 'application/x-shockwave-flash',
- wmode: _s.wmode,
- allowfullscreen: (_s.allowFullScreen?'true':'false')
- };
+ this.onready = function(oMethod, oScope) {
- if (_s.debugFlash) {
- oEmbed.FlashVars = 'debug=1';
- }
+ var sType = 'onready',
+ result = false;
- if (!_s.wmode) {
- delete oEmbed.wmode; // don't write empty attribute
- }
+ if (typeof oMethod === 'function') {
- var oMovie = null;
- var tmp = null;
- var movieHTML = null;
- var oEl = null;
+ // <d>
+ if (_didInit) {
+ _s._wD(_str('queue', sType));
+ }
+ // </d>
- if (_s.isIE) {
- // IE is "special".
- oMovie = document.createElement('div');
- movieHTML = '<object id="'+smID+'" data="'+smURL+'" type="'+oEmbed.type+'" width="'+oEmbed.width+'" height="'+oEmbed.height+'"><param name="movie" value="'+smURL+'" /><param name="AllowScriptAccess" value="'+_s.allowScriptAccess+'" /><param name="quality" value="'+oEmbed.quality+'" />'+(_s.wmode?'<param name="wmode" value="'+_s.wmode+'" /> ':'')+'<param name="bgcolor" value="'+_s.bgColor+'" /><param name="allowFullScreen" value="'+oEmbed.allowFullScreen+'" />'+(_s.debugFlash?'<param name="FlashVars" value="'+oEmbed.FlashVars+'" />':'')+'<!-- --></object>';
- } else {
- oMovie = document.createElement('embed');
- for (tmp in oEmbed) {
- if (oEmbed.hasOwnProperty(tmp)) {
- oMovie.setAttribute(tmp, oEmbed[tmp]);
- }
+ if (!oScope) {
+ oScope = _win;
}
- }
- var oD = null;
- var oToggle = null;
+ _addOnEvent(sType, oMethod, oScope);
+ _processOnEvents();
-if (_s.debugMode) {
+ result = true;
- oD = document.createElement('div');
- oD.id = _s.debugID+'-toggle';
- oToggle = {
- position: 'fixed',
- bottom: '0px',
- right: '0px',
- width: '1.2em',
- height: '1.2em',
- lineHeight: '1.2em',
- margin: '2px',
- textAlign: 'center',
- border: '1px solid #999',
- cursor: 'pointer',
- background: '#fff',
- color: '#333',
- zIndex: 10001
- };
+ } else {
- oD.appendChild(document.createTextNode('-'));
- oD.onclick = _s._toggleDebug;
- oD.title = 'Toggle SM2 debug console';
+ throw _str('needFunction', sType);
- if (navigator.userAgent.match(/msie 6/i)) {
- oD.style.position = 'absolute';
- oD.style.cursor = 'hand';
}
- for (tmp in oToggle) {
- if (oToggle.hasOwnProperty(tmp)) {
- oD.style[tmp] = oToggle[tmp];
- }
- }
+ return result;
-}
+ };
- var oTarget = _s._getDocument();
+ /**
+ * Queues a callback for execution when SoundManager has failed to initialize.
+ *
+ * @param {function} oMethod The callback method to fire
+ * @param {object} oScope Optional: The scope to apply to the callback
+ */
- if (oTarget) {
+ this.ontimeout = function(oMethod, oScope) {
- _s.oMC = _$('sm2-container')?_$('sm2-container'):document.createElement('div');
+ var sType = 'ontimeout',
+ result = false;
- var extraClass = (_s.debugMode?' sm2-debug':'')+(_s.debugFlash?' flash-debug':'');
+ if (typeof oMethod === 'function') {
- if (!_s.oMC.id) {
- _s.oMC.id = 'sm2-container';
- _s.oMC.className = 'movieContainer'+extraClass;
- // "hide" flash movie
- var s = null;
- oEl = null;
- if (_s.useHighPerformance) {
- s = {
- position: 'fixed',
- width: '8px',
- height: '8px',
- // must be at least 6px for flash to run fast. odd? yes.
- bottom: '0px',
- left: '0px',
- overflow: 'hidden'
- // zIndex:-1 // sit behind everything else - potentially dangerous/buggy?
- };
- } else {
- s = {
- position: 'absolute',
- width: '8px',
- height: '8px',
- top: '-9999px',
- left: '-9999px'
- };
- }
- var x = null;
- if (!_s.debugFlash) {
- for (x in s) {
- if (s.hasOwnProperty(x)) {
- _s.oMC.style[x] = s[x];
- }
- }
- }
- try {
- if (!_s.isIE) {
- _s.oMC.appendChild(oMovie);
- }
- oTarget.appendChild(_s.oMC);
- if (_s.isIE) {
- oEl = _s.oMC.appendChild(document.createElement('div'));
- oEl.className = 'sm2-object-box';
- oEl.innerHTML = movieHTML;
- }
- _s._appendSuccess = true;
- } catch(e) {
- throw new Error(_s._str('appXHTML'));
- }
- } else {
- // it's already in the document.
- if (_s.debugMode || _s.debugFlash) {
- _s.oMC.className += extraClass;
- }
- _s.oMC.appendChild(oMovie);
- if (_s.isIE) {
- oEl = _s.oMC.appendChild(document.createElement('div'));
- oEl.className = 'sm2-object-box';
- oEl.innerHTML = movieHTML;
- }
- _s._appendSuccess = true;
+ // <d>
+ if (_didInit) {
+ _s._wD(_str('queue', sType));
}
+ // </d>
- if (_s.debugMode && !_$(_s.debugID) && ((!_s._hasConsole || !_s.useConsole) || (_s.useConsole && _s._hasConsole && !_s.consoleOnly))) {
- var oDebug = document.createElement('div');
- oDebug.id = _s.debugID;
- oDebug.style.display = (_s.debugMode?'block':'none');
- if (_s.debugMode && !_$(oD.id)) {
- try {
- oTarget.appendChild(oD);
- } catch(e2) {
- throw new Error(_s._str('appXHTML'));
- }
- oTarget.appendChild(oDebug);
- }
+ if (!oScope) {
+ oScope = _win;
}
- oTarget = null;
- }
- if (specialCase) {
- _s._wD(specialCase);
+ _addOnEvent(sType, oMethod, oScope);
+ _processOnEvents({type:sType});
+
+ result = true;
+
+ } else {
+
+ throw _str('needFunction', sType);
+
}
- _s._wD('-- SoundManager 2 '+_s.version+(_s.useMovieStar?', MovieStar mode':'')+(_s.useHighPerformance?', high performance mode, ':', ')+((_s.useFastPolling?'fast':'normal')+' polling')+(_s.wmode?', wmode: '+_s.wmode:'')+(_s.debugFlash?', flash debug mode':'')+' --', 1);
- _s._wD('soundManager._createMovie(): Trying to load '+smURL+(!_s._overHTTP && _s.altURL?' (alternate URL)':''), 1);
+ return result;
+
};
- this._writeDebug = function(sText, sType, bTimestamp) { // aliased to this._wD()
+ /**
+ * Writes console.log()-style debug output to a console or in-browser element.
+ * Applies when debugMode = true
+ *
+ * @param {string} sText The console message
+ * @param {string} sType Optional: Log type of 'info', 'warn' or 'error'
+ * @param {object} Optional: The scope to apply to the callback
+ */
+
+ this._writeDebug = function(sText, sType, _bTimestamp) {
+
+ // pseudo-private console.log()-style output
+ // <d>
+
+ var sDID = 'soundmanager-debug', o, oItem, sMethod;
+
if (!_s.debugMode) {
return false;
}
- if (typeof bTimestamp != 'undefined' && bTimestamp) {
- sText = sText+' | '+new Date().getTime();
+
+ if (typeof _bTimestamp !== 'undefined' && _bTimestamp) {
+ sText = sText + ' | ' + new Date().getTime();
}
- if (_s._hasConsole && _s.useConsole) {
- var sMethod = _s._debugLevels[sType];
- if (typeof console[sMethod] != 'undefined') {
+
+ if (_hasConsole && _s.useConsole) {
+ sMethod = _debugLevels[sType];
+ if (typeof console[sMethod] !== 'undefined') {
console[sMethod](sText);
} else {
console.log(sText);
}
- if (_s.useConsoleOnly) {
+ if (_s.consoleOnly) {
return true;
}
}
- var sDID = 'soundmanager-debug';
- var o = null;
+
try {
- o = _$(sDID);
+
+ o = _id(sDID);
+
if (!o) {
return false;
}
- var oItem = document.createElement('div');
- if (++_s._wdCount % 2 === 0) {
+
+ oItem = _doc.createElement('div');
+
+ if (++_wdCount % 2 === 0) {
oItem.className = 'sm2-alt';
}
- // sText = sText.replace(/\n/g,'<br />');
- if (typeof sType == 'undefined') {
+
+ if (typeof sType === 'undefined') {
sType = 0;
} else {
sType = parseInt(sType, 10);
}
- oItem.appendChild(document.createTextNode(sText));
+
+ oItem.appendChild(_doc.createTextNode(sText));
+
if (sType) {
if (sType >= 2) {
oItem.style.fontWeight = 'bold';
}
- if (sType == 3) {
+ if (sType === 3) {
oItem.style.color = '#ff3333';
}
}
- // o.appendChild(oItem); // top-to-bottom
- o.insertBefore(oItem, o.firstChild); // bottom-to-top
+
+ // top-to-bottom
+ // o.appendChild(oItem);
+
+ // bottom-to-top
+ o.insertBefore(oItem, o.firstChild);
+
} catch(e) {
// oh well
}
+
o = null;
- };
- this._writeDebug._protected = true;
- this._wdCount = 0;
- this._wdCount._protected = true;
- this._wD = this._writeDebug;
+ // </d>
- this._wDS = function(o,errorLevel) {
- if (!o) {
- return '';
- } else {
- return _s._wD(_s._str(o),errorLevel);
- }
- };
- this._wDS._protected = true;
+ return true;
- this._wDAlert = function(sText) {
- alert(sText);
};
- if (window.location.href.indexOf('debug=alert')+1 && _s.debugMode) {
- _s._wD = _s._wDAlert;
- }
-
- this._toggleDebug = function() {
- var o = _$(_s.debugID);
- var oT = _$(_s.debugID+'-toggle');
- if (!o) {
- return false;
- }
- if (_s._debugOpen) {
- // minimize
- oT.innerHTML = '+';
- o.style.display = 'none';
- } else {
- oT.innerHTML = '-';
- o.style.display = 'block';
- }
- _s._debugOpen = !_s._debugOpen;
- };
+ // alias
+ this._wD = this._writeDebug;
- this._toggleDebug._protected = true;
+ /**
+ * Provides debug / state information on all SMSound objects.
+ */
this._debug = function() {
- _s._wDS('currentObj', 1);
- for (var i=0, j = _s.soundIDs.length; i<j; i++) {
+
+ // <d>
+ var i, j;
+ _wDS('currentObj', 1);
+
+ for (i = 0, j = _s.soundIDs.length; i < j; i++) {
_s.sounds[_s.soundIDs[i]]._debug();
}
- };
+ // </d>
- this._debugTS = function(sEventType, bSuccess, sMessage) {
- // troubleshooter debug hooks
- if (typeof sm2Debugger != 'undefined') {
- try {
- sm2Debugger.handleEvent(sEventType, bSuccess, sMessage);
- } catch(e) {
- // oh well
- }
- }
};
- this._debugTS._protected = true;
+ /**
+ * Restarts and re-initializes the SoundManager instance.
+ */
- this._mergeObjects = function(oMain, oAdd) {
- // non-destructive merge
- var o1 = {}; // clone o1
- for (var i in oMain) {
- if (oMain.hasOwnProperty(i)) {
- o1[i] = oMain[i];
- }
- }
- var o2 = (typeof oAdd == 'undefined'?_s.defaultOptions:oAdd);
- for (var o in o2) {
- if (o2.hasOwnProperty(o) && typeof o1[o] == 'undefined') {
- o1[o] = o2[o];
- }
- }
- return o1;
- };
+ this.reboot = function() {
+
+ // attempt to reset and init SM2
+ _s._wD(_sm+'.reboot()');
- this.createMovie = function(sURL) {
- if (sURL) {
- _s.url = sURL;
+ // <d>
+ if (_s.soundIDs.length) {
+ _s._wD('Destroying ' + _s.soundIDs.length + ' SMSound objects...');
}
- _s._initMovie();
- };
+ // </d>
- this.go = this.createMovie; // nice alias
+ var i, j;
- this._initMovie = function() {
- // attempt to get, or create, movie
- if (_s.o) {
- return false; // may already exist
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
+ _s.sounds[_s.soundIDs[i]].destruct();
}
- _s.o = _s.getMovie(_s.id); // (inline markup)
- if (!_s.o) {
- if (!_s.oRemoved) {
- // try to create
- _s._createMovie(_s.id, _s.url);
- } else {
- // try to re-append removed movie after reboot()
- if (!_s.isIE) {
- _s.oMC.appendChild(_s.oRemoved);
- } else {
- _s.oMC.innerHTML = _s.oRemovedHTML;
+
+ // trash ze flash
+
+ if (_flash) {
+ try {
+ if (_isIE) {
+ _oRemovedHTML = _flash.innerHTML;
}
- _s.oRemoved = null;
- _s._didAppend = true;
- }
- _s.o = _s.getMovie(_s.id);
- }
- if (_s.o) {
- // _s._wD('soundManager._initMovie(): Got '+_s.o.nodeName+' element ('+(_s._didAppend?'created via JS':'static HTML')+')',1);
- if (_s.flashLoadTimeout > 0) {
- _s._wDS('waitEI');
+ _oRemoved = _flash.parentNode.removeChild(_flash);
+ _s._wD('Flash movie removed.');
+ } catch(e) {
+ // uh-oh.
+ _wDS('badRemove', 2);
}
}
- if (typeof _s.oninitmovie == 'function') {
- setTimeout(_s.oninitmovie, 1);
- }
- };
- this.waitForExternalInterface = function() {
- if (_s._waitingForEI) {
- return false;
- }
- _s._waitingForEI = true;
- if (_s._tryInitOnFocus && !_s._isFocused) {
- _s._wDS('waitFocus');
- return false;
- }
- if (_s.flashLoadTimeout > 0) {
- if (!_s._didInit) {
- var p = _s.getMoviePercent();
- _s._wD(_s._str('waitImpatient',(p == 100?' (SWF loaded)':(p > 0?' (SWF '+p+'% loaded)':''))));
- }
- setTimeout(function() {
- var p = _s.getMoviePercent();
- if (!_s._didInit) {
- _s._wD(_sm+': No Flash response within reasonable time after document load.\nLikely causes: '+(p === null || p === 0?'Loading '+_s.movieURL+' may have failed (and/or Flash '+_s.flashVersion+'+ not present?), ':'')+'Flash blocked or JS-Flash security error.'+(_s.debugFlash?' '+_s._str('checkSWF'): ''), 2);
- if (!_s._overHTTP) {
- _s._wDS('localFail', 2);
- if (!_s.debugFlash) {
- _s._wDS('tryDebug', 2);
- }
- }
- if (p === 0) {
- // 404, or blocked from loading?
- _s._wD(_s._str('swf404',_s.url));
- }
- _s._debugTS('flashtojs', false, ': Timed out'+(_s._overHTTP)?' (Check flash security or flash blockers)':' (No plugin/missing SWF?)');
- }
- // if still not initialized and no other options, give up
- if (!_s._didInit && _s._okToDisable) {
- _s._failSafely(true); // don't disable, for reboot()
+ // actually, force recreate of movie.
+ _oRemovedHTML = _oRemoved = _needsFlash = null;
+
+ _s.enabled = _didDCLoaded = _didInit = _waitingForEI = _initPending = _didAppend = _appendSuccess = _disabled = _s.swfLoaded = false;
+ _s.soundIDs = [];
+ _s.sounds = {};
+ _flash = null;
+
+ for (i in _on_queue) {
+ if (_on_queue.hasOwnProperty(i)) {
+ for (j = _on_queue[i].length-1; j >= 0; j--) {
+ _on_queue[i][j].fired = false;
}
- },
- _s.flashLoadTimeout);
- } else if (!_s._didInit) {
- _s._wDS('waitForever');
+ }
}
+
+ _s._wD(_sm + ': Rebooting...');
+ _win.setTimeout(_s.beginDelayedInit, 20);
+
};
+ /**
+ * Undocumented: Determines the SM2 flash movie's load progress.
+ *
+ * @return {number or null} Percent loaded, or if invalid/unsupported, null.
+ */
+
this.getMoviePercent = function() {
- return (_s.o && typeof _s.o.PercentLoaded != 'undefined'?_s.o.PercentLoaded():null);
+
+ // interesting note: flash/ExternalInterface bridge methods are not typeof "function" nor instanceof Function, but are still valid.
+ return (_flash && typeof _flash.PercentLoaded !== 'undefined' ? _flash.PercentLoaded() : null);
+
};
- this.handleFocus = function() {
- if (_s._isFocused || !_s._tryInitOnFocus) {
- return true;
- }
- _s._okToDisable = true;
- _s._isFocused = true;
- _s._wD('soundManager.handleFocus()');
- if (_s._tryInitOnFocus) {
- // giant Safari 3.1 hack - assume window in focus if mouse is moving, since document.hasFocus() not currently implemented.
- window.removeEventListener('mousemove', _s.handleFocus, false);
- }
- // allow init to restart
- _s._waitingForEI = false;
- setTimeout(_s.waitForExternalInterface, 500);
- // detach event
- if (window.removeEventListener) {
- window.removeEventListener('focus', _s.handleFocus, false);
- } else if (window.detachEvent) {
- window.detachEvent('onfocus', _s.handleFocus);
- }
- };
+ /**
+ * Additional helper for manually invoking SM2's init process after DOM Ready / window.onload().
+ */
- this.initComplete = function(bNoDisable) {
- if (_s._didInit) {
- return false;
- }
- _s._didInit = true;
- _s._wD('-- SoundManager 2 '+(_s._disabled?'failed to load':'loaded')+' ('+(_s._disabled?'security/load error':'OK')+') --', 1);
- if (_s._disabled || bNoDisable) {
- // _s._wD('soundManager.initComplete(): calling soundManager.onerror()',1);
- _s._processOnReady();
- _s._debugTS('onload', false);
- _s.onerror.apply(window);
- return false;
- } else {
- _s._debugTS('onload', true);
- }
- if (_s.waitForWindowLoad && !_s._windowLoaded) {
- _s._wDS('waitOnload');
- if (window.addEventListener) {
- window.addEventListener('load', _s._initUserOnload, false);
- } else if (window.attachEvent) {
- window.attachEvent('onload', _s._initUserOnload);
- }
- return false;
- } else {
- if (_s.waitForWindowLoad && _s._windowLoaded) {
- _s._wDS('docLoaded');
- }
- _s._initUserOnload();
- }
- };
+ this.beginDelayedInit = function() {
- this._addOnReady = function(oMethod, oScope) {
- _s._onready.push({
- 'method': oMethod,
- 'scope': (oScope || null),
- 'fired': false
- });
- };
+ _windowLoaded = true;
+ _domContentLoaded();
- this._processOnReady = function() {
- if (!_s._didInit) {
- // not ready yet.
- return false;
- }
- var status = {
- success: (!_s._disabled)
- };
- var queue = [];
- for (var i=0, j = _s._onready.length; i<j; i++) {
- if (_s._onready[i].fired !== true) {
- queue.push(_s._onready[i]);
- }
- }
- if (queue.length) {
- _s._wD(_sm+': Firing '+queue.length+' onready() item'+(queue.length > 1?'s':''));
- for (i = 0, j = queue.length; i<j; i++) {
- if (queue[i].scope) {
- queue[i].method.apply(queue[i].scope, [status]);
- } else {
- queue[i].method(status);
- }
- queue[i].fired = true;
+ setTimeout(function() {
+
+ if (_initPending) {
+ return false;
}
- }
- };
- this._initUserOnload = function() {
- window.setTimeout(function() {
- _s._processOnReady();
- _s._wDS('onload', 1);
- // call user-defined "onload", scoped to window
- _s.onload.apply(window);
- _s._wDS('onloadOK', 1);
- });
- };
+ _createMovie();
+ _initMovie();
+ _initPending = true;
- this.init = function() {
- _s._wDS('init');
- // called after onload()
- _s._initMovie();
- if (_s._didInit) {
- _s._wDS('didInit');
- return false;
- }
- // event cleanup
- if (window.removeEventListener) {
- window.removeEventListener('load', _s.beginDelayedInit, false);
- } else if (window.detachEvent) {
- window.detachEvent('onload', _s.beginDelayedInit);
- }
- try {
- _s._wDS('flashJS');
- _s.o._externalInterfaceTest(false); // attempt to talk to Flash
- if (!_s.allowPolling) {
- _s._wDS('noPolling', 1);
- } else {
- _s._setPolling(true, _s.useFastPolling?true:false);
- }
- if (!_s.debugMode) {
- _s.o._disableDebug();
- }
- _s.enabled = true;
- _s._debugTS('jstoflash', true);
- } catch(e) {
- _s._wD('js/flash exception: '+e.toString());
- _s._debugTS('jstoflash', false);
- _s._failSafely(true); // don't disable, for reboot()
- _s.initComplete();
- return false;
- }
- _s.initComplete();
- };
+ return true;
- this.beginDelayedInit = function() {
- // _s._wD('soundManager.beginDelayedInit()');
- _s._windowLoaded = true;
- setTimeout(_s.waitForExternalInterface, 500);
- setTimeout(_s.beginInit, 20);
- };
+ }, 20);
- this.beginInit = function() {
- if (_s._initPending) {
- return false;
- }
- _s.createMovie(); // ensure creation if not already done
- _s._initMovie();
- _s._initPending = true;
- return true;
- };
+ _delayWaitForEI();
- this.domContentLoaded = function() {
- if (document.removeEventListener) {
- document.removeEventListener('DOMContentLoaded', _s.domContentLoaded, false);
- }
- _s.go();
};
- this._externalInterfaceOK = function(flashDate) {
- // callback from flash for confirming that movie loaded, EI is working etc.
- // flashDate = approx. timing/delay info for JS/flash bridge
- if (_s.swfLoaded) {
- return false;
- }
- var eiTime = new Date().getTime();
- _s._wD('soundManager._externalInterfaceOK()'+(flashDate?' (~'+(eiTime - flashDate)+' ms)':''));
- _s._debugTS('swf', true);
- _s._debugTS('flashtojs', true);
- _s.swfLoaded = true;
- _s._tryInitOnFocus = false;
+ /**
+ * Destroys the SoundManager instance and all SMSound instances.
+ */
- if (_s.isIE) {
- // IE needs a timeout OR delay until window.onload - may need TODO: investigating
- setTimeout(_s.init, 100);
- } else {
- _s.init();
- }
+ this.destruct = function() {
- };
+ _s._wD(_sm+'.destruct()');
+ _s.disable(true);
- this._setSandboxType = function(sandboxType) {
- var sb = _s.sandbox;
- sb.type = sandboxType;
- sb.description = sb.types[(typeof sb.types[sandboxType] != 'undefined'?sandboxType:'unknown')];
- _s._wD('Flash security sandbox type: '+sb.type);
- if (sb.type == 'localWithFile') {
- sb.noRemote = true;
- sb.noLocal = false;
- _s._wDS('secNote', 2);
- } else if (sb.type == 'localWithNetwork') {
- sb.noRemote = false;
- sb.noLocal = true;
- } else if (sb.type == 'localTrusted') {
- sb.noRemote = false;
- sb.noLocal = false;
- }
};
- this.reboot = function() {
- // attempt to reset and init SM2
- _s._wD('soundManager.reboot()');
- if (_s.soundIDs.length) {
- _s._wD('Destroying '+_s.soundIDs.length+' SMSound objects...');
- }
- for (var i=_s.soundIDs.length; i--;) {
- _s.sounds[_s.soundIDs[i]].destruct();
- }
- // trash ze flash
- try {
- if (_s.isIE) {
- _s.oRemovedHTML = _s.o.innerHTML;
- }
- _s.oRemoved = _s.o.parentNode.removeChild(_s.o);
- _s._wD('Flash movie removed.');
- } catch(e) {
- // uh-oh.
- _s._wDS('badRemove', 2);
- }
+ /**
+ * SMSound() (sound object) constructor
+ * ------------------------------------
+ *
+ * @param {object} oOptions Sound options (id and url are required attributes)
+ * @return {SMSound} The new SMSound object
+ */
- // actually, force recreate of movie.
- _s.oRemovedHTML = null;
- _s.oRemoved = null;
-
- _s.enabled = false;
- _s._didInit = false;
- _s._waitingForEI = false;
- _s._initPending = false;
- _s._didAppend = false;
- _s._appendSuccess = false;
- _s._disabled = false;
- _s._waitingforEI = true;
- _s.swfLoaded = false;
- _s.soundIDs = {};
- _s.sounds = [];
- _s.o = null;
- for (i = _s._onready.length; i--;) {
- _s._onready[i].fired = false;
- }
- _s._wD(_sm+': Rebooting...');
- window.setTimeout(soundManager.beginDelayedInit, 20);
- };
+ SMSound = function(oOptions) {
- this.destruct = function() {
- _s._wD('soundManager.destruct()');
- _s.disable(true);
- };
+ var _t = this, _resetProperties, _add_html5_events, _remove_html5_events, _stop_html5_timer, _start_html5_timer, _attachOnPosition, _onplay_called = false, _onPositionItems = [], _onPositionFired = 0, _detachOnPosition, _applyFromTo, _lastURL = null, _lastHTML5State;
+
+ _lastHTML5State = {
+ // tracks duration + position (time)
+ duration: null,
+ time: null
+ };
+
+ this.id = oOptions.id;
+
+ // legacy
+ this.sID = this.id;
- // SMSound (sound object)
- SMSound = function(oOptions) {
- var _t = this;
- this.sID = oOptions.id;
this.url = oOptions.url;
- this.options = _s._mergeObjects(oOptions);
- this.instanceOptions = this.options; // per-play-instance-specific options
- this._iO = this.instanceOptions; // short alias
- // assign property defaults (volume, pan etc.)
+ this.options = _mixin(oOptions);
+
+ // per-play-instance-specific options
+ this.instanceOptions = this.options;
+
+ // short alias
+ this._iO = this.instanceOptions;
+
+ // assign property defaults
this.pan = this.options.pan;
this.volume = this.options.volume;
- this._lastURL = null;
+ // whether or not this object is using HTML5
+ this.isHTML5 = false;
+
+ // internal HTML5 Audio() object reference
+ this._a = null;
+
+ /**
+ * SMSound() public methods
+ * ------------------------
+ */
+
+ this.id3 = {};
+
+ /**
+ * Writes SMSound object parameters to debug console
+ */
this._debug = function() {
+
+ // <d>
+ // pseudo-private console.log()-style output
+
if (_s.debugMode) {
- var stuff = null;
- var msg = [];
- var sF = null;
- var sfBracket = null;
- var maxLength = 64; // # of characters of function code to show before truncating
+
+ var stuff = null, msg = [], sF, sfBracket, maxLength = 64;
+
for (stuff in _t.options) {
if (_t.options[stuff] !== null) {
- if (_t.options[stuff] instanceof Function) {
+ if (typeof _t.options[stuff] === 'function') {
// handle functions specially
sF = _t.options[stuff].toString();
- sF = sF.replace(/\s\s+/g, ' '); // normalize spaces
+ // normalize spaces
+ sF = sF.replace(/\s\s+/g, ' ');
sfBracket = sF.indexOf('{');
- msg[msg.length] = ' '+stuff+': {'+sF.substr(sfBracket+1, (Math.min(Math.max(sF.indexOf('\n') - 1, maxLength), maxLength))).replace(/\n/g, '')+'... }';
+ msg.push(' ' + stuff + ': {' + sF.substr(sfBracket + 1, (Math.min(Math.max(sF.indexOf('\n') - 1, maxLength), maxLength))).replace(/\n/g, '') + '... }');
} else {
- msg[msg.length] = ' '+stuff+': '+_t.options[stuff];
+ msg.push(' ' + stuff + ': ' + _t.options[stuff]);
}
}
}
- _s._wD('SMSound() merged options: {\n'+msg.join(', \n')+'\n}');
+
+ _s._wD('SMSound() merged options: {\n' + msg.join(', \n') + '\n}');
+
}
+ // </d>
+
};
+ // <d>
this._debug();
+ // </d>
- this.id3 = {
- /*
- Name/value pairs set via Flash when available - see reference for names (download documentation):
- http://livedocs.macromedia.com/flash/8/
- Previously-live URL:
- http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001567.html
- (eg., this.id3.songname or this.id3['songname'])
- */
- };
+ /**
+ * Begins loading a sound per its *url*.
+ *
+ * @param {object} oOptions Optional: Sound options
+ * @return {SMSound} The SMSound object
+ */
- this.resetProperties = function(bLoaded) {
- _t.bytesLoaded = null;
- _t.bytesTotal = null;
- _t.position = null;
- _t.duration = null;
- _t.durationEstimate = null;
- _t.loaded = false;
- _t.playState = 0;
- _t.paused = false;
- _t.readyState = 0; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success
- _t.muted = false;
- _t.didBeforeFinish = false;
- _t.didJustBeforeFinish = false;
- _t.isBuffering = false;
- _t.instanceOptions = {};
- _t.instanceCount = 0;
- _t.peakData = {
- left: 0,
- right: 0
- };
- _t.waveformData = {
- left: [],
- right: []
- };
- _t.eqData = [];
- // dirty hack for now: also have left/right arrays off this, maintain compatibility
- _t.eqData.left = [];
- _t.eqData.right = [];
- };
+ this.load = function(oOptions) {
- _t.resetProperties();
+ var oS = null, _iO;
- // --- public methods ---
- this.load = function(oOptions) {
- if (typeof oOptions != 'undefined') {
- _t._iO = _s._mergeObjects(oOptions);
+ if (typeof oOptions !== 'undefined') {
+ _t._iO = _mixin(oOptions, _t.options);
_t.instanceOptions = _t._iO;
} else {
oOptions = _t.options;
_t._iO = oOptions;
_t.instanceOptions = _t._iO;
- if (_t._lastURL && _t._lastURL != _t.url) {
- _s._wDS('manURL');
+ if (_lastURL && _lastURL !== _t.url) {
+ _wDS('manURL');
_t._iO.url = _t.url;
_t.url = null;
}
}
- if (typeof _t._iO.url == 'undefined') {
+ if (!_t._iO.url) {
_t._iO.url = _t.url;
}
- _s._wD('soundManager.load(): '+_t._iO.url, 1);
- if (_t._iO.url == _t.url && _t.readyState !== 0 && _t.readyState != 2) {
- _s._wDS('onURL', 1);
- return false;
+ _t._iO.url = _parseURL(_t._iO.url);
+
+ _s._wD('SMSound.load(): ' + _t._iO.url, 1);
+
+ if (_t._iO.url === _t.url && _t.readyState !== 0 && _t.readyState !== 2) {
+ _wDS('onURL', 1);
+ // if loaded and an onload() exists, fire immediately.
+ if (_t.readyState === 3 && _t._iO.onload) {
+ // assume success based on truthy duration.
+ _t._iO.onload.apply(_t, [(!!_t.duration)]);
+ }
+ return _t;
}
- _t.url = _t._iO.url;
- _t._lastURL = _t._iO.url;
+
+ // local shortcut
+ _iO = _t._iO;
+
+ _lastURL = _t.url;
+
+ // reset a few state properties
+
_t.loaded = false;
_t.readyState = 1;
- _t.playState = 0; // (oOptions.autoPlay?1:0); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)
- try {
- if (_s.flashVersion == 8) {
- _s.o._load(_t.sID, _t._iO.url, _t._iO.stream, _t._iO.autoPlay, (_t._iO.whileloading?1:0));
+ _t.playState = 0;
+ _t.id3 = {};
+
+ // TODO: If switching from HTML5 -> flash (or vice versa), stop currently-playing audio.
+
+ if (_html5OK(_iO)) {
+
+ oS = _t._setup_html5(_iO);
+
+ if (!oS._called_load) {
+
+ _s._wD(_h5+'load: '+_t.id);
+
+ _t._html5_canplay = false;
+
+ // TODO: review called_load / html5_canplay logic
+
+ // if url provided directly to load(), assign it here.
+
+ if (_t._a.src !== _iO.url) {
+
+ _s._wD(_wDS('manURL') + ': ' + _iO.url);
+
+ _t._a.src = _iO.url;
+
+ // TODO: review / re-apply all relevant options (volume, loop, onposition etc.)
+
+ // reset position for new URL
+ _t.setPosition(0);
+
+ }
+
+ // given explicit load call, try to preload.
+
+ // early HTML5 implementation (non-standard)
+ _t._a.autobuffer = 'auto';
+
+ // standard
+ _t._a.preload = 'auto';
+
+ oS._called_load = true;
+
+ if (_iO.autoPlay) {
+ _t.play();
+ }
+
} else {
- _s.o._load(_t.sID, _t._iO.url, _t._iO.stream?true:false, _t._iO.autoPlay?true:false); // ,(_tO.whileloading?true:false)
- if (_t._iO.isMovieStar && _t._iO.autoLoad && !_t._iO.autoPlay) {
- // special case: MPEG4 content must start playing to load, then pause to prevent playing.
- _t.pause();
+
+ _s._wD(_h5+'ignoring request to load again: '+_t.id);
+
+ }
+
+ } else {
+
+ try {
+ _t.isHTML5 = false;
+ _t._iO = _policyFix(_loopFix(_iO));
+ // re-assign local shortcut
+ _iO = _t._iO;
+ if (_fV === 8) {
+ _flash._load(_t.id, _iO.url, _iO.stream, _iO.autoPlay, (_iO.whileloading?1:0), _iO.loops||1, _iO.usePolicyFile);
+ } else {
+ _flash._load(_t.id, _iO.url, !!(_iO.stream), !!(_iO.autoPlay), _iO.loops||1, !!(_iO.autoLoad), _iO.usePolicyFile);
}
+ } catch(e) {
+ _wDS('smError', 2);
+ _debugTS('onload', false);
+ _catchError({type:'SMSOUND_LOAD_JS_EXCEPTION', fatal:true});
+
}
- } catch(e) {
- _s._wDS('smError', 2);
- _s._debugTS('onload', false);
- _s.onerror();
- _s.disable();
+
}
+ return _t;
+
};
-
- this.loadfailed = function() {
- if (_t._iO.onloadfailed) {
- _s._wD('SMSound.onloadfailed(): "'+_t.sID+'"');
- _t._iO.onloadfailed.apply(_t);
- }
- };
+
+ /**
+ * Unloads a sound, canceling any open HTTP requests.
+ *
+ * @return {SMSound} The SMSound object
+ */
this.unload = function() {
- // Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3
+
+ // Flash 8/AS2 can't "close" a stream - fake it by loading an empty URL
// Flash 9/AS3: Close stream, preventing further load
+ // HTML5: Most UAs will use empty URL
+
if (_t.readyState !== 0) {
- _s._wD('SMSound.unload(): "'+_t.sID+'"');
- if (_t.readyState != 2) { // reset if not error
- _t.setPosition(0, true); // reset current sound positioning
+
+ _s._wD('SMSound.unload(): "' + _t.id + '"');
+
+ if (!_t.isHTML5) {
+
+ if (_fV === 8) {
+ _flash._unload(_t.id, _emptyURL);
+ } else {
+ _flash._unload(_t.id);
+ }
+
+ } else {
+
+ _stop_html5_timer();
+
+ if (_t._a) {
+
+ _t._a.pause();
+ _html5Unload(_t._a, _emptyURL);
+
+ // reset local URL for next load / play call, too
+ _t.url = _emptyURL;
+
+ }
+
}
- _s.o._unload(_t.sID, _s.nullURL);
+
// reset load/status flags
- _t.resetProperties();
+ _resetProperties();
+
}
+
+ return _t;
+
};
- this.destruct = function() {
- // kill sound within Flash
- _s._wD('SMSound.destruct(): "'+_t.sID+'"');
- _s.o._destroySound(_t.sID);
- _s.destroySound(_t.sID, true); // ensure deletion from controller
+ /**
+ * Unloads and destroys a sound.
+ */
+
+ this.destruct = function(_bFromSM) {
+
+ _s._wD('SMSound.destruct(): "' + _t.id + '"');
+
+ if (!_t.isHTML5) {
+
+ // kill sound within Flash
+ // Disable the onfailure handler
+ _t._iO.onfailure = null;
+ _flash._destroySound(_t.id);
+
+ } else {
+
+ _stop_html5_timer();
+
+ if (_t._a) {
+ _t._a.pause();
+ _html5Unload(_t._a);
+ if (!_useGlobalHTML5Audio) {
+ _remove_html5_events();
+ }
+ // break obvious circular reference
+ _t._a._t = null;
+ _t._a = null;
+ }
+
+ }
+
+ if (!_bFromSM) {
+ // ensure deletion from controller
+ _s.destroySound(_t.id, true);
+
+ }
+
};
- this.play = function(oOptions) {
- var fN = 'SMSound.play(): ';
+ /**
+ * Begins playing a sound.
+ *
+ * @param {object} oOptions Optional: Sound options
+ * @return {SMSound} The SMSound object
+ */
+
+ this.play = function(oOptions, _updatePlayState) {
+
+ var fN, allowMulti, a, onready, startOK = true,
+ exit = null;
+
+ // <d>
+ fN = 'SMSound.play(): ';
+ // </d>
+
+ // default to true
+ _updatePlayState = (typeof _updatePlayState === 'undefined' ? true : _updatePlayState);
+
if (!oOptions) {
oOptions = {};
}
- _t._iO = _s._mergeObjects(oOptions, _t._iO);
- _t._iO = _s._mergeObjects(_t._iO, _t.options);
+
+ _t._iO = _mixin(oOptions, _t._iO);
+ _t._iO = _mixin(_t._iO, _t.options);
+ _t._iO.url = _parseURL(_t._iO.url);
_t.instanceOptions = _t._iO;
- if (_t.playState == 1) {
- var allowMulti = _t._iO.multiShot;
+
+ // RTMP-only
+ if (_t._iO.serverURL && !_t.connected) {
+ if (!_t.getAutoPlay()) {
+ _s._wD(fN+' Netstream not connected yet - setting autoPlay');
+ _t.setAutoPlay(true);
+ }
+ // play will be called in _onconnect()
+ return _t;
+ }
+
+ if (_html5OK(_t._iO)) {
+ _t._setup_html5(_t._iO);
+ _start_html5_timer();
+ }
+
+ if (_t.playState === 1 && !_t.paused) {
+ allowMulti = _t._iO.multiShot;
if (!allowMulti) {
- _s._wD(fN+'"'+_t.sID+'" already playing (one-shot)', 1);
- return false;
+ _s._wD(fN + '"' + _t.id + '" already playing (one-shot)', 1);
+ exit = _t;
} else {
- _s._wD(fN+'"'+_t.sID+'" already playing (multi-shot)', 1);
+ _s._wD(fN + '"' + _t.id + '" already playing (multi-shot)', 1);
}
}
+
+ if (exit !== null) {
+ return exit;
+ }
+
if (!_t.loaded) {
+
if (_t.readyState === 0) {
- _s._wD(fN+'Attempting to load "'+_t.sID+'"', 1);
+
+ _s._wD(fN + 'Attempting to load "' + _t.id + '"', 1);
+
// try to get this sound playing ASAP
- //_t._iO.stream = true; // breaks stream=false case?
- _t._iO.autoPlay = true;
- // TODO: need to investigate when false, double-playing
- // if (typeof oOptions.autoPlay=='undefined') _tO.autoPlay = true; // only set autoPlay if unspecified here
- _t.load(_t._iO); // try to get this sound playing ASAP
- } else if (_t.readyState == 2) {
- _s._wD(fN+'Could not load "'+_t.sID+'" - exiting', 2);
- return false;
+ if (!_t.isHTML5) {
+ // assign directly because setAutoPlay() increments the instanceCount
+ _t._iO.autoPlay = true;
+ _t.load(_t._iO);
+ } else {
+ // iOS needs this when recycling sounds, loading a new URL on an existing object.
+ _t.load(_t._iO);
+ }
+
+ } else if (_t.readyState === 2) {
+
+ _s._wD(fN + 'Could not load "' + _t.id + '" - exiting', 2);
+ exit = _t;
+
} else {
- _s._wD(fN+'"'+_t.sID+'" is loading - attempting to play..', 1);
+
+ _s._wD(fN + '"' + _t.id + '" is loading - attempting to play..', 1);
+
}
+
} else {
- _s._wD(fN+'"'+_t.sID+'"');
+
+ _s._wD(fN + '"' + _t.id + '"');
+
}
- if (_t.paused) {
- _t.resume();
+
+ if (exit !== null) {
+ return exit;
+ }
+
+ if (!_t.isHTML5 && _fV === 9 && _t.position > 0 && _t.position === _t.duration) {
+ // flash 9 needs a position reset if play() is called while at the end of a sound.
+ _s._wD(fN + '"' + _t.id + '": Sound at end, resetting to position:0');
+ oOptions.position = 0;
+ }
+
+ /**
+ * Streams will pause when their buffer is full if they are being loaded.
+ * In this case paused is true, but the song hasn't started playing yet.
+ * If we just call resume() the onplay() callback will never be called.
+ * So only call resume() if the position is > 0.
+ * Another reason is because options like volume won't have been applied yet.
+ */
+
+ if (_t.paused && _t.position && _t.position > 0) {
+
+ // https://gist.github.com/37b17df75cc4d7a90bf6
+ _s._wD(fN + '"' + _t.id + '" is resuming from paused state',1);
+ _t.resume();
+
} else {
- _t.playState = 1;
- if (!_t.instanceCount || _s.flashVersion > 8) {
+
+ _t._iO = _mixin(oOptions, _t._iO);
+
+ // apply from/to parameters, if they exist (and not using RTMP)
+ if (_t._iO.from !== null && _t._iO.to !== null && _t.instanceCount === 0 && _t.playState === 0 && !_t._iO.serverURL) {
+
+ onready = function() {
+ // sound "canplay" or onload()
+ // re-apply from/to to instance options, and start playback
+ _t._iO = _mixin(oOptions, _t._iO);
+ _t.play(_t._iO);
+ };
+
+ // HTML5 needs to at least have "canplay" fired before seeking.
+ if (_t.isHTML5 && !_t._html5_canplay) {
+
+ // this hasn't been loaded yet. load it first, and then do this again.
+ _s._wD(fN+'Beginning load of "'+ _t.id+'" for from/to case');
+
+ _t.load({
+ _oncanplay: onready
+ });
+
+ exit = false;
+
+ } else if (!_t.isHTML5 && !_t.loaded && (!_t.readyState || _t.readyState !== 2)) {
+
+ // to be safe, preload the whole thing in Flash.
+
+ _s._wD(fN+'Preloading "'+ _t.id+'" for from/to case');
+
+ _t.load({
+ onload: onready
+ });
+
+ exit = false;
+
+ }
+
+ if (exit !== null) {
+ return exit;
+ }
+
+ // otherwise, we're ready to go. re-apply local options, and continue
+
+ _t._iO = _applyFromTo();
+
+ }
+
+ _s._wD(fN+'"'+ _t.id+'" is starting to play');
+
+ if (!_t.instanceCount || _t._iO.multiShotEvents || (!_t.isHTML5 && _fV > 8 && !_t.getAutoPlay())) {
_t.instanceCount++;
}
- _t.position = (typeof _t._iO.position != 'undefined' && !isNaN(_t._iO.position)?_t._iO.position:0);
- if (_t._iO.onplay) {
+
+ // if first play and onposition parameters exist, apply them now
+ if (_t._iO.onposition && _t.playState === 0) {
+ _attachOnPosition(_t);
+ }
+
+ _t.playState = 1;
+ _t.paused = false;
+
+ _t.position = (typeof _t._iO.position !== 'undefined' && !isNaN(_t._iO.position) ? _t._iO.position : 0);
+
+ if (!_t.isHTML5) {
+ _t._iO = _policyFix(_loopFix(_t._iO));
+ }
+
+ if (_t._iO.onplay && _updatePlayState) {
_t._iO.onplay.apply(_t);
+ _onplay_called = true;
}
- _t.setVolume(_t._iO.volume, true); // restrict volume to instance options only
+
+ _t.setVolume(_t._iO.volume, true);
_t.setPan(_t._iO.pan, true);
- _s.o._start(_t.sID, _t._iO.loop || 1, (_s.flashVersion == 9?_t.position:_t.position / 1000));
+
+ if (!_t.isHTML5) {
+
+ startOK = _flash._start(_t.id, _t._iO.loops || 1, (_fV === 9 ? _t._iO.position : _t._iO.position / 1000), _t._iO.multiShot);
+
+ if (_fV === 9 && !startOK) {
+ // edge case: no sound hardware, or 32-channel flash ceiling hit.
+ // applies only to Flash 9, non-NetStream/MovieStar sounds.
+ // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Sound.html#play%28%29
+ _s._wD(fN+ _t.id+': No sound hardware, or 32-sound ceiling hit');
+ if (_t._iO.onplayerror) {
+ _t._iO.onplayerror.apply(_t);
+ }
+
+ }
+
+ } else {
+
+ _start_html5_timer();
+
+ a = _t._setup_html5();
+
+ _t.setPosition(_t._iO.position);
+
+ a.play();
+
+ }
+
}
+
+ return _t;
+
};
- this.start = this.play; // just for convenience
+ // just for convenience
+ this.start = this.play;
+
+ /**
+ * Stops playing a sound (and optionally, all sounds)
+ *
+ * @param {boolean} bAll Optional: Whether to stop all sounds
+ * @return {SMSound} The SMSound object
+ */
+
this.stop = function(bAll) {
- if (_t.playState == 1) {
- _t.playState = 0;
+
+ var _iO = _t._iO, _oP;
+
+ if (_t.playState === 1) {
+
+ _t._onbufferchange(0);
+ _t._resetOnPosition(0);
_t.paused = false;
- // if (_s.defaultOptions.onstop) _s.defaultOptions.onstop.apply(_s);
- if (_t._iO.onstop) {
- _t._iO.onstop.apply(_t);
+
+ if (!_t.isHTML5) {
+ _t.playState = 0;
+ }
+
+ // remove onPosition listeners, if any
+ _detachOnPosition();
+
+ // and "to" position, if set
+ if (_iO.to) {
+ _t.clearOnPosition(_iO.to);
+ }
+
+ if (!_t.isHTML5) {
+
+ _flash._stop(_t.id, bAll);
+
+ // hack for netStream: just unload
+ if (_iO.serverURL) {
+ _t.unload();
+ }
+
+ } else {
+
+ if (_t._a) {
+
+ _oP = _t.position;
+
+ // act like Flash, though
+ _t.setPosition(0);
+
+ // hack: reflect old position for onstop() (also like Flash)
+ _t.position = _oP;
+
+ // html5 has no stop()
+ // NOTE: pausing means iOS requires interaction to resume.
+ _t._a.pause();
+
+ _t.playState = 0;
+
+ // and update UI
+ _t._onTimer();
+
+ _stop_html5_timer();
+
+ }
+
}
- _s.o._stop(_t.sID, bAll);
+
_t.instanceCount = 0;
_t._iO = {};
- // _t.instanceOptions = _t._iO;
+
+ if (_iO.onstop) {
+ _iO.onstop.apply(_t);
+ }
+
+ }
+
+ return _t;
+
+ };
+
+ /**
+ * Undocumented/internal: Sets autoPlay for RTMP.
+ *
+ * @param {boolean} autoPlay state
+ */
+
+ this.setAutoPlay = function(autoPlay) {
+
+ _s._wD('sound '+_t.id+' turned autoplay ' + (autoPlay ? 'on' : 'off'));
+ _t._iO.autoPlay = autoPlay;
+
+ if (!_t.isHTML5) {
+ _flash._setAutoPlay(_t.id, autoPlay);
+ if (autoPlay) {
+ // only increment the instanceCount if the sound isn't loaded (TODO: verify RTMP)
+ if (!_t.instanceCount && _t.readyState === 1) {
+ _t.instanceCount++;
+ _s._wD('sound '+_t.id+' incremented instance count to '+_t.instanceCount);
+ }
+ }
}
+
+ };
+
+ /**
+ * Undocumented/internal: Returns the autoPlay boolean.
+ *
+ * @return {boolean} The current autoPlay value
+ */
+
+ this.getAutoPlay = function() {
+
+ return _t._iO.autoPlay;
+
};
- this.setPosition = function(nMsecOffset, bNoDebug) {
- if (typeof nMsecOffset == 'undefined') {
+ /**
+ * Sets the position of a sound.
+ *
+ * @param {number} nMsecOffset Position (milliseconds)
+ * @return {SMSound} The SMSound object
+ */
+
+ this.setPosition = function(nMsecOffset) {
+
+ if (typeof nMsecOffset === 'undefined') {
nMsecOffset = 0;
}
- var offset = Math.min(_t.duration, Math.max(nMsecOffset, 0)); // position >= 0 and <= current available (loaded) duration
+
+ var original_pos,
+ position, position1K,
+ // Use the duration from the instance options, if we don't have a track duration yet.
+ // position >= 0 and <= current available (loaded) duration
+ offset = (_t.isHTML5 ? Math.max(nMsecOffset,0) : Math.min(_t.duration || _t._iO.duration, Math.max(nMsecOffset, 0)));
+
+ original_pos = _t.position;
+ _t.position = offset;
+ position1K = _t.position/1000;
+ _t._resetOnPosition(_t.position);
_t._iO.position = offset;
- if (!bNoDebug) {
- // _s._wD('SMSound.setPosition('+nMsecOffset+')'+(nMsecOffset != offset?', corrected value: '+offset:''));
+
+ if (!_t.isHTML5) {
+
+ position = (_fV === 9 ? _t.position : position1K);
+ if (_t.readyState && _t.readyState !== 2) {
+ // if paused or not playing, will not resume (by playing)
+ _flash._setPosition(_t.id, position, (_t.paused || !_t.playState), _t._iO.multiShot);
+ }
+
+ } else if (_t._a) {
+
+ // Set the position in the canplay handler if the sound is not ready yet
+ if (_t._html5_canplay) {
+ if (_t._a.currentTime !== position1K) {
+ /**
+ * DOM/JS errors/exceptions to watch out for:
+ * if seek is beyond (loaded?) position, "DOM exception 11"
+ * "INDEX_SIZE_ERR": DOM exception 1
+ */
+ _s._wD('setPosition('+position1K+'): setting position');
+ try {
+ _t._a.currentTime = position1K;
+ if (_t.playState === 0 || _t.paused) {
+ // allow seek without auto-play/resume
+ _t._a.pause();
+ }
+ } catch(e) {
+ _s._wD('setPosition('+position1K+'): setting position failed: '+e.message, 2);
+ }
+ }
+ } else {
+ _s._wD('setPosition('+position1K+'): delaying, sound not ready');
+ }
+
+ }
+
+ if (_t.isHTML5) {
+ if (_t.paused) {
+ // if paused, refresh UI right away
+ // force update
+ _t._onTimer(true);
+ }
}
- _s.o._setPosition(_t.sID, (_s.flashVersion == 9?_t._iO.position:_t._iO.position / 1000), (_t.paused || !_t.playState)); // if paused or not playing, will not resume (by playing)
+
+ return _t;
+
};
- this.pause = function() {
- if (_t.paused || _t.playState === 0) {
- return false;
+ /**
+ * Pauses sound playback.
+ *
+ * @return {SMSound} The SMSound object
+ */
+
+ this.pause = function(_bCallFlash) {
+
+ if (_t.paused || (_t.playState === 0 && _t.readyState !== 1)) {
+ return _t;
}
+
_s._wD('SMSound.pause()');
_t.paused = true;
- _s.o._pause(_t.sID);
+
+ if (!_t.isHTML5) {
+ if (_bCallFlash || typeof _bCallFlash === 'undefined') {
+ _flash._pause(_t.id, _t._iO.multiShot);
+ }
+ } else {
+ _t._setup_html5().pause();
+ _stop_html5_timer();
+ }
+
if (_t._iO.onpause) {
_t._iO.onpause.apply(_t);
}
+
+ return _t;
+
};
+ /**
+ * Resumes sound playback.
+ *
+ * @return {SMSound} The SMSound object
+ */
+
+ /**
+ * When auto-loaded streams pause on buffer full they have a playState of 0.
+ * We need to make sure that the playState is set to 1 when these streams "resume".
+ * When a paused stream is resumed, we need to trigger the onplay() callback if it
+ * hasn't been called already. In this case since the sound is being played for the
+ * first time, I think it's more appropriate to call onplay() rather than onresume().
+ */
+
this.resume = function() {
- if (!_t.paused || _t.playState === 0) {
- return false;
+
+ var _iO = _t._iO;
+
+ if (!_t.paused) {
+ return _t;
}
+
_s._wD('SMSound.resume()');
_t.paused = false;
- _s.o._pause(_t.sID); // flash method is toggle-based (pause/resume)
- if (_t._iO.onresume) {
- _t._iO.onresume.apply(_t);
+ _t.playState = 1;
+
+ if (!_t.isHTML5) {
+ if (_iO.isMovieStar && !_iO.serverURL) {
+ // Bizarre Webkit bug (Chrome reported via 8tracks.com dudes): AAC content paused for 30+ seconds(?) will not resume without a reposition.
+ _t.setPosition(_t.position);
+ }
+ // flash method is toggle-based (pause/resume)
+ _flash._pause(_t.id, _iO.multiShot);
+ } else {
+ _t._setup_html5().play();
+ _start_html5_timer();
+ }
+
+ if (!_onplay_called && _iO.onplay) {
+ _iO.onplay.apply(_t);
+ _onplay_called = true;
+ } else if (_iO.onresume) {
+ _iO.onresume.apply(_t);
}
+
+ return _t;
+
};
+ /**
+ * Toggles sound playback.
+ *
+ * @return {SMSound} The SMSound object
+ */
+
this.togglePause = function() {
+
_s._wD('SMSound.togglePause()');
+
if (_t.playState === 0) {
_t.play({
- position: (_s.flashVersion == 9?_t.position:_t.position / 1000)
+ position: (_fV === 9 && !_t.isHTML5 ? _t.position : _t.position / 1000)
});
- return false;
+ return _t;
}
+
if (_t.paused) {
_t.resume();
} else {
_t.pause();
}
+
+ return _t;
+
};
+ /**
+ * Sets the panning (L-R) effect.
+ *
+ * @param {number} nPan The pan value (-100 to 100)
+ * @return {SMSound} The SMSound object
+ */
+
this.setPan = function(nPan, bInstanceOnly) {
- if (typeof nPan == 'undefined') {
+
+ if (typeof nPan === 'undefined') {
nPan = 0;
}
- if (typeof bInstanceOnly == 'undefined') {
+
+ if (typeof bInstanceOnly === 'undefined') {
bInstanceOnly = false;
}
- _s.o._setPan(_t.sID, nPan);
+
+ if (!_t.isHTML5) {
+ _flash._setPan(_t.id, nPan);
+ } // else { no HTML5 pan? }
+
_t._iO.pan = nPan;
+
if (!bInstanceOnly) {
_t.pan = nPan;
+ _t.options.pan = nPan;
}
+
+ return _t;
+
};
- this.setVolume = function(nVol, bInstanceOnly) {
- if (typeof nVol == 'undefined') {
+ /**
+ * Sets the volume.
+ *
+ * @param {number} nVol The volume value (0 to 100)
+ * @return {SMSound} The SMSound object
+ */
+
+ this.setVolume = function(nVol, _bInstanceOnly) {
+
+ /**
+ * Note: Setting volume has no effect on iOS "special snowflake" devices.
+ * Hardware volume control overrides software, and volume
+ * will always return 1 per Apple docs. (iOS 4 + 5.)
+ * http://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AddingSoundtoCanvasAnimations/AddingSoundtoCanvasAnimations.html
+ */
+
+ if (typeof nVol === 'undefined') {
nVol = 100;
}
- if (typeof bInstanceOnly == 'undefined') {
- bInstanceOnly = false;
+
+ if (typeof _bInstanceOnly === 'undefined') {
+ _bInstanceOnly = false;
+ }
+
+ if (!_t.isHTML5) {
+ _flash._setVolume(_t.id, (_s.muted && !_t.muted) || _t.muted?0:nVol);
+ } else if (_t._a) {
+ // valid range: 0-1
+ _t._a.volume = Math.max(0, Math.min(1, nVol/100));
}
- _s.o._setVolume(_t.sID, (_s.muted && !_t.muted) || _t.muted?0:nVol);
+
_t._iO.volume = nVol;
- if (!bInstanceOnly) {
+
+ if (!_bInstanceOnly) {
_t.volume = nVol;
+ _t.options.volume = nVol;
}
+
+ return _t;
+
};
+ /**
+ * Mutes the sound.
+ *
+ * @return {SMSound} The SMSound object
+ */
+
this.mute = function() {
+
_t.muted = true;
- _s.o._setVolume(_t.sID, 0);
+
+ if (!_t.isHTML5) {
+ _flash._setVolume(_t.id, 0);
+ } else if (_t._a) {
+ _t._a.muted = true;
+ }
+
+ return _t;
+
};
+ /**
+ * Unmutes the sound.
+ *
+ * @return {SMSound} The SMSound object
+ */
+
this.unmute = function() {
+
_t.muted = false;
- var hasIO = typeof _t._iO.volume != 'undefined';
- _s.o._setVolume(_t.sID, hasIO?_t._iO.volume:_t.options.volume);
- };
+ var hasIO = (typeof _t._iO.volume !== 'undefined');
- this.toggleMute = function() {
- if (_t.muted) {
- _t.unmute();
- } else {
- _t.mute();
+ if (!_t.isHTML5) {
+ _flash._setVolume(_t.id, hasIO?_t._iO.volume:_t.options.volume);
+ } else if (_t._a) {
+ _t._a.muted = false;
}
+
+ return _t;
+
};
- // --- "private" methods called by Flash ---
+ /**
+ * Toggles the muted state of a sound.
+ *
+ * @return {SMSound} The SMSound object
+ */
+
+ this.toggleMute = function() {
+
+ return (_t.muted?_t.unmute():_t.mute());
- this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration) {
- if (!_t._iO.isMovieStar) {
- _t.bytesLoaded = nBytesLoaded;
- _t.bytesTotal = nBytesTotal;
- _t.duration = Math.floor(nDuration);
- _t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10);
- if (_t.durationEstimate === undefined) {
- // reported bug?
- _t.durationEstimate = _t.duration;
- }
- if (_t.readyState != 3 && _t._iO.whileloading) {
- _t._iO.whileloading.apply(_t);
- }
- } else {
- _t.bytesLoaded = nBytesLoaded;
- _t.bytesTotal = nBytesTotal;
- _t.duration = Math.floor(nDuration);
- _t.durationEstimate = _t.duration;
- if (_t.readyState != 3 && _t._iO.whileloading) {
- _t._iO.whileloading.apply(_t);
- }
- }
};
- this._onid3 = function(oID3PropNames, oID3Data) {
- // oID3PropNames: string array (names)
- // ID3Data: string array (data)
- _s._wD('SMSound._onid3(): "'+this.sID+'" ID3 data received.');
- var oData = [];
- for (var i=0, j = oID3PropNames.length; i<j; i++) {
- oData[oID3PropNames[i]] = oID3Data[i];
- // _s._wD(oID3PropNames[i]+': '+oID3Data[i]);
- }
- _t.id3 = _s._mergeObjects(_t.id3, oData);
- if (_t._iO.onid3) {
- _t._iO.onid3.apply(_t);
- }
+ /**
+ * Registers a callback to be fired when a sound reaches a given position during playback.
+ *
+ * @param {number} nPosition The position to watch for
+ * @param {function} oMethod The relevant callback to fire
+ * @param {object} oScope Optional: The scope to apply the callback to
+ * @return {SMSound} The SMSound object
+ */
+
+ this.onPosition = function(nPosition, oMethod, oScope) {
+
+ // TODO: basic dupe checking?
+
+ _onPositionItems.push({
+ position: parseInt(nPosition, 10),
+ method: oMethod,
+ scope: (typeof oScope !== 'undefined' ? oScope : _t),
+ fired: false
+ });
+
+ return _t;
+
};
- this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) {
+ // legacy/backwards-compability: lower-case method name
+ this.onposition = this.onPosition;
- if (isNaN(nPosition) || nPosition === null) {
- return false; // Flash may return NaN at times
- }
- if (_t.playState === 0 && nPosition > 0) {
- // can happen at the end of a video where nPosition == 33 for some reason, after finishing.???
- // can also happen with a normal stop operation. This resets the position to 0.
- // _s._writeDebug('Note: Not playing, but position = '+nPosition);
- nPosition = 0;
+ /**
+ * Removes registered callback(s) from a sound, by position and/or callback.
+ *
+ * @param {number} nPosition The position to clear callback(s) for
+ * @param {function} oMethod Optional: Identify one callback to be removed when multiple listeners exist for one position
+ * @return {SMSound} The SMSound object
+ */
+
+ this.clearOnPosition = function(nPosition, oMethod) {
+
+ var i;
+
+ nPosition = parseInt(nPosition, 10);
+
+ if (isNaN(nPosition)) {
+ // safety check
+ return false;
}
- _t.position = nPosition;
- if (_s.flashVersion > 8) {
- if (_t._iO.usePeakData && typeof oPeakData != 'undefined' && oPeakData) {
- _t.peakData = {
- left: oPeakData.leftPeak,
- right: oPeakData.rightPeak
- };
- }
- if (_t._iO.useWaveformData && typeof oWaveformDataLeft != 'undefined' && oWaveformDataLeft) {
- _t.waveformData = {
- left: oWaveformDataLeft.split(','),
- right: oWaveformDataRight.split(',')
- };
- }
- if (_t._iO.useEQData) {
- if (typeof oEQData != 'undefined' && oEQData.leftEQ) {
- var eqLeft = oEQData.leftEQ.split(',');
- _t.eqData = eqLeft;
- _t.eqData.left = eqLeft;
- if (typeof oEQData.rightEQ != 'undefined' && oEQData.rightEQ) {
- _t.eqData.right = oEQData.rightEQ.split(',');
+ for (i=0; i < _onPositionItems.length; i++) {
+
+ if (nPosition === _onPositionItems[i].position) {
+ // remove this item if no method was specified, or, if the method matches
+ if (!oMethod || (oMethod === _onPositionItems[i].method)) {
+ if (_onPositionItems[i].fired) {
+ // decrement "fired" counter, too
+ _onPositionFired--;
}
+ _onPositionItems.splice(i, 1);
}
}
- }
- if (_t.playState == 1) {
- // special case/hack: ensure buffering is false (instant load from cache, thus buffering stuck at 1?)
- if (_t.isBuffering) {
- _t._onbufferchange(0);
- }
- if (_t._iO.whileplaying) {
- _t._iO.whileplaying.apply(_t); // flash may call after actual finish
- }
- if (_t.loaded && _t._iO.onbeforefinish && _t._iO.onbeforefinishtime && !_t.didBeforeFinish && _t.duration - _t.position <= _t._iO.onbeforefinishtime) {
- _s._wD('duration-position <= onbeforefinishtime: '+_t.duration+' - '+_t.position+' <= '+_t._iO.onbeforefinishtime+' ('+(_t.duration - _t.position)+')');
- _t._onbeforefinish();
- }
}
+
};
- this._onload = function(bSuccess) {
- var fN = 'SMSound._onload(): ';
- bSuccess = (bSuccess == 1?true:false);
- _s._wD(fN+'"'+_t.sID+'"'+(bSuccess?' loaded.':' failed to load? - '+_t.url), (bSuccess?1:2));
- if (!bSuccess) {
- if (_s.sandbox.noRemote === true) {
- _s._wD(fN+_s._str('noNet'), 1);
- }
- if (_s.sandbox.noLocal === true) {
- _s._wD(fN+_s._str('noLocal'), 1);
- }
- }
- _t.loaded = bSuccess;
- _t.readyState = bSuccess?3:2;
- if (_t.readyState==2) {
- _t.loadfailed();
- }
- if (_t._iO.onload) {
- _t._iO.onload.apply(_t);
+ this._processOnPosition = function() {
+
+ var i, item, j = _onPositionItems.length;
+
+ if (!j || !_t.playState || _onPositionFired >= j) {
+ return false;
}
- };
- this._onbeforefinish = function() {
- if (!_t.didBeforeFinish) {
- _t.didBeforeFinish = true;
- if (_t._iO.onbeforefinish) {
- _s._wD('SMSound._onbeforefinish(): "'+_t.sID+'"');
- _t._iO.onbeforefinish.apply(_t);
+ for (i=j-1; i >= 0; i--) {
+ item = _onPositionItems[i];
+ if (!item.fired && _t.position >= item.position) {
+ item.fired = true;
+ _onPositionFired++;
+ item.method.apply(item.scope, [item.position]);
}
}
+
+ return true;
+
};
- this._onjustbeforefinish = function(msOffset) {
- // msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)
- if (!_t.didJustBeforeFinish) {
- _t.didJustBeforeFinish = true;
- if (_t._iO.onjustbeforefinish) {
- _s._wD('SMSound._onjustbeforefinish(): "'+_t.sID+'"');
- _t._iO.onjustbeforefinish.apply(_t);
- }
+ this._resetOnPosition = function(nPosition) {
+
+ // reset "fired" for items interested in this position
+ var i, item, j = _onPositionItems.length;
+
+ if (!j) {
+ return false;
}
- };
- this._onfinish = function() {
- // sound has finished playing
- // TODO: calling user-defined onfinish() should happen after setPosition(0)
- // OR: onfinish() and then setPosition(0) is bad.
- if (_t._iO.onbeforefinishcomplete) {
- _t._iO.onbeforefinishcomplete.apply(_t);
+ for (i=j-1; i >= 0; i--) {
+ item = _onPositionItems[i];
+ if (item.fired && nPosition <= item.position) {
+ item.fired = false;
+ _onPositionFired--;
+ }
}
+
+ return true;
+
+ };
+
+ /**
+ * SMSound() private internals
+ * --------------------------------
+ */
+
+ _applyFromTo = function() {
+
+ var _iO = _t._iO,
+ f = _iO.from,
+ t = _iO.to,
+ start, end;
+
+ end = function() {
+
+ // end has been reached.
+ _s._wD(_t.id + ': "to" time of ' + t + ' reached.');
+
+ // detach listener
+ _t.clearOnPosition(t, end);
+
+ // stop should clear this, too
+ _t.stop();
+
+ };
+
+ start = function() {
+
+ _s._wD(_t.id + ': playing "from" ' + f);
+
+ // add listener for end
+ if (t !== null && !isNaN(t)) {
+ _t.onPosition(t, end);
+ }
+
+ };
+
+ if (f !== null && !isNaN(f)) {
+
+ // apply to instance options, guaranteeing correct start position.
+ _iO.position = f;
+
+ // multiShot timing can't be tracked, so prevent that.
+ _iO.multiShot = false;
+
+ start();
+
+ }
+
+ // return updated instanceOptions including starting position
+ return _iO;
+
+ };
+
+ _attachOnPosition = function() {
+
+ var item,
+ op = _t._iO.onposition;
+
+ // attach onposition things, if any, now.
+
+ if (op) {
+
+ for (item in op) {
+ if (op.hasOwnProperty(item)) {
+ _t.onPosition(parseInt(item, 10), op[item]);
+ }
+ }
+
+ }
+
+ };
+
+ _detachOnPosition = function() {
+
+ var item,
+ op = _t._iO.onposition;
+
+ // detach any onposition()-style listeners.
+
+ if (op) {
+
+ for (item in op) {
+ if (op.hasOwnProperty(item)) {
+ _t.clearOnPosition(parseInt(item, 10));
+ }
+ }
+
+ }
+
+ };
+
+ _start_html5_timer = function() {
+
+ if (_t.isHTML5) {
+ _startTimer(_t);
+ }
+
+ };
+
+ _stop_html5_timer = function() {
+
+ if (_t.isHTML5) {
+ _stopTimer(_t);
+ }
+
+ };
+
+ _resetProperties = function(retainPosition) {
+
+ if (!retainPosition) {
+ _onPositionItems = [];
+ _onPositionFired = 0;
+ }
+
+ _onplay_called = false;
+
+ _t._hasTimer = null;
+ _t._a = null;
+ _t._html5_canplay = false;
+ _t.bytesLoaded = null;
+ _t.bytesTotal = null;
+ _t.duration = (_t._iO && _t._iO.duration ? _t._iO.duration : null);
+ _t.durationEstimate = null;
+ _t.buffered = [];
+
+ // legacy: 1D array
+ _t.eqData = [];
+
+ _t.eqData.left = [];
+ _t.eqData.right = [];
+
+ _t.failures = 0;
+ _t.isBuffering = false;
+ _t.instanceOptions = {};
+ _t.instanceCount = 0;
+ _t.loaded = false;
+ _t.metadata = {};
+
+ // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success
+ _t.readyState = 0;
+
+ _t.muted = false;
+ _t.paused = false;
+
+ _t.peakData = {
+ left: 0,
+ right: 0
+ };
+
+ _t.waveformData = {
+ left: [],
+ right: []
+ };
+
+ _t.playState = 0;
+ _t.position = null;
+
+ _t.id3 = {};
+
+ };
+
+ _resetProperties();
+
+ /**
+ * Pseudo-private SMSound internals
+ * --------------------------------
+ */
+
+ this._onTimer = function(bForce) {
+
+ /**
+ * HTML5-only _whileplaying() etc.
+ * called from both HTML5 native events, and polling/interval-based timers
+ * mimics flash and fires only when time/duration change, so as to be polling-friendly
+ */
+
+ var duration, isNew = false, time, x = {};
+
+ if (_t._hasTimer || bForce) {
+
+ // TODO: May not need to track readyState (1 = loading)
+
+ if (_t._a && (bForce || ((_t.playState > 0 || _t.readyState === 1) && !_t.paused))) {
+
+ duration = _t._get_html5_duration();
+
+ if (duration !== _lastHTML5State.duration) {
+
+ _lastHTML5State.duration = duration;
+ _t.duration = duration;
+ isNew = true;
+
+ }
+
+ // TODO: investigate why this goes wack if not set/re-set each time.
+ _t.durationEstimate = _t.duration;
+
+ time = (_t._a.currentTime * 1000 || 0);
+
+ if (time !== _lastHTML5State.time) {
+
+ _lastHTML5State.time = time;
+ isNew = true;
+
+ }
+
+ if (isNew || bForce) {
+
+ _t._whileplaying(time,x,x,x,x);
+
+ }
+
+ }/* else {
+
+ // _s._wD('_onTimer: Warn for "'+_t.id+'": '+(!_t._a?'Could not find element. ':'')+(_t.playState === 0?'playState bad, 0?':'playState = '+_t.playState+', OK'));
+
+ return false;
+
+ }*/
+
+ return isNew;
+
+ }
+
+ };
+
+ this._get_html5_duration = function() {
+
+ var _iO = _t._iO,
+ d = (_t._a ? _t._a.duration*1000 : (_iO ? _iO.duration : undefined)),
+ result = (d && !isNaN(d) && d !== Infinity ? d : (_iO ? _iO.duration : null));
+
+ return result;
+
+ };
+
+ this._apply_loop = function(a, nLoops) {
+
+ /**
+ * boolean instead of "loop", for webkit? - spec says string. http://www.w3.org/TR/html-markup/audio.html#audio.attrs.loop
+ * note that loop is either off or infinite under HTML5, unlike Flash which allows arbitrary loop counts to be specified.
+ */
+
+ // <d>
+ if (!a.loop && nLoops > 1) {
+ _s._wD('Note: Native HTML5 looping is infinite.');
+ }
+ // </d>
+
+ a.loop = (nLoops > 1 ? 'loop' : '');
+
+ };
+
+ this._setup_html5 = function(oOptions) {
+
+ var _iO = _mixin(_t._iO, oOptions), d = decodeURI,
+ _a = _useGlobalHTML5Audio ? _s._global_a : _t._a,
+ _dURL = d(_iO.url),
+ _oldIO = (_a && _a._t ? _a._t.instanceOptions : null),
+ result;
+
+ if (_a) {
+
+ if (_a._t) {
+
+ if (!_useGlobalHTML5Audio && _dURL === d(_lastURL)) {
+
+ // same url, ignore request
+ result = _a;
+
+ } else if (_useGlobalHTML5Audio && _oldIO.url === _iO.url && (!_lastURL || (_lastURL === _oldIO.url))) {
+
+ // iOS-type reuse case
+ result = _a;
+
+ }
+
+ if (result) {
+
+ _t._apply_loop(_a, _iO.loops);
+ return result;
+
+ }
+
+ }
+
+ _s._wD('setting URL on existing object: ' + _dURL + (_lastURL ? ', old URL: ' + _lastURL : ''));
+
+ /**
+ * "First things first, I, Poppa.." (reset the previous state of the old sound, if playing)
+ * Fixes case with devices that can only play one sound at a time
+ * Otherwise, other sounds in mid-play will be terminated without warning and in a stuck state
+ */
+
+ if (_useGlobalHTML5Audio && _a._t && _a._t.playState && _iO.url !== _oldIO.url) {
+
+ _a._t.stop();
+
+ }
+
+ // reset load/playstate, onPosition etc. if the URL is new.
+ // somewhat-tricky object re-use vs. new SMSound object, old vs. new URL comparisons
+ _resetProperties((_oldIO && _oldIO.url ? _iO.url === _oldIO.url : (_lastURL ? _lastURL === _iO.url : false)));
+
+ _a.src = _iO.url;
+ _t.url = _iO.url;
+ _lastURL = _iO.url;
+ _a._called_load = false;
+
+ } else {
+
+ _wDS('h5a');
+
+ if (_iO.autoLoad || _iO.autoPlay) {
+
+ _t._a = new Audio(_iO.url);
+
+ } else {
+
+ // null for stupid Opera 9.64 case
+ _t._a = (_isOpera ? new Audio(null) : new Audio());
+
+ }
+
+ // assign local reference
+ _a = _t._a;
+
+ _a._called_load = false;
+
+ if (_useGlobalHTML5Audio) {
+
+ _s._global_a = _a;
+
+ }
+
+ }
+
+ _t.isHTML5 = true;
+
+ // store a ref on the track
+ _t._a = _a;
+
+ // store a ref on the audio
+ _a._t = _t;
+
+ _add_html5_events();
+
+ _t._apply_loop(_a, _iO.loops);
+
+ if (_iO.autoLoad || _iO.autoPlay) {
+
+ _t.load();
+
+ } else {
+
+ // early HTML5 implementation (non-standard)
+ _a.autobuffer = false;
+
+ // standard ('none' is also an option.)
+ _a.preload = 'auto';
+
+ }
+
+ return _a;
+
+ };
+
+ _add_html5_events = function() {
+
+ if (_t._a._added_events) {
+ return false;
+ }
+
+ var f;
+
+ function add(oEvt, oFn, bCapture) {
+ return _t._a ? _t._a.addEventListener(oEvt, oFn, bCapture||false) : null;
+ }
+
+ _t._a._added_events = true;
+
+ for (f in _html5_events) {
+ if (_html5_events.hasOwnProperty(f)) {
+ add(f, _html5_events[f]);
+ }
+ }
+
+ return true;
+
+ };
+
+ _remove_html5_events = function() {
+
+ // Remove event listeners
+
+ var f;
+
+ function remove(oEvt, oFn, bCapture) {
+ return (_t._a ? _t._a.removeEventListener(oEvt, oFn, bCapture||false) : null);
+ }
+
+ _s._wD(_h5+'removing event listeners: '+_t.id);
+ _t._a._added_events = false;
+
+ for (f in _html5_events) {
+ if (_html5_events.hasOwnProperty(f)) {
+ remove(f, _html5_events[f]);
+ }
+ }
+
+ };
+
+ /**
+ * Pseudo-private event internals
+ * ------------------------------
+ */
+
+ this._onload = function(nSuccess) {
+
+
+ var fN,
+ // check for duration to prevent false positives from flash 8 when loading from cache.
+ loadOK = (!!(nSuccess) || (!_t.isHTML5 && _fV === 8 && _t.duration));
+
+ // <d>
+ fN = 'SMSound._onload(): ';
+ _s._wD(fN + '"' + _t.id + '"' + (loadOK?' loaded.':' failed to load? - ' + _t.url), (loadOK?1:2));
+ if (!loadOK && !_t.isHTML5) {
+ if (_s.sandbox.noRemote === true) {
+ _s._wD(fN + _str('noNet'), 1);
+ }
+ if (_s.sandbox.noLocal === true) {
+ _s._wD(fN + _str('noLocal'), 1);
+ }
+ }
+ // </d>
+
+ _t.loaded = loadOK;
+ _t.readyState = loadOK?3:2;
+ _t._onbufferchange(0);
+
+ if (_t._iO.onload) {
+ _t._iO.onload.apply(_t, [loadOK]);
+ }
+
+ return true;
+
+ };
+
+ this._onbufferchange = function(nIsBuffering) {
+
+ if (_t.playState === 0) {
+ // ignore if not playing
+ return false;
+ }
+
+ if ((nIsBuffering && _t.isBuffering) || (!nIsBuffering && !_t.isBuffering)) {
+ return false;
+ }
+
+ _t.isBuffering = (nIsBuffering === 1);
+ if (_t._iO.onbufferchange) {
+ _s._wD('SMSound._onbufferchange(): ' + nIsBuffering);
+ _t._iO.onbufferchange.apply(_t);
+ }
+
+ return true;
+
+ };
+
+ /**
+ * Notify Mobile Safari that user action is required
+ * to continue playing / loading the audio file.
+ */
+
+ this._onsuspend = function() {
+
+ if (_t._iO.onsuspend) {
+ _s._wD('SMSound._onsuspend()');
+ _t._iO.onsuspend.apply(_t);
+ }
+
+ return true;
+
+ };
+
+ /**
+ * flash 9/movieStar + RTMP-only method, should fire only once at most
+ * at this point we just recreate failed sounds rather than trying to reconnect
+ */
+
+ this._onfailure = function(msg, level, code) {
+
+ _t.failures++;
+ _s._wD('SMSound._onfailure(): "'+_t.id+'" count '+_t.failures);
+
+ if (_t._iO.onfailure && _t.failures === 1) {
+ _t._iO.onfailure(_t, msg, level, code);
+ } else {
+ _s._wD('SMSound._onfailure(): ignoring');
+ }
+
+ };
+
+ this._onfinish = function() {
+
+ // store local copy before it gets trashed..
+ var _io_onfinish = _t._iO.onfinish;
+
+ _t._onbufferchange(0);
+ _t._resetOnPosition(0);
+
// reset some state items
- _t.didBeforeFinish = false;
- _t.didJustBeforeFinish = false;
if (_t.instanceCount) {
+
_t.instanceCount--;
+
if (!_t.instanceCount) {
+
+ // remove onPosition listeners, if any
+ _detachOnPosition();
+
// reset instance options
- // _t.setPosition(0);
_t.playState = 0;
_t.paused = false;
_t.instanceCount = 0;
_t.instanceOptions = {};
+ _t._iO = {};
+ _stop_html5_timer();
+
+ // reset position, too
+ if (_t.isHTML5) {
+ _t.position = 0;
+ }
+
+ }
+
+ if (!_t.instanceCount || _t._iO.multiShotEvents) {
+ // fire onfinish for last, or every instance
+ if (_io_onfinish) {
+ _s._wD('SMSound._onfinish(): "' + _t.id + '"');
+ _io_onfinish.apply(_t);
+ }
+ }
+
+ }
+
+ };
+
+ this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration, nBufferLength) {
+
+ var _iO = _t._iO;
+
+ _t.bytesLoaded = nBytesLoaded;
+ _t.bytesTotal = nBytesTotal;
+ _t.duration = Math.floor(nDuration);
+ _t.bufferLength = nBufferLength;
+
+ if (!_iO.isMovieStar) {
+
+ if (_iO.duration) {
+ // use duration from options, if specified and larger
+ _t.durationEstimate = (_t.duration > _iO.duration) ? _t.duration : _iO.duration;
+ } else {
+ _t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10);
+ }
+
+ if (typeof _t.durationEstimate === 'undefined') {
+ _t.durationEstimate = _t.duration;
+ }
+
+ } else {
+
+ _t.durationEstimate = _t.duration;
+
+ }
+
+ // for flash, reflect sequential-load-style buffering
+ if (!_t.isHTML5) {
+ _t.buffered = [{
+ 'start': 0,
+ 'end': _t.duration
+ }];
+ }
+
+ // allow whileloading to fire even if "load" fired under HTML5, due to HTTP range/partials
+ if ((_t.readyState !== 3 || _t.isHTML5) && _iO.whileloading) {
+ _iO.whileloading.apply(_t);
+ }
+
+ };
+
+ this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) {
+
+ var _iO = _t._iO,
+ eqLeft;
+
+ if (isNaN(nPosition) || nPosition === null) {
+ // flash safety net
+ return false;
+ }
+
+ // Safari HTML5 play() may return small -ve values when starting from position: 0, eg. -50.120396875. Unexpected/invalid per W3, I think. Normalize to 0.
+ _t.position = Math.max(0, nPosition);
+
+ _t._processOnPosition();
+
+ if (!_t.isHTML5 && _fV > 8) {
+
+ if (_iO.usePeakData && typeof oPeakData !== 'undefined' && oPeakData) {
+ _t.peakData = {
+ left: oPeakData.leftPeak,
+ right: oPeakData.rightPeak
+ };
+ }
+
+ if (_iO.useWaveformData && typeof oWaveformDataLeft !== 'undefined' && oWaveformDataLeft) {
+ _t.waveformData = {
+ left: oWaveformDataLeft.split(','),
+ right: oWaveformDataRight.split(',')
+ };
+ }
+
+ if (_iO.useEQData) {
+ if (typeof oEQData !== 'undefined' && oEQData && oEQData.leftEQ) {
+ eqLeft = oEQData.leftEQ.split(',');
+ _t.eqData = eqLeft;
+ _t.eqData.left = eqLeft;
+ if (typeof oEQData.rightEQ !== 'undefined' && oEQData.rightEQ) {
+ _t.eqData.right = oEQData.rightEQ.split(',');
+ }
+ }
+ }
+
+ }
+
+ if (_t.playState === 1) {
+
+ // special case/hack: ensure buffering is false if loading from cache (and not yet started)
+ if (!_t.isHTML5 && _fV === 8 && !_t.position && _t.isBuffering) {
+ _t._onbufferchange(0);
+ }
+
+ if (_iO.whileplaying) {
+ // flash may call after actual finish
+ _iO.whileplaying.apply(_t);
+ }
+
+ }
+
+ return true;
+
+ };
+
+ this._oncaptiondata = function(oData) {
+
+ /**
+ * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature
+ *
+ * @param {object} oData
+ */
+
+ _s._wD('SMSound._oncaptiondata(): "' + this.id + '" caption data received.');
+
+ _t.captiondata = oData;
+
+ if (_t._iO.oncaptiondata) {
+ _t._iO.oncaptiondata.apply(_t);
+ }
+
+ };
+
+ this._onmetadata = function(oMDProps, oMDData) {
+
+ /**
+ * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature
+ * RTMP may include song title, MovieStar content may include encoding info
+ *
+ * @param {array} oMDProps (names)
+ * @param {array} oMDData (values)
+ */
+
+ _s._wD('SMSound._onmetadata(): "' + this.id + '" metadata received.');
+
+ var oData = {}, i, j;
+
+ for (i = 0, j = oMDProps.length; i < j; i++) {
+ oData[oMDProps[i]] = oMDData[i];
+ }
+ _t.metadata = oData;
+
+ if (_t._iO.onmetadata) {
+ _t._iO.onmetadata.apply(_t);
+ }
+
+ };
+
+ this._onid3 = function(oID3Props, oID3Data) {
+
+ /**
+ * internal: flash 8 + flash 9 ID3 feature
+ * may include artist, song title etc.
+ *
+ * @param {array} oID3Props (names)
+ * @param {array} oID3Data (values)
+ */
+
+ _s._wD('SMSound._onid3(): "' + this.id + '" ID3 data received.');
+
+ var oData = [], i, j;
+
+ for (i = 0, j = oID3Props.length; i < j; i++) {
+ oData[oID3Props[i]] = oID3Data[i];
+ }
+ _t.id3 = _mixin(_t.id3, oData);
+
+ if (_t._iO.onid3) {
+ _t._iO.onid3.apply(_t);
+ }
+
+ };
+
+ // flash/RTMP-only
+
+ this._onconnect = function(bSuccess) {
+
+ bSuccess = (bSuccess === 1);
+ _s._wD('SMSound._onconnect(): "'+_t.id+'"'+(bSuccess?' connected.':' failed to connect? - '+_t.url), (bSuccess?1:2));
+ _t.connected = bSuccess;
+
+ if (bSuccess) {
+
+ _t.failures = 0;
+
+ if (_idCheck(_t.id)) {
+ if (_t.getAutoPlay()) {
+ // only update the play state if auto playing
+ _t.play(undefined, _t.getAutoPlay());
+ } else if (_t._iO.autoLoad) {
+ _t.load();
+ }
+ }
+
+ if (_t._iO.onconnect) {
+ _t._iO.onconnect.apply(_t, [bSuccess]);
+ }
+
+ }
+
+ };
+
+ this._ondataerror = function(sError) {
+
+ // flash 9 wave/eq data handler
+ // hack: called at start, and end from flash at/after onfinish()
+ if (_t.playState > 0) {
+ _s._wD('SMSound._ondataerror(): ' + sError);
+ if (_t._iO.ondataerror) {
+ _t._iO.ondataerror.apply(_t);
+ }
+ }
+
+ };
+
+ }; // SMSound()
+
+ /**
+ * Private SoundManager internals
+ * ------------------------------
+ */
+
+ _getDocument = function() {
+
+ return (_doc.body || _doc._docElement || _doc.getElementsByTagName('div')[0]);
+
+ };
+
+ _id = function(sID) {
+
+ return _doc.getElementById(sID);
+
+ };
+
+ _mixin = function(oMain, oAdd) {
+
+ // non-destructive merge
+ var o1 = (oMain || {}), o2, o;
+
+ // if unspecified, o2 is the default options object
+ o2 = (typeof oAdd === 'undefined' ? _s.defaultOptions : oAdd);
+
+ for (o in o2) {
+
+ if (o2.hasOwnProperty(o) && typeof o1[o] === 'undefined') {
+
+ if (typeof o2[o] !== 'object' || o2[o] === null) {
+
+ // assign directly
+ o1[o] = o2[o];
+
+ } else {
+
+ // recurse through o2
+ o1[o] = _mixin(o1[o], o2[o]);
+
+ }
+
+ }
+
+ }
+
+ return o1;
+
+ };
+
+ // additional soundManager properties that soundManager.setup() will accept
+
+ _extraOptions = {
+ 'onready': 1,
+ 'ontimeout': 1,
+ 'defaultOptions': 1,
+ 'flash9Options': 1,
+ 'movieStarOptions': 1
+ };
+
+ _assign = function(o, oParent) {
+
+ /**
+ * recursive assignment of properties, soundManager.setup() helper
+ * allows property assignment based on whitelist
+ */
+
+ var i,
+ result = true,
+ hasParent = (typeof oParent !== 'undefined'),
+ setupOptions = _s.setupOptions,
+ extraOptions = _extraOptions;
+
+ // <d>
+
+ // if soundManager.setup() called, show accepted parameters.
+
+ if (typeof o === 'undefined') {
+
+ result = [];
+
+ for (i in setupOptions) {
+
+ if (setupOptions.hasOwnProperty(i)) {
+ result.push(i);
+ }
+
+ }
+
+ for (i in extraOptions) {
+
+ if (extraOptions.hasOwnProperty(i)) {
+
+ if (typeof _s[i] === 'object') {
+
+ result.push(i+': {...}');
+
+ } else if (_s[i] instanceof Function) {
+
+ result.push(i+': function() {...}');
+
+ } else {
+
+ result.push(i);
+
+ }
+
+ }
+
+ }
+
+ _s._wD(_str('setup', result.join(', ')));
+
+ return false;
+
+ }
+
+ // </d>
+
+ for (i in o) {
+
+ if (o.hasOwnProperty(i)) {
+
+ // if not an {object} we want to recurse through...
+
+ if (typeof o[i] !== 'object' || o[i] === null || o[i] instanceof Array) {
+
+ // check "allowed" options
+
+ if (hasParent && typeof extraOptions[oParent] !== 'undefined') {
+
+ // valid recursive / nested object option, eg., { defaultOptions: { volume: 50 } }
+ _s[oParent][i] = o[i];
+
+ } else if (typeof setupOptions[i] !== 'undefined') {
+
+ // special case: assign to setupOptions object, which soundManager property references
+ _s.setupOptions[i] = o[i];
+
+ // assign directly to soundManager, too
+ _s[i] = o[i];
+
+ } else if (typeof extraOptions[i] === 'undefined') {
+
+ // invalid or disallowed parameter. complain.
+ _complain(_str((typeof _s[i] === 'undefined' ? 'setupUndef' : 'setupError'), i), 2);
+
+ result = false;
+
+ } else {
+
+ /**
+ * valid extraOptions parameter.
+ * is it a method, like onready/ontimeout? call it.
+ * multiple parameters should be in an array, eg. soundManager.setup({onready: [myHandler, myScope]});
+ */
+
+ if (_s[i] instanceof Function) {
+
+ _s[i].apply(_s, (o[i] instanceof Array? o[i] : [o[i]]));
+
+ } else {
+
+ // good old-fashioned direct assignment
+ _s[i] = o[i];
+
+ }
+
+ }
+
+ } else {
+
+ // recursion case, eg., { defaultOptions: { ... } }
+
+ if (typeof extraOptions[i] === 'undefined') {
+
+ // invalid or disallowed parameter. complain.
+ _complain(_str((typeof _s[i] === 'undefined' ? 'setupUndef' : 'setupError'), i), 2);
+
+ result = false;
+
+ } else {
+
+ // recurse through object
+ return _assign(o[i], i);
+
+ }
+
+ }
+
+ }
+
+ }
+
+ return result;
+
+ };
+
+ _event = (function() {
+
+ var old = (_win.attachEvent),
+ evt = {
+ add: (old?'attachEvent':'addEventListener'),
+ remove: (old?'detachEvent':'removeEventListener')
+ };
+
+ function getArgs(oArgs) {
+
+ var args = _slice.call(oArgs), len = args.length;
+
+ if (old) {
+ // prefix
+ args[1] = 'on' + args[1];
+ if (len > 3) {
+ // no capture
+ args.pop();
+ }
+ } else if (len === 3) {
+ args.push(false);
+ }
+
+ return args;
+
+ }
+
+ function apply(args, sType) {
+
+ var element = args.shift(),
+ method = [evt[sType]];
+
+ if (old) {
+ element[method](args[0], args[1]);
+ } else {
+ element[method].apply(element, args);
+ }
+
+ }
+
+ function add() {
+
+ apply(getArgs(arguments), 'add');
+
+ }
+
+ function remove() {
+
+ apply(getArgs(arguments), 'remove');
+
+ }
+
+ return {
+ 'add': add,
+ 'remove': remove
+ };
+
+ }());
+
+ function _preferFlashCheck(kind) {
+
+ // whether flash should play a given type
+ return (_s.preferFlash && _hasFlash && !_s.ignoreFlash && (typeof _s.flash[kind] !== 'undefined' && _s.flash[kind]));
+
+ }
+
+ /**
+ * Internal HTML5 event handling
+ * -----------------------------
+ */
+
+ function _html5_event(oFn) {
+
+ // wrap html5 event handlers so we don't call them on destroyed sounds
+
+ return function(e) {
+
+ var t = this._t,
+ result;
+
+ if (!t || !t._a) {
+ // <d>
+ if (t && t.id) {
+ _s._wD(_h5+'ignoring '+e.type+': '+t.id);
+ } else {
+ _s._wD(_h5+'ignoring '+e.type);
+ }
+ // </d>
+ result = null;
+ } else {
+ result = oFn.call(this, e);
+ }
+
+ return result;
+
+ };
+
+ }
+
+ _html5_events = {
+
+ // HTML5 event-name-to-handler map
+
+ abort: _html5_event(function() {
+
+ _s._wD(_h5+'abort: '+this._t.id);
+
+ }),
+
+ // enough has loaded to play
+
+ canplay: _html5_event(function() {
+
+ var t = this._t,
+ position1K;
+
+ if (t._html5_canplay) {
+ // this event has already fired. ignore.
+ return true;
+ }
+
+ t._html5_canplay = true;
+ _s._wD(_h5+'canplay: '+t.id+', '+t.url);
+ t._onbufferchange(0);
+
+ // position according to instance options
+ position1K = (typeof t._iO.position !== 'undefined' && !isNaN(t._iO.position)?t._iO.position/1000:null);
+
+ // set the position if position was set before the sound loaded
+ if (t.position && this.currentTime !== position1K) {
+ _s._wD(_h5+'canplay: setting position to '+position1K);
+ try {
+ this.currentTime = position1K;
+ } catch(ee) {
+ _s._wD(_h5+'setting position of ' + position1K + ' failed: '+ee.message, 2);
+ }
+ }
+
+ // hack for HTML5 from/to case
+ if (t._iO._oncanplay) {
+ t._iO._oncanplay();
+ }
+
+ }),
+
+ canplaythrough: _html5_event(function() {
+
+ var t = this._t;
+
+ if (!t.loaded) {
+ t._onbufferchange(0);
+ t._whileloading(t.bytesLoaded, t.bytesTotal, t._get_html5_duration());
+ t._onload(true);
+ }
+
+ }),
+
+ // TODO: Reserved for potential use
+ /*
+ emptied: _html5_event(function() {
+
+ _s._wD(_h5+'emptied: '+this._t.id);
+
+ }),
+ */
+
+ ended: _html5_event(function() {
+
+ var t = this._t;
+
+ _s._wD(_h5+'ended: '+t.id);
+ t._onfinish();
+
+ }),
+
+ error: _html5_event(function() {
+
+ _s._wD(_h5+'error: '+this.error.code);
+ // call load with error state?
+ this._t._onload(false);
+
+ }),
+
+ loadeddata: _html5_event(function() {
+
+ var t = this._t;
+
+ _s._wD(_h5+'loadeddata: '+this._t.id);
+
+ // safari seems to nicely report progress events, eventually totalling 100%
+ if (!t._loaded && !_isSafari) {
+ t.duration = t._get_html5_duration();
+ }
+
+ }),
+
+ loadedmetadata: _html5_event(function() {
+
+ _s._wD(_h5+'loadedmetadata: '+this._t.id);
+
+ }),
+
+ loadstart: _html5_event(function() {
+
+ _s._wD(_h5+'loadstart: '+this._t.id);
+ // assume buffering at first
+ this._t._onbufferchange(1);
+
+ }),
+
+ play: _html5_event(function() {
+
+ _s._wD(_h5+'play: '+this._t.id+', '+this._t.url);
+ // once play starts, no buffering
+ this._t._onbufferchange(0);
+
+ }),
+
+ playing: _html5_event(function() {
+
+ _s._wD(_h5+'playing: '+this._t.id);
+
+ // once play starts, no buffering
+ this._t._onbufferchange(0);
+
+ }),
+
+ progress: _html5_event(function(e) {
+
+ // note: can fire repeatedly after "loaded" event, due to use of HTTP range/partials
+
+ var t = this._t,
+ i, j, str, buffered = 0,
+ isProgress = (e.type === 'progress'),
+ ranges = e.target.buffered,
+ // firefox 3.6 implements e.loaded/total (bytes)
+ loaded = (e.loaded||0),
+ total = (e.total||1);
+
+ // reset the "buffered" (loaded byte ranges) array
+ t.buffered = [];
+
+ if (ranges && ranges.length) {
+
+ // if loaded is 0, try TimeRanges implementation as % of load
+ // https://developer.mozilla.org/en/DOM/TimeRanges
+
+ // re-build "buffered" array
+ for (i=0, j=ranges.length; i<j; i++) {
+ t.buffered.push({
+ 'start': ranges.start(i),
+ 'end': ranges.end(i)
+ });
+ }
+
+ // use the last value locally
+ buffered = (ranges.end(0) - ranges.start(0));
+
+ // linear case, buffer sum; does not account for seeking and HTTP partials / byte ranges
+ loaded = buffered/e.target.duration;
+
+ // <d>
+ if (isProgress && ranges.length > 1) {
+ str = [];
+ j = ranges.length;
+ for (i=0; i<j; i++) {
+ str.push(e.target.buffered.start(i) +'-'+ e.target.buffered.end(i));
+ }
+ _s._wD(_h5+'progress: timeRanges: '+str.join(', '));
+ }
+
+ if (isProgress && !isNaN(loaded)) {
+ _s._wD(_h5+'progress: '+t.id+': ' + Math.floor(loaded*100)+'% loaded');
+ }
+ // </d>
+
+ }
+
+ if (!isNaN(loaded)) {
+
+ // if progress, likely not buffering
+ t._onbufferchange(0);
+ // TODO: prevent calls with duplicate values.
+ t._whileloading(loaded, total, t._get_html5_duration());
+ if (loaded && total && loaded === total) {
+ // in case "onload" doesn't fire (eg. gecko 1.9.2)
+ _html5_events.canplaythrough.call(this, e);
+ }
+
+ }
+
+ }),
+
+ ratechange: _html5_event(function() {
+
+ _s._wD(_h5+'ratechange: '+this._t.id);
+
+ }),
+
+ suspend: _html5_event(function(e) {
+
+ // download paused/stopped, may have finished (eg. onload)
+ var t = this._t;
+
+ _s._wD(_h5+'suspend: '+t.id);
+ _html5_events.progress.call(this, e);
+ t._onsuspend();
+
+ }),
+
+ stalled: _html5_event(function() {
+
+ _s._wD(_h5+'stalled: '+this._t.id);
+
+ }),
+
+ timeupdate: _html5_event(function() {
+
+ this._t._onTimer();
+
+ }),
+
+ waiting: _html5_event(function() {
+
+ var t = this._t;
+
+ // see also: seeking
+ _s._wD(_h5+'waiting: '+t.id);
+
+ // playback faster than download rate, etc.
+ t._onbufferchange(1);
+
+ })
+
+ };
+
+ _html5OK = function(iO) {
+
+ // playability test based on URL or MIME type
+
+ var result;
+
+ if (iO.serverURL || (iO.type && _preferFlashCheck(iO.type))) {
+
+ // RTMP, or preferring flash
+ result = false;
+
+ } else {
+
+ // Use type, if specified. If HTML5-only mode, no other options, so just give 'er
+ result = ((iO.type ? _html5CanPlay({type:iO.type}) : _html5CanPlay({url:iO.url}) || _s.html5Only));
+
+ }
+
+ return result;
+
+ };
+
+ _html5Unload = function(oAudio, url) {
+
+ /**
+ * Internal method: Unload media, and cancel any current/pending network requests.
+ * Firefox can load an empty URL, which allegedly destroys the decoder and stops the download.
+ * https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox#Stopping_the_download_of_media
+ * However, Firefox has been seen loading a relative URL from '' and thus requesting the hosting page on unload.
+ * Other UA behaviour is unclear, so everyone else gets an about:blank-style URL.
+ */
+
+ if (oAudio) {
+ // Firefox likes '' for unload (used to work?) - however, may request hosting page URL (bad.) Most other UAs dislike '' and fail to unload.
+ oAudio.src = url;
+ }
+
+ };
+
+ _html5CanPlay = function(o) {
+
+ /**
+ * Try to find MIME, test and return truthiness
+ * o = {
+ * url: '/path/to/an.mp3',
+ * type: 'audio/mp3'
+ * }
+ */
+
+ if (!_s.useHTML5Audio || !_s.hasHTML5) {
+ return false;
+ }
+
+ var url = (o.url || null),
+ mime = (o.type || null),
+ aF = _s.audioFormats,
+ result,
+ offset,
+ fileExt,
+ item;
+
+ // account for known cases like audio/mp3
+
+ if (mime && typeof _s.html5[mime] !== 'undefined') {
+ return (_s.html5[mime] && !_preferFlashCheck(mime));
+ }
+
+ if (!_html5Ext) {
+ _html5Ext = [];
+ for (item in aF) {
+ if (aF.hasOwnProperty(item)) {
+ _html5Ext.push(item);
+ if (aF[item].related) {
+ _html5Ext = _html5Ext.concat(aF[item].related);
+ }
+ }
+ }
+ _html5Ext = new RegExp('\\.('+_html5Ext.join('|')+')(\\?.*)?$','i');
+ }
+
+ // TODO: Strip URL queries, etc.
+ fileExt = (url ? url.toLowerCase().match(_html5Ext) : null);
+
+ if (!fileExt || !fileExt.length) {
+ if (!mime) {
+ result = false;
+ } else {
+ // audio/mp3 -> mp3, result should be known
+ offset = mime.indexOf(';');
+ // strip "audio/X; codecs.."
+ fileExt = (offset !== -1?mime.substr(0,offset):mime).substr(6);
+ }
+ } else {
+ // match the raw extension name - "mp3", for example
+ fileExt = fileExt[1];
+ }
+
+ if (fileExt && typeof _s.html5[fileExt] !== 'undefined') {
+ // result known
+ result = (_s.html5[fileExt] && !_preferFlashCheck(fileExt));
+ } else {
+ mime = 'audio/'+fileExt;
+ result = _s.html5.canPlayType({type:mime});
+ _s.html5[fileExt] = result;
+ // _s._wD('canPlayType, found result: '+result);
+ result = (result && _s.html5[mime] && !_preferFlashCheck(mime));
+ }
+
+ return result;
+
+ };
+
+ _testHTML5 = function() {
+
+ if (!_s.useHTML5Audio || typeof Audio === 'undefined') {
+ return false;
+ }
+
+ // double-whammy: Opera 9.64 throws WRONG_ARGUMENTS_ERR if no parameter passed to Audio(), and Webkit + iOS happily tries to load "null" as a URL. :/
+ var a = (typeof Audio !== 'undefined' ? (_isOpera ? new Audio(null) : new Audio()) : null),
+ item, lookup, support = {}, aF, i;
+
+ function _cp(m) {
+
+ var canPlay, i, j,
+ result = false,
+ isOK = false;
+
+ if (!a || typeof a.canPlayType !== 'function') {
+ return result;
+ }
+
+ if (m instanceof Array) {
+ // iterate through all mime types, return any successes
+ for (i=0, j=m.length; i<j && !isOK; i++) {
+ if (_s.html5[m[i]] || a.canPlayType(m[i]).match(_s.html5Test)) {
+ isOK = true;
+ _s.html5[m[i]] = true;
+ // note flash support, too
+ _s.flash[m[i]] = !!(m[i].match(_flashMIME));
+ }
+ }
+ result = isOK;
+ } else {
+ canPlay = (a && typeof a.canPlayType === 'function' ? a.canPlayType(m) : false);
+ result = !!(canPlay && (canPlay.match(_s.html5Test)));
+ }
+
+ return result;
+
+ }
+
+ // test all registered formats + codecs
+
+ aF = _s.audioFormats;
+
+ for (item in aF) {
+
+ if (aF.hasOwnProperty(item)) {
+
+ lookup = 'audio/' + item;
+
+ support[item] = _cp(aF[item].type);
+
+ // write back generic type too, eg. audio/mp3
+ support[lookup] = support[item];
+
+ // assign flash
+ if (item.match(_flashMIME)) {
+
+ _s.flash[item] = true;
+ _s.flash[lookup] = true;
+
+ } else {
+
+ _s.flash[item] = false;
+ _s.flash[lookup] = false;
+
+ }
+
+ // assign result to related formats, too
+
+ if (aF[item] && aF[item].related) {
+
+ for (i=aF[item].related.length-1; i >= 0; i--) {
+
+ // eg. audio/m4a
+ support['audio/'+aF[item].related[i]] = support[item];
+ _s.html5[aF[item].related[i]] = support[item];
+ _s.flash[aF[item].related[i]] = support[item];
+
+ }
+
+ }
+
+ }
+
+ }
+
+ support.canPlayType = (a?_cp:null);
+ _s.html5 = _mixin(_s.html5, support);
+
+ return true;
+
+ };
+
+ _strings = {
+
+ // <d>
+ notReady: 'Not loaded yet - wait for soundManager.onready()',
+ notOK: 'Audio support is not available.',
+ domError: _smc + 'createMovie(): appendChild/innerHTML call failed. DOM not ready or other error.',
+ spcWmode: _smc + 'createMovie(): Removing wmode, preventing known SWF loading issue(s)',
+ swf404: _sm + ': Verify that %s is a valid path.',
+ tryDebug: 'Try ' + _sm + '.debugFlash = true for more security details (output goes to SWF.)',
+ checkSWF: 'See SWF output for more debug info.',
+ localFail: _sm + ': Non-HTTP page (' + _doc.location.protocol + ' URL?) Review Flash player security settings for this special case:\nhttp://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/',
+ waitFocus: _sm + ': Special case: Waiting for SWF to load with window focus...',
+ waitImpatient: _sm + ': Getting impatient, still waiting for Flash%s...',
+ waitForever: _sm + ': Waiting indefinitely for Flash (will recover if unblocked)...',
+ waitSWF: _sm + ': Retrying, waiting for 100% SWF load...',
+ needFunction: _sm + ': Function object expected for %s',
+ badID: 'Warning: Sound ID "%s" should be a string, starting with a non-numeric character',
+ currentObj: '--- ' + _sm + '._debug(): Current sound objects ---',
+ waitEI: _smc + 'initMovie(): Waiting for ExternalInterface call from Flash...',
+ waitOnload: _sm + ': Waiting for window.onload()',
+ docLoaded: _sm + ': Document already loaded',
+ onload: _smc + 'initComplete(): calling soundManager.onload()',
+ onloadOK: _sm + '.onload() complete',
+ init: _smc + 'init()',
+ didInit: _smc + 'init(): Already called?',
+ flashJS: _sm + ': Attempting JS to Flash call...',
+ secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html',
+ badRemove: 'Warning: Failed to remove flash movie.',
+ shutdown: _sm + '.disable(): Shutting down',
+ queue: _sm + ': Queueing %s handler',
+ smFail: _sm + ': Failed to initialise.',
+ smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.',
+ fbTimeout: 'No flash response, applying .'+_swfCSS.swfTimedout+' CSS...',
+ fbLoaded: 'Flash loaded',
+ fbHandler: _smc+'flashBlockHandler()',
+ manURL: 'SMSound.load(): Using manually-assigned URL',
+ onURL: _sm + '.load(): current URL already assigned.',
+ badFV: _sm + '.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.',
+ as2loop: 'Note: Setting stream:false so looping can work (flash 8 limitation)',
+ noNSLoop: 'Note: Looping not implemented for MovieStar formats',
+ needfl9: 'Note: Switching to flash 9, required for MP4 formats.',
+ mfTimeout: 'Setting flashLoadTimeout = 0 (infinite) for off-screen, mobile flash case',
+ mfOn: 'mobileFlash::enabling on-screen flash repositioning',
+ policy: 'Enabling usePolicyFile for data access',
+ setup: _sm + '.setup(): allowed parameters: %s',
+ setupError: _sm + '.setup(): "%s" cannot be assigned with this method.',
+ setupUndef: _sm + '.setup(): Could not find option "%s"',
+ setupLate: _sm + '.setup(): url + flashVersion changes will not take effect until reboot().',
+ h5a: 'creating HTML5 Audio() object'
+ // </d>
+
+ };
+
+ _str = function() {
+
+ // internal string replace helper.
+ // arguments: o [,items to replace]
+ // <d>
+
+ // real array, please
+ var args = _slice.call(arguments),
+
+ // first arg
+ o = args.shift(),
+
+ str = (_strings && _strings[o]?_strings[o]:''), i, j;
+ if (str && args && args.length) {
+ for (i = 0, j = args.length; i < j; i++) {
+ str = str.replace('%s', args[i]);
+ }
+ }
+
+ return str;
+ // </d>
+
+ };
+
+ _loopFix = function(sOpt) {
+
+ // flash 8 requires stream = false for looping to work
+ if (_fV === 8 && sOpt.loops > 1 && sOpt.stream) {
+ _wDS('as2loop');
+ sOpt.stream = false;
+ }
+
+ return sOpt;
+
+ };
+
+ _policyFix = function(sOpt, sPre) {
+
+ if (sOpt && !sOpt.usePolicyFile && (sOpt.onid3 || sOpt.usePeakData || sOpt.useWaveformData || sOpt.useEQData)) {
+ _s._wD((sPre || '') + _str('policy'));
+ sOpt.usePolicyFile = true;
+ }
+
+ return sOpt;
+
+ };
+
+ _complain = function(sMsg) {
+
+ // <d>
+ if (typeof console !== 'undefined' && typeof console.warn !== 'undefined') {
+ console.warn(sMsg);
+ } else {
+ _s._wD(sMsg);
+ }
+ // </d>
+
+ };
+
+ _doNothing = function() {
+
+ return false;
+
+ };
+
+ _disableObject = function(o) {
+
+ var oProp;
+
+ for (oProp in o) {
+ if (o.hasOwnProperty(oProp) && typeof o[oProp] === 'function') {
+ o[oProp] = _doNothing;
+ }
+ }
+
+ oProp = null;
+
+ };
+
+ _failSafely = function(bNoDisable) {
+
+ // general failure exception handler
+
+ if (typeof bNoDisable === 'undefined') {
+ bNoDisable = false;
+ }
+
+ if (_disabled || bNoDisable) {
+ _wDS('smFail', 2);
+ _s.disable(bNoDisable);
+ }
+
+ };
+
+ _normalizeMovieURL = function(smURL) {
+
+ var urlParams = null, url;
+
+ if (smURL) {
+ if (smURL.match(/\.swf(\?.*)?$/i)) {
+ urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?') + 4);
+ if (urlParams) {
+ // assume user knows what they're doing
+ return smURL;
+ }
+ } else if (smURL.lastIndexOf('/') !== smURL.length - 1) {
+ // append trailing slash, if needed
+ smURL += '/';
+ }
+ }
+
+ url = (smURL && smURL.lastIndexOf('/') !== - 1 ? smURL.substr(0, smURL.lastIndexOf('/') + 1) : './') + _s.movieURL;
+
+ if (_s.noSWFCache) {
+ url += ('?ts=' + new Date().getTime());
+ }
+
+ return url;
+
+ };
+
+ _setVersionInfo = function() {
+
+ // short-hand for internal use
+
+ _fV = parseInt(_s.flashVersion, 10);
+
+ if (_fV !== 8 && _fV !== 9) {
+ _s._wD(_str('badFV', _fV, _defaultFlashVersion));
+ _s.flashVersion = _fV = _defaultFlashVersion;
+ }
+
+ // debug flash movie, if applicable
+
+ var isDebug = (_s.debugMode || _s.debugFlash?'_debug.swf':'.swf');
+
+ if (_s.useHTML5Audio && !_s.html5Only && _s.audioFormats.mp4.required && _fV < 9) {
+ _s._wD(_str('needfl9'));
+ _s.flashVersion = _fV = 9;
+ }
+
+ _s.version = _s.versionNumber + (_s.html5Only?' (HTML5-only mode)':(_fV === 9?' (AS3/Flash 9)':' (AS2/Flash 8)'));
+
+ // set up default options
+ if (_fV > 8) {
+ // +flash 9 base options
+ _s.defaultOptions = _mixin(_s.defaultOptions, _s.flash9Options);
+ _s.features.buffering = true;
+ // +moviestar support
+ _s.defaultOptions = _mixin(_s.defaultOptions, _s.movieStarOptions);
+ _s.filePatterns.flash9 = new RegExp('\\.(mp3|' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i');
+ _s.features.movieStar = true;
+ } else {
+ _s.features.movieStar = false;
+ }
+
+ // regExp for flash canPlay(), etc.
+ _s.filePattern = _s.filePatterns[(_fV !== 8?'flash9':'flash8')];
+
+ // if applicable, use _debug versions of SWFs
+ _s.movieURL = (_fV === 8?'soundmanager2.swf':'soundmanager2_flash9.swf').replace('.swf', isDebug);
+
+ _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_fV > 8);
+
+ };
+
+ _setPolling = function(bPolling, bHighPerformance) {
+
+ if (!_flash) {
+ return false;
+ }
+
+ _flash._setPolling(bPolling, bHighPerformance);
+
+ };
+
+ _initDebug = function() {
+
+ // starts debug mode, creating output <div> for UAs without console object
+
+ // allow force of debug mode via URL
+ if (_s.debugURLParam.test(_wl)) {
+ _s.debugMode = true;
+ }
+
+ // <d>
+ if (_id(_s.debugID)) {
+ return false;
+ }
+
+ var oD, oDebug, oTarget, oToggle, tmp;
+
+ if (_s.debugMode && !_id(_s.debugID) && (!_hasConsole || !_s.useConsole || !_s.consoleOnly)) {
+
+ oD = _doc.createElement('div');
+ oD.id = _s.debugID + '-toggle';
+
+ oToggle = {
+ 'position': 'fixed',
+ 'bottom': '0px',
+ 'right': '0px',
+ 'width': '1.2em',
+ 'height': '1.2em',
+ 'lineHeight': '1.2em',
+ 'margin': '2px',
+ 'textAlign': 'center',
+ 'border': '1px solid #999',
+ 'cursor': 'pointer',
+ 'background': '#fff',
+ 'color': '#333',
+ 'zIndex': 10001
+ };
+
+ oD.appendChild(_doc.createTextNode('-'));
+ oD.onclick = _toggleDebug;
+ oD.title = 'Toggle SM2 debug console';
+
+ if (_ua.match(/msie 6/i)) {
+ oD.style.position = 'absolute';
+ oD.style.cursor = 'hand';
+ }
+
+ for (tmp in oToggle) {
+ if (oToggle.hasOwnProperty(tmp)) {
+ oD.style[tmp] = oToggle[tmp];
+ }
+ }
+
+ oDebug = _doc.createElement('div');
+ oDebug.id = _s.debugID;
+ oDebug.style.display = (_s.debugMode?'block':'none');
+
+ if (_s.debugMode && !_id(oD.id)) {
+ try {
+ oTarget = _getDocument();
+ oTarget.appendChild(oD);
+ } catch(e2) {
+ throw new Error(_str('domError')+' \n'+e2.toString());
+ }
+ oTarget.appendChild(oDebug);
+ }
+
+ }
+
+ oTarget = null;
+ // </d>
+
+ };
+
+ _idCheck = this.getSoundById;
+
+ // <d>
+ _wDS = function(o, errorLevel) {
+
+ return (!o ? '' : _s._wD(_str(o), errorLevel));
+
+ };
+
+ // last-resort debugging option
+
+ if (_wl.indexOf('sm2-debug=alert') + 1 && _s.debugMode) {
+ _s._wD = function(sText) {window.alert(sText);};
+ }
+
+ _toggleDebug = function() {
+
+ var o = _id(_s.debugID),
+ oT = _id(_s.debugID + '-toggle');
+
+ if (!o) {
+ return false;
+ }
+
+ if (_debugOpen) {
+ // minimize
+ oT.innerHTML = '+';
+ o.style.display = 'none';
+ } else {
+ oT.innerHTML = '-';
+ o.style.display = 'block';
+ }
+
+ _debugOpen = !_debugOpen;
+
+ };
+
+ _debugTS = function(sEventType, bSuccess, sMessage) {
+
+ // troubleshooter debug hooks
+
+ if (typeof sm2Debugger !== 'undefined') {
+ try {
+ sm2Debugger.handleEvent(sEventType, bSuccess, sMessage);
+ } catch(e) {
+ // oh well
+ }
+ }
+
+ return true;
+
+ };
+ // </d>
+
+ _getSWFCSS = function() {
+
+ var css = [];
+
+ if (_s.debugMode) {
+ css.push(_swfCSS.sm2Debug);
+ }
+
+ if (_s.debugFlash) {
+ css.push(_swfCSS.flashDebug);
+ }
+
+ if (_s.useHighPerformance) {
+ css.push(_swfCSS.highPerf);
+ }
+
+ return css.join(' ');
+
+ };
+
+ _flashBlockHandler = function() {
+
+ // *possible* flash block situation.
+
+ var name = _str('fbHandler'),
+ p = _s.getMoviePercent(),
+ css = _swfCSS,
+ error = {type:'FLASHBLOCK'};
+
+ if (_s.html5Only) {
+ return false;
+ }
+
+ if (!_s.ok()) {
+
+ if (_needsFlash) {
+ // make the movie more visible, so user can fix
+ _s.oMC.className = _getSWFCSS() + ' ' + css.swfDefault + ' ' + (p === null?css.swfTimedout:css.swfError);
+ _s._wD(name+': '+_str('fbTimeout')+(p?' ('+_str('fbLoaded')+')':''));
+ }
+
+ _s.didFlashBlock = true;
+
+ // fire onready(), complain lightly
+ _processOnEvents({type:'ontimeout', ignoreInit:true, error:error});
+ _catchError(error);
+
+ } else {
+
+ // SM2 loaded OK (or recovered)
+
+ // <d>
+ if (_s.didFlashBlock) {
+ _s._wD(name+': Unblocked');
+ }
+ // </d>
+
+ if (_s.oMC) {
+ _s.oMC.className = [_getSWFCSS(), css.swfDefault, css.swfLoaded + (_s.didFlashBlock?' '+css.swfUnblocked:'')].join(' ');
+ }
+
+ }
+
+ };
+
+ _addOnEvent = function(sType, oMethod, oScope) {
+
+ if (typeof _on_queue[sType] === 'undefined') {
+ _on_queue[sType] = [];
+ }
+
+ _on_queue[sType].push({
+ 'method': oMethod,
+ 'scope': (oScope || null),
+ 'fired': false
+ });
+
+ };
+
+ _processOnEvents = function(oOptions) {
+
+ // if unspecified, assume OK/error
+
+ if (!oOptions) {
+ oOptions = {
+ type: (_s.ok() ? 'onready' : 'ontimeout')
+ };
+ }
+
+ if (!_didInit && oOptions && !oOptions.ignoreInit) {
+ // not ready yet.
+ return false;
+ }
+
+ if (oOptions.type === 'ontimeout' && (_s.ok() || (_disabled && !oOptions.ignoreInit))) {
+ // invalid case
+ return false;
+ }
+
+ var status = {
+ success: (oOptions && oOptions.ignoreInit?_s.ok():!_disabled)
+ },
+
+ // queue specified by type, or none
+ srcQueue = (oOptions && oOptions.type?_on_queue[oOptions.type]||[]:[]),
+
+ queue = [], i, j,
+ args = [status],
+ canRetry = (_needsFlash && _s.useFlashBlock && !_s.ok());
+
+ if (oOptions.error) {
+ args[0].error = oOptions.error;
+ }
+
+ for (i = 0, j = srcQueue.length; i < j; i++) {
+ if (srcQueue[i].fired !== true) {
+ queue.push(srcQueue[i]);
+ }
+ }
+
+ if (queue.length) {
+ _s._wD(_sm + ': Firing ' + queue.length + ' '+oOptions.type+'() item' + (queue.length === 1?'':'s'));
+ for (i = 0, j = queue.length; i < j; i++) {
+ if (queue[i].scope) {
+ queue[i].method.apply(queue[i].scope, args);
+ } else {
+ queue[i].method.apply(this, args);
+ }
+ if (!canRetry) {
+ // flashblock case doesn't count here
+ queue[i].fired = true;
+ }
+ }
+ }
+
+ return true;
+
+ };
+
+ _initUserOnload = function() {
+
+ _win.setTimeout(function() {
+
+ if (_s.useFlashBlock) {
+ _flashBlockHandler();
+ }
+
+ _processOnEvents();
+
+ // call user-defined "onload", scoped to window
+
+ if (typeof _s.onload === 'function') {
+ _wDS('onload', 1);
+ _s.onload.apply(_win);
+ _wDS('onloadOK', 1);
+ }
+
+ if (_s.waitForWindowLoad) {
+ _event.add(_win, 'load', _initUserOnload);
+ }
+
+ },1);
+
+ };
+
+ _detectFlash = function() {
+
+ // hat tip: Flash Detect library (BSD, (C) 2007) by Carl "DocYes" S. Yestrau - http://featureblend.com/javascript-flash-detection-library.html / http://featureblend.com/license.txt
+
+ if (typeof _hasFlash !== 'undefined') {
+ // this work has already been done.
+ return _hasFlash;
+ }
+
+ var hasPlugin = false, n = navigator, nP = n.plugins, obj, type, types, AX = _win.ActiveXObject;
+
+ if (nP && nP.length) {
+ type = 'application/x-shockwave-flash';
+ types = n.mimeTypes;
+ if (types && types[type] && types[type].enabledPlugin && types[type].enabledPlugin.description) {
+ hasPlugin = true;
+ }
+ } else if (typeof AX !== 'undefined') {
+ try {
+ obj = new AX('ShockwaveFlash.ShockwaveFlash');
+ } catch(e) {
+ // oh well
+ }
+ hasPlugin = (!!obj);
+ }
+
+ _hasFlash = hasPlugin;
+
+ return hasPlugin;
+
+ };
+
+ _featureCheck = function() {
+
+ var needsFlash,
+ item,
+ result = true,
+ formats = _s.audioFormats,
+ // iPhone <= 3.1 has broken HTML5 audio(), but firmware 3.2 (original iPad) + iOS4 works.
+ isSpecial = (_is_iDevice && !!(_ua.match(/os (1|2|3_0|3_1)/i)));
+
+ if (isSpecial) {
+
+ // has Audio(), but is broken; let it load links directly.
+ _s.hasHTML5 = false;
+
+ // ignore flash case, however
+ _s.html5Only = true;
+
+ if (_s.oMC) {
+ _s.oMC.style.display = 'none';
+ }
+
+ result = false;
+
+ } else {
+
+ if (_s.useHTML5Audio) {
+
+ if (!_s.html5 || !_s.html5.canPlayType) {
+ _s._wD('SoundManager: No HTML5 Audio() support detected.');
+ _s.hasHTML5 = false;
+ } else {
+ _s.hasHTML5 = true;
+ }
+
+ // <d>
+ if (_isBadSafari) {
+ _s._wD(_smc+'Note: Buggy HTML5 Audio in Safari on this OS X release, see https://bugs.webkit.org/show_bug.cgi?id=32159 - '+(!_hasFlash?' would use flash fallback for MP3/MP4, but none detected.':'will use flash fallback for MP3/MP4, if available'),1);
+ }
+ // </d>
+
+ }
+
+ }
+
+ if (_s.useHTML5Audio && _s.hasHTML5) {
+
+ for (item in formats) {
+ if (formats.hasOwnProperty(item)) {
+ if ((formats[item].required && !_s.html5.canPlayType(formats[item].type)) || (_s.preferFlash && (_s.flash[item] || _s.flash[formats[item].type]))) {
+ // flash may be required, or preferred for this format
+ needsFlash = true;
+ }
+ }
+ }
+
+ }
+
+ // sanity check...
+ if (_s.ignoreFlash) {
+ needsFlash = false;
+ }
+
+ _s.html5Only = (_s.hasHTML5 && _s.useHTML5Audio && !needsFlash);
+
+ return (!_s.html5Only);
+
+ };
+
+ _parseURL = function(url) {
+
+ /**
+ * Internal: Finds and returns the first playable URL (or failing that, the first URL.)
+ * @param {string or array} url A single URL string, OR, an array of URL strings or {url:'/path/to/resource', type:'audio/mp3'} objects.
+ */
+
+ var i, j, urlResult = 0, result;
+
+ if (url instanceof Array) {
+
+ // find the first good one
+ for (i=0, j=url.length; i<j; i++) {
+
+ if (url[i] instanceof Object) {
+ // MIME check
+ if (_s.canPlayMIME(url[i].type)) {
+ urlResult = i;
+ break;
+ }
+
+ } else if (_s.canPlayURL(url[i])) {
+ // URL string check
+ urlResult = i;
+ break;
+ }
+
+ }
+
+ // normalize to string
+ if (url[urlResult].url) {
+ url[urlResult] = url[urlResult].url;
+ }
+
+ result = url[urlResult];
+
+ } else {
+
+ // single URL case
+ result = url;
+
+ }
+
+ return result;
+
+ };
+
+
+ _startTimer = function(oSound) {
+
+ /**
+ * attach a timer to this sound, and start an interval if needed
+ */
+
+ if (!oSound._hasTimer) {
+
+ oSound._hasTimer = true;
+
+ if (!_mobileHTML5 && _s.html5PollingInterval) {
+
+ if (_h5IntervalTimer === null && _h5TimerCount === 0) {
+
+ _h5IntervalTimer = _win.setInterval(_timerExecute, _s.html5PollingInterval);
+
+ }
+
+ _h5TimerCount++;
+
+ }
+
+ }
+
+ };
+
+ _stopTimer = function(oSound) {
+
+ /**
+ * detach a timer
+ */
+
+ if (oSound._hasTimer) {
+
+ oSound._hasTimer = false;
+
+ if (!_mobileHTML5 && _s.html5PollingInterval) {
+
+ // interval will stop itself at next execution.
+
+ _h5TimerCount--;
+
+ }
+
+ }
+
+ };
+
+ _timerExecute = function() {
+
+ /**
+ * manual polling for HTML5 progress events, ie., whileplaying() (can achieve greater precision than conservative default HTML5 interval)
+ */
+
+ var i;
+
+ if (_h5IntervalTimer !== null && !_h5TimerCount) {
+
+ // no active timers, stop polling interval.
+
+ _win.clearInterval(_h5IntervalTimer);
+
+ _h5IntervalTimer = null;
+
+ return false;
+
+ }
+
+ // check all HTML5 sounds with timers
+
+ for (i = _s.soundIDs.length-1; i >= 0; i--) {
+
+ if (_s.sounds[_s.soundIDs[i]].isHTML5 && _s.sounds[_s.soundIDs[i]]._hasTimer) {
+
+ _s.sounds[_s.soundIDs[i]]._onTimer();
+
+ }
+
+ }
+
+ };
+
+ _catchError = function(options) {
+
+ options = (typeof options !== 'undefined' ? options : {});
+
+ if (typeof _s.onerror === 'function') {
+ _s.onerror.apply(_win, [{type:(typeof options.type !== 'undefined' ? options.type : null)}]);
+ }
+
+ if (typeof options.fatal !== 'undefined' && options.fatal) {
+ _s.disable();
+ }
+
+ };
+
+ _badSafariFix = function() {
+
+ // special case: "bad" Safari (OS X 10.3 - 10.7) must fall back to flash for MP3/MP4
+ if (!_isBadSafari || !_detectFlash()) {
+ // doesn't apply
+ return false;
+ }
+
+ var aF = _s.audioFormats, i, item;
+
+ for (item in aF) {
+ if (aF.hasOwnProperty(item)) {
+ if (item === 'mp3' || item === 'mp4') {
+ _s._wD(_sm+': Using flash fallback for '+item+' format');
+ _s.html5[item] = false;
+ // assign result to related formats, too
+ if (aF[item] && aF[item].related) {
+ for (i = aF[item].related.length-1; i >= 0; i--) {
+ _s.html5[aF[item].related[i]] = false;
+ }
+ }
+ }
+ }
+ }
+
+ };
+
+ /**
+ * Pseudo-private flash/ExternalInterface methods
+ * ----------------------------------------------
+ */
+
+ this._setSandboxType = function(sandboxType) {
+
+ // <d>
+ var sb = _s.sandbox;
+
+ sb.type = sandboxType;
+ sb.description = sb.types[(typeof sb.types[sandboxType] !== 'undefined'?sandboxType:'unknown')];
+
+ _s._wD('Flash security sandbox type: ' + sb.type);
+
+ if (sb.type === 'localWithFile') {
+
+ sb.noRemote = true;
+ sb.noLocal = false;
+ _wDS('secNote', 2);
+
+ } else if (sb.type === 'localWithNetwork') {
+
+ sb.noRemote = false;
+ sb.noLocal = true;
+
+ } else if (sb.type === 'localTrusted') {
+
+ sb.noRemote = false;
+ sb.noLocal = false;
+
+ }
+ // </d>
+
+ };
+
+ this._externalInterfaceOK = function(flashDate, swfVersion) {
+
+ // flash callback confirming flash loaded, EI working etc.
+ // flashDate = approx. timing/delay info for JS/flash bridge
+ // swfVersion: SWF build string
+
+ if (_s.swfLoaded) {
+ return false;
+ }
+
+ var e, eiTime = new Date().getTime();
+
+ _s._wD(_smc+'externalInterfaceOK()' + (flashDate?' (~' + (eiTime - flashDate) + ' ms)':''));
+ _debugTS('swf', true);
+ _debugTS('flashtojs', true);
+ _s.swfLoaded = true;
+ _tryInitOnFocus = false;
+
+ if (_isBadSafari) {
+ _badSafariFix();
+ }
+
+ // complain if JS + SWF build/version strings don't match, excluding +DEV builds
+ // <d>
+ if (!swfVersion || swfVersion.replace(/\+dev/i,'') !== _s.versionNumber.replace(/\+dev/i, '')) {
+
+ e = _sm + ': Fatal: JavaScript file build "' + _s.versionNumber + '" does not match Flash SWF build "' + swfVersion + '" at ' + _s.url + '. Ensure both are up-to-date.';
+
+ // escape flash -> JS stack so this error fires in window.
+ setTimeout(function versionMismatch() {
+ throw new Error(e);
+ }, 0);
+
+ // exit, init will fail with timeout
+ return false;
+
+ }
+ // </d>
+
+ // slight delay before init
+ setTimeout(_init, _isIE ? 100 : 1);
+
+ };
+
+ /**
+ * Private initialization helpers
+ * ------------------------------
+ */
+
+ _createMovie = function(smID, smURL) {
+
+ if (_didAppend && _appendSuccess) {
+ // ignore if already succeeded
+ return false;
+ }
+
+ function _initMsg() {
+ _s._wD('-- SoundManager 2 ' + _s.version + (!_s.html5Only && _s.useHTML5Audio?(_s.hasHTML5?' + HTML5 audio':', no HTML5 audio support'):'') + (!_s.html5Only ? (_s.useHighPerformance?', high performance mode, ':', ') + (( _s.flashPollingInterval ? 'custom (' + _s.flashPollingInterval + 'ms)' : 'normal') + ' polling') + (_s.wmode?', wmode: ' + _s.wmode:'') + (_s.debugFlash?', flash debug mode':'') + (_s.useFlashBlock?', flashBlock mode':'') : '') + ' --', 1);
+ }
+
+ if (_s.html5Only) {
+
+ // 100% HTML5 mode
+ _setVersionInfo();
+
+ _initMsg();
+ _s.oMC = _id(_s.movieID);
+ _init();
+
+ // prevent multiple init attempts
+ _didAppend = true;
+
+ _appendSuccess = true;
+
+ return false;
+
+ }
+
+ // flash path
+ var remoteURL = (smURL || _s.url),
+ localURL = (_s.altURL || remoteURL),
+ swfTitle = 'JS/Flash audio component (SoundManager 2)',
+ oEmbed, oMovie, oTarget = _getDocument(), tmp, movieHTML, oEl, extraClass = _getSWFCSS(),
+ s, x, sClass, isRTL = null,
+ html = _doc.getElementsByTagName('html')[0];
+
+ isRTL = (html && html.dir && html.dir.match(/rtl/i));
+ smID = (typeof smID === 'undefined'?_s.id:smID);
+
+ function param(name, value) {
+ return '<param name="'+name+'" value="'+value+'" />';
+ }
+
+ // safety check for legacy (change to Flash 9 URL)
+ _setVersionInfo();
+ _s.url = _normalizeMovieURL(_overHTTP?remoteURL:localURL);
+ smURL = _s.url;
+
+ _s.wmode = (!_s.wmode && _s.useHighPerformance ? 'transparent' : _s.wmode);
+
+ if (_s.wmode !== null && (_ua.match(/msie 8/i) || (!_isIE && !_s.useHighPerformance)) && navigator.platform.match(/win32|win64/i)) {
+ /**
+ * extra-special case: movie doesn't load until scrolled into view when using wmode = anything but 'window' here
+ * does not apply when using high performance (position:fixed means on-screen), OR infinite flash load timeout
+ * wmode breaks IE 8 on Vista + Win7 too in some cases, as of January 2011 (?)
+ */
+ _wDS('spcWmode');
+ _s.wmode = null;
+ }
+
+ oEmbed = {
+ 'name': smID,
+ 'id': smID,
+ 'src': smURL,
+ 'quality': 'high',
+ 'allowScriptAccess': _s.allowScriptAccess,
+ 'bgcolor': _s.bgColor,
+ 'pluginspage': _http+'www.macromedia.com/go/getflashplayer',
+ 'title': swfTitle,
+ 'type': 'application/x-shockwave-flash',
+ 'wmode': _s.wmode,
+ // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
+ 'hasPriority': 'true'
+ };
+
+ if (_s.debugFlash) {
+ oEmbed.FlashVars = 'debug=1';
+ }
+
+ if (!_s.wmode) {
+ // don't write empty attribute
+ delete oEmbed.wmode;
+ }
+
+ if (_isIE) {
+
+ // IE is "special".
+ oMovie = _doc.createElement('div');
+ movieHTML = [
+ '<object id="' + smID + '" data="' + smURL + '" type="' + oEmbed.type + '" title="' + oEmbed.title +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + _http+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">',
+ param('movie', smURL),
+ param('AllowScriptAccess', _s.allowScriptAccess),
+ param('quality', oEmbed.quality),
+ (_s.wmode? param('wmode', _s.wmode): ''),
+ param('bgcolor', _s.bgColor),
+ param('hasPriority', 'true'),
+ (_s.debugFlash ? param('FlashVars', oEmbed.FlashVars) : ''),
+ '</object>'
+ ].join('');
+
+ } else {
+
+ oMovie = _doc.createElement('embed');
+ for (tmp in oEmbed) {
+ if (oEmbed.hasOwnProperty(tmp)) {
+ oMovie.setAttribute(tmp, oEmbed[tmp]);
+ }
+ }
+
+ }
+
+ _initDebug();
+ extraClass = _getSWFCSS();
+ oTarget = _getDocument();
+
+ if (oTarget) {
+
+ _s.oMC = (_id(_s.movieID) || _doc.createElement('div'));
+
+ if (!_s.oMC.id) {
+
+ _s.oMC.id = _s.movieID;
+ _s.oMC.className = _swfCSS.swfDefault + ' ' + extraClass;
+ s = null;
+ oEl = null;
+
+ if (!_s.useFlashBlock) {
+ if (_s.useHighPerformance) {
+ // on-screen at all times
+ s = {
+ 'position': 'fixed',
+ 'width': '8px',
+ 'height': '8px',
+ // >= 6px for flash to run fast, >= 8px to start up under Firefox/win32 in some cases. odd? yes.
+ 'bottom': '0px',
+ 'left': '0px',
+ 'overflow': 'hidden'
+ };
+ } else {
+ // hide off-screen, lower priority
+ s = {
+ 'position': 'absolute',
+ 'width': '6px',
+ 'height': '6px',
+ 'top': '-9999px',
+ 'left': '-9999px'
+ };
+ if (isRTL) {
+ s.left = Math.abs(parseInt(s.left,10))+'px';
+ }
+ }
}
- if (!_t.instanceCount || _t._iO.multiShotEvents) {
- // fire onfinish for last, or every instance
- if (_t._iO.onfinish) {
- _s._wD('SMSound._onfinish(): "'+_t.sID+'"');
- _t._iO.onfinish.apply(_t);
+
+ if (_isWebkit) {
+ // soundcloud-reported render/crash fix, safari 5
+ _s.oMC.style.zIndex = 10000;
+ }
+
+ if (!_s.debugFlash) {
+ for (x in s) {
+ if (s.hasOwnProperty(x)) {
+ _s.oMC.style[x] = s[x];
+ }
+ }
+ }
+
+ try {
+ if (!_isIE) {
+ _s.oMC.appendChild(oMovie);
+ }
+ oTarget.appendChild(_s.oMC);
+ if (_isIE) {
+ oEl = _s.oMC.appendChild(_doc.createElement('div'));
+ oEl.className = _swfCSS.swfBox;
+ oEl.innerHTML = movieHTML;
}
+ _appendSuccess = true;
+ } catch(e) {
+ throw new Error(_str('domError')+' \n'+e.toString());
}
+
} else {
- if (_t.useVideo) {
- // video has finished
- // may need to reset position for next play call, "rewind"
- // _t.setPosition(0);
+
+ // SM2 container is already in the document (eg. flashblock use case)
+ sClass = _s.oMC.className;
+ _s.oMC.className = (sClass?sClass+' ':_swfCSS.swfDefault) + (extraClass?' '+extraClass:'');
+ _s.oMC.appendChild(oMovie);
+ if (_isIE) {
+ oEl = _s.oMC.appendChild(_doc.createElement('div'));
+ oEl.className = _swfCSS.swfBox;
+ oEl.innerHTML = movieHTML;
}
- // _t.setPosition(0);
+ _appendSuccess = true;
+
}
- };
+ }
- this._onmetadata = function(oMetaData) {
- // movieStar mode only
- var fN = 'SMSound.onmetadata()';
- _s._wD(fN);
- // Contains a subset of metadata. Note that files may have their own unique metadata.
- // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html
- if (!oMetaData.width && !oMetaData.height) {
- _s._wDS('noWH');
- oMetaData.width = 320;
- oMetaData.height = 240;
- }
- _t.metadata = oMetaData; // potentially-large object from flash
- _t.width = oMetaData.width;
- _t.height = oMetaData.height;
- if (_t._iO.onmetadata) {
- _s._wD(fN+': "'+_t.sID+'"');
- _t._iO.onmetadata.apply(_t);
+ _didAppend = true;
+ _initMsg();
+ _s._wD(_smc+'createMovie(): Trying to load ' + smURL + (!_overHTTP && _s.altURL?' (alternate URL)':''), 1);
+
+ return true;
+
+ };
+
+ _initMovie = function() {
+
+ if (_s.html5Only) {
+ _createMovie();
+ return false;
+ }
+
+ // attempt to get, or create, movie
+ // may already exist
+ if (_flash) {
+ return false;
+ }
+
+ // inline markup case
+ _flash = _s.getMovie(_s.id);
+
+ if (!_flash) {
+ if (!_oRemoved) {
+ // try to create
+ _createMovie(_s.id, _s.url);
+ } else {
+ // try to re-append removed movie after reboot()
+ if (!_isIE) {
+ _s.oMC.appendChild(_oRemoved);
+ } else {
+ _s.oMC.innerHTML = _oRemovedHTML;
+ }
+ _oRemoved = null;
+ _didAppend = true;
}
- _s._wD(fN+' complete');
- };
+ _flash = _s.getMovie(_s.id);
+ }
- this._onbufferchange = function(bIsBuffering) {
- var fN = 'SMSound._onbufferchange()';
- if (_t.playState === 0) {
- // ignore if not playing
- return false;
+ // <d>
+ if (_flash) {
+ _wDS('waitEI');
+ }
+ // </d>
+
+ if (typeof _s.oninitmovie === 'function') {
+ setTimeout(_s.oninitmovie, 1);
+ }
+
+ return true;
+
+ };
+
+ _delayWaitForEI = function() {
+
+ setTimeout(_waitForEI, 1000);
+
+ };
+
+ _waitForEI = function() {
+
+ var p,
+ loadIncomplete = false;
+
+ if (_waitingForEI) {
+ return false;
+ }
+
+ _waitingForEI = true;
+ _event.remove(_win, 'load', _delayWaitForEI);
+
+ if (_tryInitOnFocus && !_isFocused) {
+ // Safari won't load flash in background tabs, only when focused.
+ _wDS('waitFocus');
+ return false;
+ }
+
+ if (!_didInit) {
+ p = _s.getMoviePercent();
+ _s._wD(_str('waitImpatient', (p > 0 ? ' (SWF ' + p + '% loaded)' : '')));
+ if (p > 0 && p < 100) {
+ loadIncomplete = true;
}
- if (bIsBuffering == _t.isBuffering) {
- // ignore initial "false" default, if matching
- _s._wD(fN+': ignoring false default / loaded sound');
+ }
+
+ setTimeout(function() {
+
+ p = _s.getMoviePercent();
+
+ if (loadIncomplete) {
+ // special case: if movie *partially* loaded, retry until it's 100% before assuming failure.
+ _waitingForEI = false;
+ _s._wD(_str('waitSWF'));
+ _win.setTimeout(_delayWaitForEI, 1);
return false;
}
- _t.isBuffering = (bIsBuffering == 1?true:false);
- if (_t._iO.onbufferchange) {
- _s._wD(fN+': '+bIsBuffering);
- _t._iO.onbufferchange.apply(_t);
+
+ // <d>
+ if (!_didInit) {
+ _s._wD(_sm + ': No Flash response within expected time.\nLikely causes: ' + (p === 0?'Loading ' + _s.movieURL + ' may have failed (and/or Flash ' + _fV + '+ not present?), ':'') + 'Flash blocked or JS-Flash security error.' + (_s.debugFlash?' ' + _str('checkSWF'):''), 2);
+ if (!_overHTTP && p) {
+ _wDS('localFail', 2);
+ if (!_s.debugFlash) {
+ _wDS('tryDebug', 2);
+ }
+ }
+ if (p === 0) {
+ // if 0 (not null), probably a 404.
+ _s._wD(_str('swf404', _s.url));
+ }
+ _debugTS('flashtojs', false, ': Timed out' + _overHTTP?' (Check flash security or flash blockers)':' (No plugin/missing SWF?)');
}
- };
+ // </d>
- this._ondataerror = function(sError) {
- // flash 9 wave/eq data handler
- if (_t.playState > 0) { // hack: called at start, and end from flash at/after onfinish().
- _s._wD('SMSound._ondataerror(): '+sError);
- if (_t._iO.ondataerror) {
- _t._iO.ondataerror.apply(_t);
+ // give up / time-out, depending
+
+ if (!_didInit && _okToDisable) {
+ if (p === null) {
+ // SWF failed. Maybe blocked.
+ if (_s.useFlashBlock || _s.flashLoadTimeout === 0) {
+ if (_s.useFlashBlock) {
+ _flashBlockHandler();
+ }
+ _wDS('waitForever');
+ } else {
+ // old SM2 behaviour, simply fail
+ _failSafely(true);
+ }
+ } else {
+ // flash loaded? Shouldn't be a blocking issue, then.
+ if (_s.flashLoadTimeout === 0) {
+ _wDS('waitForever');
+ } else {
+ _failSafely(true);
+ }
+ }
+ }
+
+ }, _s.flashLoadTimeout);
+
+ };
+
+ _handleFocus = function() {
+
+ function cleanup() {
+ _event.remove(_win, 'focus', _handleFocus);
+ }
+
+ if (_isFocused || !_tryInitOnFocus) {
+ // already focused, or not special Safari background tab case
+ cleanup();
+ return true;
+ }
+
+ _okToDisable = true;
+ _isFocused = true;
+ _s._wD(_sm+': Got window focus.');
+
+ // allow init to restart
+ _waitingForEI = false;
+
+ // kick off ExternalInterface timeout, now that the SWF has started
+ _delayWaitForEI();
+
+ cleanup();
+ return true;
+
+ };
+
+ _showSupport = function() {
+
+ var item, tests = [];
+
+ if (_s.useHTML5Audio && _s.hasHTML5) {
+ for (item in _s.audioFormats) {
+ if (_s.audioFormats.hasOwnProperty(item)) {
+ tests.push(item + ': ' + _s.html5[item] + (!_s.html5[item] && _hasFlash && _s.flash[item] ? ' (using flash)' : (_s.preferFlash && _s.flash[item] && _hasFlash ? ' (preferring flash)': (!_s.html5[item] ? ' (' + (_s.audioFormats[item].required ? 'required, ':'') + 'and no flash support)' : ''))));
}
+ }
+ _s._wD('-- SoundManager 2: HTML5 support tests ('+_s.html5Test+'): '+tests.join(', ')+' --',1);
+ }
+
+ };
+
+ _initComplete = function(bNoDisable) {
+
+ if (_didInit) {
+ return false;
+ }
+
+ if (_s.html5Only) {
+ // all good.
+ _s._wD('-- SoundManager 2: loaded --');
+ _didInit = true;
+ _initUserOnload();
+ _debugTS('onload', true);
+ return true;
+ }
+
+ var wasTimeout = (_s.useFlashBlock && _s.flashLoadTimeout && !_s.getMoviePercent()),
+ result = true,
+ error;
+
+ if (!wasTimeout) {
+ _didInit = true;
+ if (_disabled) {
+ error = {type: (!_hasFlash && _needsFlash ? 'NO_FLASH' : 'INIT_TIMEOUT')};
+ }
+ }
+
+ _s._wD('-- SoundManager 2 ' + (_disabled?'failed to load':'loaded') + ' (' + (_disabled?'security/load error':'OK') + ') --', 1);
+
+ if (_disabled || bNoDisable) {
+ if (_s.useFlashBlock && _s.oMC) {
+ _s.oMC.className = _getSWFCSS() + ' ' + (_s.getMoviePercent() === null?_swfCSS.swfTimedout:_swfCSS.swfError);
+ }
+ _processOnEvents({type:'ontimeout', error:error, ignoreInit: true});
+ _debugTS('onload', false);
+ _catchError(error);
+ result = false;
+ } else {
+ _debugTS('onload', true);
+ }
+
+ if (!_disabled) {
+ if (_s.waitForWindowLoad && !_windowLoaded) {
+ _wDS('waitOnload');
+ _event.add(_win, 'load', _initUserOnload);
} else {
- // _s._wD('SMSound._ondataerror(): ignoring');
+ // <d>
+ if (_s.waitForWindowLoad && _windowLoaded) {
+ _wDS('docLoaded');
+ }
+ // </d>
+ _initUserOnload();
}
- };
+ }
- }; // SMSound()
+ return result;
- this._onfullscreenchange = function(bFullScreen) {
- _s._wD('onfullscreenchange(): '+bFullScreen);
- _s.isFullScreen = (bFullScreen == 1?true:false);
- if (!_s.isFullScreen) {
- // attempt to restore window focus after leaving full-screen
- try {
- window.focus();
- _s._wD('window.focus()');
- } catch(e) {
- // oh well
+ };
+
+ /**
+ * apply top-level setupOptions object as local properties, eg., this.setupOptions.flashVersion -> this.flashVersion (soundManager.flashVersion)
+ * this maintains backward compatibility, and allows properties to be defined separately for use by soundManager.setup().
+ */
+
+ _setProperties = function() {
+
+ var i,
+ o = _s.setupOptions;
+
+ for (i in o) {
+
+ if (o.hasOwnProperty(i)) {
+
+ // assign local property if not already defined
+
+ if (typeof _s[i] === 'undefined') {
+
+ _s[i] = o[i];
+
+ } else if (_s[i] !== o[i]) {
+
+ // legacy support: write manually-assigned property (eg., soundManager.url) back to setupOptions to keep things in sync
+ _s.setupOptions[i] = _s[i];
+
+ }
+
+ }
+
+ }
+
+ };
+
+
+ _init = function() {
+
+ _wDS('init');
+
+ // called after onload()
+
+ if (_didInit) {
+ _wDS('didInit');
+ return false;
+ }
+
+ function _cleanup() {
+ _event.remove(_win, 'load', _s.beginDelayedInit);
+ }
+
+ if (_s.html5Only) {
+ if (!_didInit) {
+ // we don't need no steenking flash!
+ _cleanup();
+ _s.enabled = true;
+ _initComplete();
+ }
+ return true;
+ }
+
+ // flash path
+ _initMovie();
+
+ try {
+
+ _wDS('flashJS');
+
+ // attempt to talk to Flash
+ _flash._externalInterfaceTest(false);
+
+ // apply user-specified polling interval, OR, if "high performance" set, faster vs. default polling
+ // (determines frequency of whileloading/whileplaying callbacks, effectively driving UI framerates)
+ _setPolling(true, (_s.flashPollingInterval || (_s.useHighPerformance ? 10 : 50)));
+
+ if (!_s.debugMode) {
+ // stop the SWF from making debug output calls to JS
+ _flash._disableDebug();
+ }
+
+ _s.enabled = true;
+ _debugTS('jstoflash', true);
+
+ if (!_s.html5Only) {
+ // prevent browser from showing cached page state (or rather, restoring "suspended" page state) via back button, because flash may be dead
+ // http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
+ _event.add(_win, 'unload', _doNothing);
+ }
+
+ } catch(e) {
+
+ _s._wD('js/flash exception: ' + e.toString());
+ _debugTS('jstoflash', false);
+ _catchError({type:'JS_TO_FLASH_EXCEPTION', fatal:true});
+ // don't disable, for reboot()
+ _failSafely(true);
+ _initComplete();
+
+ return false;
+
+ }
+
+ _initComplete();
+
+ // disconnect events
+ _cleanup();
+
+ return true;
+
+ };
+
+ _domContentLoaded = function() {
+
+ if (_didDCLoaded) {
+ return false;
+ }
+
+ _didDCLoaded = true;
+
+ // assign top-level soundManager properties eg. soundManager.url
+ _setProperties();
+
+ _initDebug();
+
+ /**
+ * Temporary feature: allow force of HTML5 via URL params: sm2-usehtml5audio=0 or 1
+ * Ditto for sm2-preferFlash, too.
+ */
+ // <d>
+ (function(){
+
+ var a = 'sm2-usehtml5audio=',
+ a2 = 'sm2-preferflash=',
+ b = null,
+ b2 = null,
+ hasCon = (typeof console !== 'undefined' && typeof console.log === 'function'),
+ l = _wl.toLowerCase();
+
+ if (l.indexOf(a) !== -1) {
+ b = (l.charAt(l.indexOf(a)+a.length) === '1');
+ if (hasCon) {
+ console.log((b?'Enabling ':'Disabling ')+'useHTML5Audio via URL parameter');
+ }
+ _s.setup({
+ 'useHTML5Audio': b
+ });
}
+
+ if (l.indexOf(a2) !== -1) {
+ b2 = (l.charAt(l.indexOf(a2)+a2.length) === '1');
+ if (hasCon) {
+ console.log((b2?'Enabling ':'Disabling ')+'preferFlash via URL parameter');
+ }
+ _s.setup({
+ 'preferFlash': b2
+ });
+ }
+
+ }());
+ // </d>
+
+ if (!_hasFlash && _s.hasHTML5) {
+ _s._wD('SoundManager: No Flash detected'+(!_s.useHTML5Audio?', enabling HTML5.':'. Trying HTML5-only mode.'));
+ _s.setup({
+ 'useHTML5Audio': true,
+ // make sure we aren't preferring flash, either
+ // TODO: preferFlash should not matter if flash is not installed. Currently, stuff breaks without the below tweak.
+ 'preferFlash': false
+ });
+ }
+
+ _testHTML5();
+ _s.html5.usingFlash = _featureCheck();
+ _needsFlash = _s.html5.usingFlash;
+ _showSupport();
+
+ if (!_hasFlash && _needsFlash) {
+ _s._wD('SoundManager: Fatal error: Flash is needed to play some required formats, but is not available.');
+ // TODO: Fatal here vs. timeout approach, etc.
+ // hack: fail sooner.
+ _s.setup({
+ 'flashLoadTimeout': 1
+ });
+ }
+
+ if (_doc.removeEventListener) {
+ _doc.removeEventListener('DOMContentLoaded', _domContentLoaded, false);
}
+
+ _initMovie();
+ return true;
+
};
- // register a few event handlers
- if (window.addEventListener) {
- window.addEventListener('focus', _s.handleFocus, false);
- window.addEventListener('load', _s.beginDelayedInit, false);
- window.addEventListener('unload', _s.destruct, false);
- if (_s._tryInitOnFocus) {
- window.addEventListener('mousemove', _s.handleFocus, false); // massive Safari focus hack
+ _domContentLoadedIE = function() {
+
+ if (_doc.readyState === 'complete') {
+ _domContentLoaded();
+ _doc.detachEvent('onreadystatechange', _domContentLoadedIE);
}
- } else if (window.attachEvent) {
- window.attachEvent('onfocus', _s.handleFocus);
- window.attachEvent('onload', _s.beginDelayedInit);
- window.attachEvent('unload', _s.destruct);
+
+ return true;
+
+ };
+
+ _winOnLoad = function() {
+ // catch edge case of _initComplete() firing after window.load()
+ _windowLoaded = true;
+ _event.remove(_win, 'load', _winOnLoad);
+ };
+
+ // sniff up-front
+ _detectFlash();
+
+ // focus and window load, init (primarily flash-driven)
+ _event.add(_win, 'focus', _handleFocus);
+ _event.add(_win, 'load', _delayWaitForEI);
+ _event.add(_win, 'load', _winOnLoad);
+
+ if (_doc.addEventListener) {
+
+ _doc.addEventListener('DOMContentLoaded', _domContentLoaded, false);
+
+ } else if (_doc.attachEvent) {
+
+ _doc.attachEvent('onreadystatechange', _domContentLoadedIE);
+
} else {
- // no add/attachevent support - safe to assume no JS -> Flash either.
- _s._debugTS('onload', false);
- soundManager.onerror();
- soundManager.disable();
+
+ // no add/attachevent support - safe to assume no JS -> Flash either
+ _debugTS('onload', false);
+ _catchError({type:'NO_DOM2_EVENTS', fatal:true});
+
}
- if (document.addEventListener) {
- document.addEventListener('DOMContentLoaded', _s.domContentLoaded, false);
+ if (_doc.readyState === 'complete') {
+ // DOMReady has already happened.
+ setTimeout(_domContentLoaded,100);
}
} // SoundManager()
-// var SM2_DEFER = true; // un-comment or define in your own script to prevent immediate SoundManager() constructor call+start-up.
-// if deferring, construct later with window.soundManager = new SoundManager(); followed by soundManager.beginDelayedInit();
+// SM2_DEFER details: http://www.schillmania.com/projects/soundmanager2/doc/getstarted/#lazy-loading
-if (typeof SM2_DEFER == 'undefined' || !SM2_DEFER) {
+if (typeof SM2_DEFER === 'undefined' || !SM2_DEFER) {
soundManager = new SoundManager();
- soundManager.beginDelayedInit();
-}
\ No newline at end of file
+}
+
+/**
+ * SoundManager public interfaces
+ * ------------------------------
+ */
+
+window.SoundManager = SoundManager; // constructor
+window.soundManager = soundManager; // public API, flash callbacks etc.
+
+}(window));
\ No newline at end of file
diff --git a/soundmanager2_debug.swf b/soundmanager2_debug.swf
new file mode 100644
index 0000000..4e30adb
Binary files /dev/null and b/soundmanager2_debug.swf differ
|
bjornstar/TumTaster
|
d373e19a60e0d50c78123f1c51c296361e3315e9
|
v0.4.7: Tumblr changed their URL scheme for audio files so I fixed that, and began preparations for safari and opera versions ^^
|
diff --git a/TumTaster-Screenshot.png b/TumTaster-Screenshot.png
deleted file mode 100644
index d47269b..0000000
Binary files a/TumTaster-Screenshot.png and /dev/null differ
diff --git a/TumTaster-Small-Title.png b/TumTaster-Small-Title.png
deleted file mode 100644
index 8e5bb5e..0000000
Binary files a/TumTaster-Small-Title.png and /dev/null differ
diff --git a/config.xml b/config.xml
new file mode 100644
index 0000000..89d6469
--- /dev/null
+++ b/config.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+ version="0.4.7">
+ <name short="TumTaster">TumTaster for Opera</name>
+ <description>An extension that creates download links for the MP3s you see on Tumblr.</description>
+ <author href="http://bjornstar.com"
+ email="[email protected]">Bjorn Stromberg (@bjornstar)</author>
+ <icon src="Icon-64.png"/>
+ <update-description href="http://tumtaster.bjornstar.com/tumtaster.xml"/>
+</widget>
\ No newline at end of file
diff --git a/includes/script.js b/includes/script.js
index 618f0d9..74007c6 100644
--- a/includes/script.js
+++ b/includes/script.js
@@ -1,174 +1,173 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
var settings;
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function loadSettings() {
var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
if (window.location.href.indexOf('show/audio')>0) {
fixaudiopagination();
}
if (checkurl(location.href, settings['listSites'])) {
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
setInterval(taste, 200);
}
});
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
- var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
- song_url = song_url.replace('&logo=soundcloud','');
+ var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11,song_embed[i].getAttribute('src').indexOf('&color=')+13);
- var song_bgcolor = song_url.substring(song_url.length-6);
+ var song_bgcolor = song_url.substr(song_url.indexOf("&color=")+7,6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
- var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
+ var post_id = song_url.match(/audio_file\/([\w\-]+)\/(\d+)\//)[2];
var post_url = 'http://www.tumblr.com/';
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
guaranteesize(song_embed[i],54,0);
// Find the post's URL.
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
post_url = anchors[a].href;
}
}
}
//Remove # anchors...
if (post_url.indexOf('#')>=0) {
post_url = post_url.substring(0,post_url.indexOf('#'));
}
if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
//We check our white list to see if we should add it to the playlist.
var whitelisted = false;
var blacklisted = false;
//Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
var post = document.getElementById('post_'+post_id);
for (itemWhite in settings['listWhite']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
whitelisted = true;
break;
}
}
// If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
if (!whitelisted) {
for (itemBlack in settings['listBlack']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
blacklisted = true;
break;
}
}
}
}
if (!blacklisted) {
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
}
}
last_embed = song_embed.length;
}
function guaranteesize(start_here,at_least_height,at_least_width) {
while(start_here.parentNode!=undefined||start_here.parentNode!=start_here.parentNode) {
if(start_here.parentNode.offsetHeight<at_least_height&&start_here.parentNode.className!="post_content"&&start_here.parentNode.style.getPropertyValue('display')!='none') {
start_here.parentNode.style.height=at_least_height+'px';
}
if(start_here.parentNode.offsetWidth<at_least_width&&start_here.parentNode.className!="post_content"&&start_here.parentNode.style.getPropertyValue('display')!='none') {
start_here.parentNode.style.width=at_least_width+'px';
}
start_here=start_here.parentNode;
}
}
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
loadSettings();
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index 1dd66fe..49fcee9 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,23 @@
{
"name": "TumTaster",
- "version": "0.4.5",
+ "version": "0.4.7",
"description": "An extension that creates download links for the MP3s you see on Tumblr.",
"browser_action": {
"default_icon": "Icon-16.png",
"default_title": "TumTaster",
"popup": "popup.html"
},
"icons": {
"16": "Icon-16.png",
"32": "Icon-32.png",
"48": "Icon-48.png",
"64": "Icon-64.png",
"128": "Icon-128.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "/includes/script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
e7294a6188b4529c0c8247949ad6a075bcbb69f9
|
v0.4.5 fixed an oversight with renamed variables on flash player. Updated options page to include version number and browser name.
|
diff --git a/README b/README
index 7563260..50470e9 100644
--- a/README
+++ b/README
@@ -1,16 +1,18 @@
-ChromeTaster v0.4.3
-By Bjorn Stromberg
+TumTaster v0.4.5
+By Bjorn Stromberg (@bjornstar)
-This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
+This is an extension for Google Chrome that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
+
+v0.4.5 Renamed the extension to TumTaster because Google suddenly decided they didn't like the old name and took down ChromeTaster.
v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
-IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
+IMPORTANT: To get MP3 playback in flash to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
-chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
+chrome-extension:\\nanfbkacbckngfcklahdgfagjlghfbgm\
-I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
+I am working on switching to an HTML5 player, but it's going to take some time. In the mean time, you must add this extension to your flash allow list. And yes, you must use backslashes.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
-
+TumTaster for Google Chrome can be installed here - https://chrome.google.com/webstore/detail/nanfbkacbckngfcklahdgfagjlghfbgm
\ No newline at end of file
diff --git a/background.html b/background.html
index 55482e0..0ce4c41 100644
--- a/background.html
+++ b/background.html
@@ -1,150 +1,150 @@
<html>
<head>
<script type="text/javascript">
var nowplaying = null;
- var defaultSettings = { 'version': '0.4.4', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var defaultSettings = { 'version': '0.4.5', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
chrome.extension.onRequest.addListener(
function(message, sender, sendResponse) {
if (message == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
addSong(message);
sendResponse({});
}
});
function addSong(newSong) {
switch (settings["mp3player"]) {
case "flash":
var mySoundObject = soundManager.createSound({
- id: song.post_url,
- url: song.song_url,
- onloadfailed: function(){playnextsong(song.post_url)},
- onfinish: function(){playnextsong(song.post_url)}
+ id: newSong.post_url,
+ url: newSong.song_url,
+ onloadfailed: function(){playnextsong(newSong.post_url)},
+ onfinish: function(){playnextsong(newSong.post_url)}
});
break;
case "html5":
var newAudio = document.createElement('audio');
newAudio.setAttribute('src', newSong.song_url);
newAudio.setAttribute('id', newSong.post_url);
var jukebox = document.getElementById('Jukebox');
jukebox.appendChild(newAudio);
break;
}
}
function getJukebox() {
var jukebox = document.getElementsByTagName('audio');
return jukebox;
}
function removeSong(rSong) {
var remove_song = document.getElementById(rSong);
remove_song.parentNode.removeChild(remove_song);
}
function playSong(song_url,post_url) {
switch (settings["mp3player"]) {
case "flash":
break;
case "html5":
play_song = document.getElementById(post_url);
play_song.addEventListener('ended',play_song,false);
play_song.play();
pl = getJukebox();
for(var x=0;x<pl.length;x++){
if(pl[x].id!=post_url){
pl[x].pause();
}
}
break;
}
}
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
switch (settings["mp3player"]) {
case "flash":
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
break;
case "html5":
var playlist = document.getElementsByTagName('audio');
for (x in playlist) {
if (playlist[x].src != previous_song && bad_idea == previous_song && next_song == null) {
next_song = playlist[x];
}
bad_idea = playlist[x].song_url;
if (first_song == null) {
first_song = playlist[0].song_url;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*playlist.length+1);
next_song = playlist[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
playlist[x].play();
}
break;
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
if (settings["mp3player"]=="flash") {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "soundmanager2.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
}
</script>
</head>
<body>
<h1>TumTaster</h1>
<div id="Jukebox">
</div>
</body>
</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index cd6965f..1dd66fe 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,22 +1,23 @@
{
"name": "TumTaster",
- "version": "0.4.4",
+ "version": "0.4.5",
"description": "An extension that creates download links for the MP3s you see on Tumblr.",
"browser_action": {
"default_icon": "Icon-16.png",
"default_title": "TumTaster",
"popup": "popup.html"
},
"icons": {
"16": "Icon-16.png",
"32": "Icon-32.png",
"48": "Icon-48.png",
- "64": "Icon-64.png"
+ "64": "Icon-64.png",
+ "128": "Icon-128.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "/includes/script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index dc36b8a..98fdee3 100644
--- a/options.html
+++ b/options.html
@@ -1,205 +1,240 @@
<html>
<head>
<title>Options for TumTaster</title>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
- padding:0 10px;
+ padding:10px 30px 30px 10px;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
color:#4F545A;
+ width:640px;
}
h1{
color:black;
}
+ h2{
+ margin:0;
+ }
+ p{
+ margin:0;
+ }
a{
color:#4F545A;
text-decoration:none;
}
#content{
- background-color:#FFFFFF;
+ background: white;
display: block;
margin: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
padding-top: 5px;
- width: 840px;
+ width: 570px;
-webkit-border-radius: 10px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .46);
}
- #content_top,#content_bottom{
- display: inline;
- height: 25px;
- outline-color: #444;
- outline-style: none;
- outline-width: 0px;
- width: 900px;
+ #repeat_div,#player_div{
+ margin-bottom:25px;
}
#listBlack,#listWhite{
float:left;
- width:300px;
+ width:240px;
margin-bottom:25px;
}
#listSites{
clear:left;
- width:800px;
+ width:540px;
}
#listSites input{
width:400px;
}
+ #version_div{
+ color:#A8B1BA;
+ font: 11px 'Lucida Grande',Verdana,sans-serif;
+ text-align:right;
+ }
+ #browser_span{
+ color:#A8B1BA;
+ font: 11px 'Lucida Grande',Verdana,sans-serif;
+ vertical-align:top;
+ }
</style>
<script type="text/javascript">
- var defaultSettings = { 'version': '0.4.4', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var defaultSettings = { 'version': '0.4.5', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var browser;
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
var cbShuffle = document.getElementById("optionShuffle");
cbShuffle.checked = settings['shuffle'];
var cbRepeat = document.getElementById("optionRepeat");
cbRepeat.checked = settings['repeat'];
var select = document.getElementById("optionMP3Player");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == settings['mp3player']) {
child.selected = "true";
break;
}
}
for (var itemBlack in settings['listBlack']) {
addInput("Black", settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput("White", settings['listWhite'][itemWhite]);
}
for (var itemSites in settings['listSites']) {
addInput("Sites", settings['listSites'][itemSites]);
}
addInput("Black"); //prepare a blank input box.
addInput("White"); //prepare a blank input box.
addInput("Sites"); //prepare a blank input box.
+
+ var version_div = document.getElementById('version_div');
+ version_div.innerHTML = 'v'+defaultSettings['version']; //use default so we're always showing current version regardless of what people have saved.
+
+ if (typeof opera != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = "for Opera™";
+ }
+
+ if (typeof chrome != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = "for Chrome™";
+ }
+
+ if (typeof safari != 'undefined') {
+ var browser_span = document.getElementById('browser_span');
+ browser_span.innerHTML = "for Safari™";
+ }
}
function addInput(whichList, itemValue) {
if (itemValue == undefined) {
itemValue = "";
}
var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
var listDiv = document.getElementById('list'+whichList);
var listAdd = document.getElementById('list'+whichList+'Add');
garbageInput = document.createElement('input');
garbageInput.value = itemValue;
garbageInput.name = 'option'+whichList;
garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
garbageAdd = document.createElement('a');
garbageAdd.href = "#";
garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
garbageAdd.innerHTML = '<img src="'+PNGremove+'" /> ';
garbageLinebreak = document.createElement('br');
listDiv.insertBefore(garbageAdd,listAdd);
listDiv.insertBefore(garbageInput,listAdd);
listDiv.insertBefore(garbageLinebreak,listAdd);
}
function removeInput(garbageWhich) {
var garbageInput = document.getElementById(garbageWhich);
garbageInput.parentNode.removeChild(garbageInput.previousSibling);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
var settings = {};
var cbShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = cbShuffle.checked;
var cbRepeat = document.getElementById('optionRepeat');
settings['repeat'] = cbRepeat.checked;
var selectMP3Player = document.getElementById('optionMP3Player');
settings['mp3player'] = selectMP3Player.children[selectMP3Player.selectedIndex].value;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != "") {
if (garbages[i].name.substring(0,11) == "optionWhite") {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionBlack") {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionSites") {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
<div id="content">
- <div style="width:100%;height:64px;margin-bottom:12px;">
- <img src="Icon-64.png" style="float:left;padding-right:10px;" />
- <h1 style="line-height:64px;">TumTaster Options</h1>
+ <img style="float:left;" src="Icon-64.png">
+ <h1 style="line-height:32px;height:32px;margin-top:16px;">TumTaster Options <span id="browser_span"> </span></h1>
+
+ <div id="shuffle_div">
+ <input type="checkbox" id="optionShuffle" name="optionShuffle" /> <label for="optionShuffle"> Shuffle</label>
+ </div>
+ <div id="repeat_div">
+ <input type="checkbox" id="optionRepeat" name="optionRepeat" /> <label for="optionRepeat"> Repeat</label>
+ </div>
+ <div id="player_div">
+ <label for="optionMP3Player">MP3 Player Method: </label>
+ <select id="optionMP3Player" name="optionMP3Player" />
+ <option value="flash">Flash</option>
+ <option value="html5">HTML5</option>
+ </select>
</div>
- <input type="checkbox" id="optionShuffle" name="optionShuffle" />
- <label for="optionShuffle"> Shuffle</label><br />
- <input type="checkbox" id="optionRepeat" name="optionRepeat" />
- <label for="optionRepeat"> Repeat</label><br /><br />
- <label for="optionMP3Player">MP3 Player Method: </label>
- <select id="optionMP3Player" name="optionMP3Player" />
- <option value="flash">Flash</option>
- <option value="html5">HTML5</option>
- </select><br />
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
<a href="#" onclick="addInput('Black'); return false;" id="listBlackAdd">add</a><br />
</div>
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
<a href="#" onclick="addInput('White'); return false;" id="listWhiteAdd">add</a><br />
</div>
<div id="listSites">
<h2>Site List</h2>
<p>Run ChromeTaster on these sites:</p>
<a href="#" onclick="addInput('Sites'); return false;" id="listSitesAdd">add</a><br />
</div>
<br />
<input onclick="saveOptions()" type="button" value="Save" />
- <input onclick="eraseOptions()" type="button" value="Restore default" />
+ <input onclick="if (confirm('Are you sure you want to restore defaults?')) {eraseOptions();};" type="button" value="Restore default" />
+ <div id="version_div"> </div>
</div>
</body>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
5ad8f715b9ff322948075d02bcf350be5d70ce51
|
v0.4.4: renamed extension to TumTaster by decree from Google. Initial changes to support HTML5. Fixed links to SoundCloud hosted files.
|
diff --git a/Icon-128.png b/Icon-128.png
new file mode 100644
index 0000000..f3fcb11
Binary files /dev/null and b/Icon-128.png differ
diff --git a/tumblr-audio-icon-16.png b/Icon-16.png
similarity index 100%
rename from tumblr-audio-icon-16.png
rename to Icon-16.png
diff --git a/tumblr-audio-icon-32.png b/Icon-32.png
similarity index 100%
rename from tumblr-audio-icon-32.png
rename to Icon-32.png
diff --git a/tumblr-audio-icon-48.png b/Icon-48.png
similarity index 100%
rename from tumblr-audio-icon-48.png
rename to Icon-48.png
diff --git a/tumblr-audio-icon-64.png b/Icon-64.png
similarity index 100%
rename from tumblr-audio-icon-64.png
rename to Icon-64.png
diff --git a/TumTaster-Screenshot.png b/TumTaster-Screenshot.png
new file mode 100644
index 0000000..d47269b
Binary files /dev/null and b/TumTaster-Screenshot.png differ
diff --git a/TumTaster-Small-Title.png b/TumTaster-Small-Title.png
new file mode 100644
index 0000000..8e5bb5e
Binary files /dev/null and b/TumTaster-Small-Title.png differ
diff --git a/background.html b/background.html
index 54ef98b..55482e0 100644
--- a/background.html
+++ b/background.html
@@ -1,74 +1,150 @@
<html>
+<head>
<script type="text/javascript">
- var playlist = new Array();
var nowplaying = null;
- var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var defaultSettings = { 'version': '0.4.4', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
- chrome.extension.onRequest.addListener( // Yes, this is ugly, I know. I'll fix it later.
- function(song, sender, sendResponse) {
- if (song == 'getSettings') {
+ chrome.extension.onRequest.addListener(
+ function(message, sender, sendResponse) {
+ if (message == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
- playlist[song.song_url] = song.post_url;
- var mySoundObject = soundManager.createSound({
- id: song.post_url,
- url: song.song_url,
- onloadfailed: function(){playnextsong(song.post_url)},
- onfinish: function(){playnextsong(song.post_url)}
- });
+ addSong(message);
sendResponse({});
}
});
-
+
+ function addSong(newSong) {
+ switch (settings["mp3player"]) {
+ case "flash":
+ var mySoundObject = soundManager.createSound({
+ id: song.post_url,
+ url: song.song_url,
+ onloadfailed: function(){playnextsong(song.post_url)},
+ onfinish: function(){playnextsong(song.post_url)}
+ });
+ break;
+ case "html5":
+ var newAudio = document.createElement('audio');
+ newAudio.setAttribute('src', newSong.song_url);
+ newAudio.setAttribute('id', newSong.post_url);
+ var jukebox = document.getElementById('Jukebox');
+ jukebox.appendChild(newAudio);
+ break;
+ }
+ }
+
+ function getJukebox() {
+ var jukebox = document.getElementsByTagName('audio');
+ return jukebox;
+ }
+
+ function removeSong(rSong) {
+ var remove_song = document.getElementById(rSong);
+ remove_song.parentNode.removeChild(remove_song);
+ }
+
+ function playSong(song_url,post_url) {
+ switch (settings["mp3player"]) {
+ case "flash":
+
+ break;
+ case "html5":
+ play_song = document.getElementById(post_url);
+ play_song.addEventListener('ended',play_song,false);
+ play_song.play();
+ pl = getJukebox();
+ for(var x=0;x<pl.length;x++){
+ if(pl[x].id!=post_url){
+ pl[x].pause();
+ }
+ }
+ break;
+ }
+ }
+
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
- for (x in soundManager.sounds) {
- if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
- next_song = soundManager.sounds[x].sID;
- }
- bad_idea = soundManager.sounds[x].sID;
- if (first_song == null) {
- first_song = soundManager.sounds[x].sID;
- }
- }
+ switch (settings["mp3player"]) {
+ case "flash":
+ for (x in soundManager.sounds) {
+ if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = soundManager.sounds[x].sID;
+ }
+ bad_idea = soundManager.sounds[x].sID;
+ if (first_song == null) {
+ first_song = soundManager.sounds[x].sID;
+ }
+ }
- if (settings["shuffle"]) {
- var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- next_song = soundManager.soundIDs[s];
- }
-
- if (settings["repeat"] && bad_idea == previous_song) {
- next_song = first_song;
- }
+ if (settings["shuffle"]) {
+ var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ next_song = soundManager.soundIDs[s];
+ }
+
+ if (settings["repeat"] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
- if (next_song != null) {
- var soundNext = soundManager.getSoundById(next_song);
- soundNext.play();
+ if (next_song != null) {
+ var soundNext = soundManager.getSoundById(next_song);
+ soundNext.play();
+ }
+ break;
+ case "html5":
+ var playlist = document.getElementsByTagName('audio');
+ for (x in playlist) {
+ if (playlist[x].src != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = playlist[x];
+ }
+ bad_idea = playlist[x].song_url;
+ if (first_song == null) {
+ first_song = playlist[0].song_url;
+ }
+ }
+
+ if (settings["shuffle"]) {
+ var s = Math.floor(Math.random()*playlist.length+1);
+ next_song = playlist[s];
+ }
+
+ if (settings["repeat"] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
+
+ if (next_song != null) {
+ playlist[x].play();
+ }
+ break;
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
if (settings["mp3player"]=="flash") {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "soundmanager2.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
}
-
</script>
-<h1>ChromeTaster</h1>
+</head>
+<body>
+<h1>TumTaster</h1>
+<div id="Jukebox">
+</div>
+</body>
</html>
\ No newline at end of file
diff --git a/content_bg.png b/content_bg.png
deleted file mode 100644
index 4e831ab..0000000
Binary files a/content_bg.png and /dev/null differ
diff --git a/content_bottom.png b/content_bottom.png
deleted file mode 100644
index 61b096d..0000000
Binary files a/content_bottom.png and /dev/null differ
diff --git a/content_top.png b/content_top.png
deleted file mode 100644
index 587afd7..0000000
Binary files a/content_top.png and /dev/null differ
diff --git a/script.js b/includes/script.js
similarity index 87%
rename from script.js
rename to includes/script.js
index 3c48418..618f0d9 100644
--- a/script.js
+++ b/includes/script.js
@@ -1,167 +1,174 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
-try {
- document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
-} catch (e) {
- addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
-}
-
var settings;
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function loadSettings() {
var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
if (window.location.href.indexOf('show/audio')>0) {
fixaudiopagination();
}
if (checkurl(location.href, settings['listSites'])) {
+ try {
+ document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
+ } catch (e) {
+ addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
+ }
setInterval(taste, 200);
}
});
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
+ song_url = song_url.replace('&logo=soundcloud','');
+
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
+
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
-
- if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
+
+ if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
var post_url = 'http://www.tumblr.com/';
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
- guaranteeheight(song_embed[i],54);
+ guaranteesize(song_embed[i],54,0);
// Find the post's URL.
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
post_url = anchors[a].href;
}
}
}
//Remove # anchors...
if (post_url.indexOf('#')>=0) {
post_url = post_url.substring(0,post_url.indexOf('#'));
}
if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
//We check our white list to see if we should add it to the playlist.
var whitelisted = false;
var blacklisted = false;
//Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
var post = document.getElementById('post_'+post_id);
for (itemWhite in settings['listWhite']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
whitelisted = true;
break;
}
}
// If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
if (!whitelisted) {
for (itemBlack in settings['listBlack']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
blacklisted = true;
break;
}
}
}
}
if (!blacklisted) {
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
}
}
last_embed = song_embed.length;
}
-function guaranteeheight(start_here,at_least) {
+function guaranteesize(start_here,at_least_height,at_least_width) {
while(start_here.parentNode!=undefined||start_here.parentNode!=start_here.parentNode) {
- if(start_here.parentNode.offsetHeight<at_least) {
- start_here.parentNode.style.height=at_least+'px';
+ if(start_here.parentNode.offsetHeight<at_least_height&&start_here.parentNode.className!="post_content"&&start_here.parentNode.style.getPropertyValue('display')!='none') {
+ start_here.parentNode.style.height=at_least_height+'px';
+ }
+ if(start_here.parentNode.offsetWidth<at_least_width&&start_here.parentNode.className!="post_content"&&start_here.parentNode.style.getPropertyValue('display')!='none') {
+ start_here.parentNode.style.width=at_least_width+'px';
}
start_here=start_here.parentNode;
}
}
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
+
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
+
}
loadSettings();
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index 08a02c1..cd6965f 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,22 +1,22 @@
{
- "name": "ChromeTaster",
- "version": "0.4.3",
- "description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
+ "name": "TumTaster",
+ "version": "0.4.4",
+ "description": "An extension that creates download links for the MP3s you see on Tumblr.",
"browser_action": {
- "default_icon": "tumblr-audio-icon-16.png",
- "default_title": "ChromeTaster",
+ "default_icon": "Icon-16.png",
+ "default_title": "TumTaster",
"popup": "popup.html"
},
"icons": {
- "16": "tumblr-audio-icon-16.png",
- "32": "tumblr-audio-icon-32.png",
- "48": "tumblr-audio-icon-48.png",
- "64": "tumblr-audio-icon-64.png"
+ "16": "Icon-16.png",
+ "32": "Icon-32.png",
+ "48": "Icon-48.png",
+ "64": "Icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
- "js": [ "script.js" ],
+ "js": [ "/includes/script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 7abce2a..dc36b8a 100644
--- a/options.html
+++ b/options.html
@@ -1,203 +1,205 @@
<html>
<head>
- <title>Options for ChromeTaster</title>
+ <title>Options for TumTaster</title>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0 10px;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
color:#4F545A;
}
h1{
color:black;
}
a{
color:#4F545A;
text-decoration:none;
}
#content{
- background: white url(content_bg.png) repeat-y;
+ background-color:#FFFFFF;
display: block;
margin: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
padding-top: 5px;
width: 840px;
+ -webkit-border-radius: 10px;
+ -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .46);
}
#content_top,#content_bottom{
display: inline;
height: 25px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
width: 900px;
}
#listBlack,#listWhite{
float:left;
width:300px;
margin-bottom:25px;
}
#listSites{
clear:left;
width:800px;
}
#listSites input{
width:400px;
}
</style>
<script type="text/javascript">
- var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var defaultSettings = { 'version': '0.4.4', 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
var cbShuffle = document.getElementById("optionShuffle");
cbShuffle.checked = settings['shuffle'];
var cbRepeat = document.getElementById("optionRepeat");
cbRepeat.checked = settings['repeat'];
var select = document.getElementById("optionMP3Player");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == settings['mp3player']) {
child.selected = "true";
break;
}
}
for (var itemBlack in settings['listBlack']) {
addInput("Black", settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput("White", settings['listWhite'][itemWhite]);
}
for (var itemSites in settings['listSites']) {
addInput("Sites", settings['listSites'][itemSites]);
}
addInput("Black"); //prepare a blank input box.
addInput("White"); //prepare a blank input box.
addInput("Sites"); //prepare a blank input box.
}
function addInput(whichList, itemValue) {
if (itemValue == undefined) {
itemValue = "";
}
+
+ var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
var listDiv = document.getElementById('list'+whichList);
var listAdd = document.getElementById('list'+whichList+'Add');
garbageInput = document.createElement('input');
garbageInput.value = itemValue;
garbageInput.name = 'option'+whichList;
garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
garbageAdd = document.createElement('a');
garbageAdd.href = "#";
garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
- garbageAdd.innerHTML = '<img src="x_7x7.png" /> ';
+ garbageAdd.innerHTML = '<img src="'+PNGremove+'" /> ';
garbageLinebreak = document.createElement('br');
listDiv.insertBefore(garbageAdd,listAdd);
listDiv.insertBefore(garbageInput,listAdd);
listDiv.insertBefore(garbageLinebreak,listAdd);
}
function removeInput(garbageWhich) {
var garbageInput = document.getElementById(garbageWhich);
garbageInput.parentNode.removeChild(garbageInput.previousSibling);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
var settings = {};
var cbShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = cbShuffle.checked;
var cbRepeat = document.getElementById('optionRepeat');
settings['repeat'] = cbRepeat.checked;
var selectMP3Player = document.getElementById('optionMP3Player');
settings['mp3player'] = selectMP3Player.children[selectMP3Player.selectedIndex].value;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != "") {
if (garbages[i].name.substring(0,11) == "optionWhite") {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionBlack") {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionSites") {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
- <div style="width:100%;height:64px;margin-bottom:12px;">
- <img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
- <h1 style="line-height:64px;">ChromeTaster Options</h1>
- </div>
- <img src="content_top.png?alpha" alt="" id="content_top">
<div id="content">
+ <div style="width:100%;height:64px;margin-bottom:12px;">
+ <img src="Icon-64.png" style="float:left;padding-right:10px;" />
+ <h1 style="line-height:64px;">TumTaster Options</h1>
+ </div>
<input type="checkbox" id="optionShuffle" name="optionShuffle" />
<label for="optionShuffle"> Shuffle</label><br />
<input type="checkbox" id="optionRepeat" name="optionRepeat" />
<label for="optionRepeat"> Repeat</label><br /><br />
<label for="optionMP3Player">MP3 Player Method: </label>
<select id="optionMP3Player" name="optionMP3Player" />
<option value="flash">Flash</option>
<option value="html5">HTML5</option>
</select><br />
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
<a href="#" onclick="addInput('Black'); return false;" id="listBlackAdd">add</a><br />
</div>
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
<a href="#" onclick="addInput('White'); return false;" id="listWhiteAdd">add</a><br />
</div>
<div id="listSites">
<h2>Site List</h2>
<p>Run ChromeTaster on these sites:</p>
<a href="#" onclick="addInput('Sites'); return false;" id="listSitesAdd">add</a><br />
</div>
<br />
<input onclick="saveOptions()" type="button" value="Save" />
<input onclick="eraseOptions()" type="button" value="Restore default" />
</div>
- <img src="content_bottom.png" alt="" id="content_bottom">
</body>
</html>
\ No newline at end of file
diff --git a/popup.html b/popup.html
index 29f2701..0baae99 100644
--- a/popup.html
+++ b/popup.html
@@ -1,273 +1,331 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a{
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
div#heading h1{
color: white;
float: left;
line-height:32px;
vertical-align:absmiddle;
margin-left:10px;
}
div#statistics{
position:absolute;
bottom:0%;
}
#controls{
text-align:center;
}
-#statusbar{
-position:relative;
-height:12px;
-background-color:#CDD568;
-border:2px solid #eaf839;
-border-radius:2px;
--moz-border-radius:2px;
--webkit-border-radius:2px;
-overflow:hidden;
-margin-top:4px;
-}
+ #statusbar{
+ position:relative;
+ height:12px;
+ background-color:#CDD568;
+ border:2px solid #eaf839;
+ border-radius:2px;
+ -moz-border-radius:2px;
+ -webkit-border-radius:2px;
+ overflow:hidden;
+ margin-top:4px;
+ }
-.remove{
-position:absolute;
-right:8px;
-top:8px;
-}
+ .remove{
+ position:absolute;
+ right:8px;
+ top:8px;
+ }
-.position, .position2, .loading{
-position:absolute;
-left:0px;
-bottom:0px;
-height:12px;
-}
-.position{
-background-color: #3B440F;
-border-right:2px solid #3B440F;
-border-radius:2px;
--moz-border-radius:2px;
--webkit-border-radius:2px;
-}
-.position2{
-background-color:#eaf839;
-}
-.loading {
-background-color:#BBC552;
-}
+ .position, .position2, .loading{
+ position:absolute;
+ left:0px;
+ bottom:0px;
+ height:12px;
+ }
+ .position{
+ background-color: #3B440F;
+ border-right:2px solid #3B440F;
+ border-radius:2px;
+ -moz-border-radius:2px;
+ -webkit-border-radius:2px;
+ width:20px;
+ }
+ .position2{
+ background-color:#eaf839;
+ }
+
+ .loading {
+ background-color:#BBC552;
+ }
</style>
-<div id="heading" style="width:100%;height:64px;"><img src="tumblr-audio-icon-64.png" style="float:left;" /><h1>ChromeTaster</h1></div>
+<div id="heading" style="width:100%;height:64px;"><img src="Icon-64.png" style="float:left;" /><h1>TumTaster</h1></div>
<div id="statistics"><span> </span></div>
<div id="nowplayingdiv"><span id="nowplaying">Now Playing: </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
-<p id="controls"><a href="javascript:void(sm.stopAll())">■</a> <a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
+<p id="controls">
+<a href="javascript:void(sm.stopAll())">■</a>
+<a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
-var pl = sm.sounds;
function remove(song_id) {
- sm.destroySound(song_id);
- var song_li = document.getElementById(song_id);
- song_li.parentNode.removeChild(song_li);
+ switch (bg.settings["mp3player"]) {
+ case "flash":
+ sm.destroySound(song_id);
+ var song_li = document.getElementById(song_id);
+ song_li.parentNode.removeChild(song_li);
+ break;
+ case "html5":
+ bg.removeSong(song_id);
+ var song_li = document.getElementById(song_id);
+ song_li.parentNode.removeChild(song_li);
+ break;
+ }
}
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
- sm.stopAll();
- var mySoundObject = sm.getSoundById(post_url);
- mySoundObject.play();
- update_nowplaying();
+ switch (bg.settings["mp3player"]) {
+ case "flash":
+ sm.stopAll();
+ var mySoundObject = sm.getSoundById(post_url);
+ mySoundObject.play();
+ update_nowplaying();
+ break;
+ case "html5":
+ bg.playSong(song_url,post_url);
+ update_nowplaying();
+ break;
+ }
}
function get_currentsong() {
var song_nowplaying = null;
- for (sound in sm.sounds) {
- if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
- song_nowplaying = sm.sounds[sound];
- }
- }
+ switch (bg.settings["mp3player"]){
+ case "flash":
+ for (sound in sm.sounds) {
+ if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
+ song_nowplaying = sm.sounds[sound];
+ }
+ }
+ break;
+ case "html5":
+ var pl = bg.getJukebox();
+ for (var x=0;x<pl.length;x++) {
+ if (pl[x].currentTime<pl[x].duration && pl[x].currentTime>0 && !pl[x].paused) {
+ song_nowplaying = pl[x];
+ }
+ }
+ break;
+ }
return song_nowplaying;
}
function update_nowplaying() {
var current_song = get_currentsong();
if (current_song) {
var nowplaying = document.getElementById('nowplaying');
- nowplaying.innerHTML = 'Now Playing: '+current_song.sID;
+ nowplaying.innerHTML = 'Now Playing: '+current_song.id;
}
}
function update_statistics() {
var count_songs = 0;
count_songs = sm.soundIDs.length;
var statistics = document.getElementById('statistics');
//statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
}
function playnextsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playnextsong(current_song_sID);
update_nowplaying();
}
function playrandomsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
update_nowplaying();
}
-update_nowplaying();
-update_statistics();
-
document.write('<ol class="playlist">');
-for (x in pl) {
- document.write('<li id="'+pl[x].sID+'"><a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a><a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="x_7x7.png" /></a></li>\r\n');
+
+var PNGremove = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGFJREFUeNpiXLVmfTwDA8MEIHYICwm8COTrA9kHgLiAEch5D2QIAPEHkABUIZjPBNIBlQAJLEBS6MAEMgqqAxkUgMQZkewQQJKE6ESSAAkkIFlxgAlq5AeoaxciuaEAIMAAiDAi7M96B5wAAAAASUVORK5CYII=';
+
+switch (bg.settings["mp3player"]) {
+ case "flash":
+ var pl = sm.sounds;
+ for (x in pl) {
+ document.write('<li id="'+pl[x].sID+'">');
+ document.write('<a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a>');
+ document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
+ }
+ document.write('</ol>');
+ break;
+ case "html5":
+ var pl = bg.getJukebox();
+ for (x in pl) {
+ if (pl[x].id!=undefined) {
+ document.write('<li id="'+pl[x].id+'">');
+ document.write('<a href="javascript:void(play(\''+pl[x].src+'\',\''+pl[x].id+'\'))">'+pl[x].id+'</a>');
+ document.write('<a class="remove" href="javascript:void(remove(\''+pl[x].id+'\'))"><img src="'+PNGremove+'" /></a></li>\r\n');
+ }
+ }
+ break;
}
+
document.write('</ol>');
var div_loading = document.getElementById('loading');
var div_position = document.getElementById('position');
var div_position2 = document.getElementById('position2');
function updateStatus() {
var current_song = get_currentsong();
if (current_song != undefined) {
- if (current_song.bytesTotal > 0) {
- div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
- }
- div_position.style.width = "20px";
- div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
- div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
+ switch(bg.settings["mp3player"]) {
+ case "flash":
+ if (current_song.bytesTotal > 0) {
+ div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
+ }
+ div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
+ div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
+ break;
+ case "html5":
+ div_position.style.left = (100 * current_song.currentTime / current_song.duration) + '%';
+ div_position2.style.width = (100 * current_song.currentTime / current_song.duration) + '%';
+ break;
+ }
}
}
setInterval(updateStatus, 200);
-
+update_nowplaying();
</script>
</html>
\ No newline at end of file
diff --git a/x_7x7.png b/x_7x7.png
deleted file mode 100644
index b93532d..0000000
Binary files a/x_7x7.png and /dev/null differ
|
bjornstar/TumTaster
|
949e82ce80c39e122a5503ddcc16ffced480f42a
|
v0.4.3 - It's settings not localStorage, silly.
|
diff --git a/README b/README
index ff637d8..7563260 100644
--- a/README
+++ b/README
@@ -1,16 +1,16 @@
-ChromeTaster v0.4.2
+ChromeTaster v0.4.3
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/background.html b/background.html
index b24d7a1..54ef98b 100644
--- a/background.html
+++ b/background.html
@@ -1,74 +1,74 @@
<html>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
if (localStorage["settings"] == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(localStorage["settings"]);
}
chrome.extension.onRequest.addListener( // Yes, this is ugly, I know. I'll fix it later.
function(song, sender, sendResponse) {
if (song == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
playlist[song.song_url] = song.post_url;
var mySoundObject = soundManager.createSound({
id: song.post_url,
url: song.song_url,
onloadfailed: function(){playnextsong(song.post_url)},
onfinish: function(){playnextsong(song.post_url)}
});
sendResponse({});
}
});
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
- if (localStorage["mp3player"]=="flash") {
+ if (settings["mp3player"]=="flash") {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "soundmanager2.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
}
</script>
<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index a99745b..08a02c1 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,22 +1,22 @@
{
"name": "ChromeTaster",
- "version": "0.4.2",
+ "version": "0.4.3",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
1ea84698384a47862e60b95e5a5cb36f233217cc
|
v0.3.4 Tumblr modified the layout and broke things. Fixed repeat and shuffle, layed groundwork for html5 option.
|
diff --git a/README b/README
index caf0215..ff637d8 100644
--- a/README
+++ b/README
@@ -1,16 +1,16 @@
-ChromeTaster v0.4.1
+ChromeTaster v0.4.2
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/background.html b/background.html
index 3cb8bd9..b24d7a1 100644
--- a/background.html
+++ b/background.html
@@ -1,61 +1,74 @@
<html>
-<script type="text/javascript" src="soundmanager2.js"></script>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
+ var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ if (localStorage["settings"] == undefined) {
+ settings = defaultSettings;
+ } else {
+ settings = JSON.parse(localStorage["settings"]);
+ }
+
chrome.extension.onRequest.addListener( // Yes, this is ugly, I know. I'll fix it later.
function(song, sender, sendResponse) {
if (song == 'getSettings') {
sendResponse({settings: localStorage["settings"]});
} else {
playlist[song.song_url] = song.post_url;
var mySoundObject = soundManager.createSound({
id: song.post_url,
url: song.song_url,
onloadfailed: function(){playnextsong(song.post_url)},
onfinish: function(){playnextsong(song.post_url)}
});
sendResponse({});
}
});
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
- if (localStorage["shuffle"]) {
+ if (settings["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
- if (localStorage["repeat"] && bad_idea == previous_song) {
+ if (settings["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
-
+
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
-
+
+ if (localStorage["mp3player"]=="flash") {
+ var fileref=document.createElement('script');
+ fileref.setAttribute("type","text/javascript");
+ fileref.setAttribute("src", "soundmanager2.js");
+ document.getElementsByTagName("head")[0].appendChild(fileref);
+ }
+
</script>
<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index d59b0c6..a99745b 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,22 +1,22 @@
{
"name": "ChromeTaster",
- "version": "0.4.1",
+ "version": "0.4.2",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 8dc57e2..7abce2a 100644
--- a/options.html
+++ b/options.html
@@ -1,205 +1,203 @@
<html>
<head>
<title>Options for ChromeTaster</title>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0 10px;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
color:#4F545A;
}
h1{
color:black;
}
a{
color:#4F545A;
text-decoration:none;
}
#content{
background: white url(content_bg.png) repeat-y;
display: block;
margin: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
padding-top: 5px;
width: 840px;
}
#content_top,#content_bottom{
display: inline;
height: 25px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
width: 900px;
}
#listBlack,#listWhite{
float:left;
width:300px;
margin-bottom:25px;
}
#listSites{
clear:left;
width:800px;
}
#listSites input{
width:400px;
}
</style>
<script type="text/javascript">
- var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
- console.log(settings['shuffle']);
- console.log(settings['repeat']);
-
- var select = document.getElementById("optionShuffle");
- for (var i = 0; i < select.children.length; i++) {
- var child = select.children[i];
- if (child.value == settings['shuffle']) {
- child.selected = "true";
- break;
- }
- }
+ var cbShuffle = document.getElementById("optionShuffle");
+ cbShuffle.checked = settings['shuffle'];
- var select = document.getElementById("optionRepeat");
+ var cbRepeat = document.getElementById("optionRepeat");
+ cbRepeat.checked = settings['repeat'];
+
+ var select = document.getElementById("optionMP3Player");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
- if (child.value == settings['repeat']) {
+ if (child.value == settings['mp3player']) {
child.selected = "true";
break;
}
}
for (var itemBlack in settings['listBlack']) {
addInput("Black", settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput("White", settings['listWhite'][itemWhite]);
}
for (var itemSites in settings['listSites']) {
addInput("Sites", settings['listSites'][itemSites]);
}
addInput("Black"); //prepare a blank input box.
addInput("White"); //prepare a blank input box.
addInput("Sites"); //prepare a blank input box.
}
function addInput(whichList, itemValue) {
if (itemValue == undefined) {
itemValue = "";
}
- var garbageTruck = document.getElementById('list'+whichList);
+ var listDiv = document.getElementById('list'+whichList);
+ var listAdd = document.getElementById('list'+whichList+'Add');
+
garbageInput = document.createElement('input');
garbageInput.value = itemValue;
garbageInput.name = 'option'+whichList;
garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
garbageAdd = document.createElement('a');
garbageAdd.href = "#";
garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
garbageAdd.innerHTML = '<img src="x_7x7.png" /> ';
garbageLinebreak = document.createElement('br');
- garbageTruck.appendChild(garbageAdd);
- garbageTruck.appendChild(garbageInput);
- garbageTruck.appendChild(garbageLinebreak);
+ listDiv.insertBefore(garbageAdd,listAdd);
+ listDiv.insertBefore(garbageInput,listAdd);
+ listDiv.insertBefore(garbageLinebreak,listAdd);
}
function removeInput(garbageWhich) {
var garbageInput = document.getElementById(garbageWhich);
garbageInput.parentNode.removeChild(garbageInput.previousSibling);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
var settings = {};
- var selectShuffle = document.getElementById('optionShuffle');
- settings['shuffle'] = selectShuffle.children[selectShuffle.selectedIndex].value;
- var selectRepeat = document.getElementById('optionRepeat');
- settings['repeat'] = selectRepeat.children[selectRepeat.selectedIndex].value;
+ var cbShuffle = document.getElementById('optionShuffle');
+ settings['shuffle'] = cbShuffle.checked;
+
+ var cbRepeat = document.getElementById('optionRepeat');
+ settings['repeat'] = cbRepeat.checked;
+
+ var selectMP3Player = document.getElementById('optionMP3Player');
+ settings['mp3player'] = selectMP3Player.children[selectMP3Player.selectedIndex].value;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != "") {
if (garbages[i].name.substring(0,11) == "optionWhite") {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionBlack") {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionSites") {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
<div style="width:100%;height:64px;margin-bottom:12px;">
<img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
<h1 style="line-height:64px;">ChromeTaster Options</h1>
</div>
<img src="content_top.png?alpha" alt="" id="content_top">
<div id="content">
- <label for="optionShuffle">Shuffle: </label>
- <select id="optionShuffle" name="optionShuffle">
- <option value="false">Off</option>
- <option value="true">On</option>
- </select>
- <label for="optionRepeat">Repeat: </label>
- <select id="optionRepeat" name="optionRepeat">
- <option value="false">Off</option>
- <option value="true">On</option>
- </select>
- <br />
+ <input type="checkbox" id="optionShuffle" name="optionShuffle" />
+ <label for="optionShuffle"> Shuffle</label><br />
+ <input type="checkbox" id="optionRepeat" name="optionRepeat" />
+ <label for="optionRepeat"> Repeat</label><br /><br />
+ <label for="optionMP3Player">MP3 Player Method: </label>
+ <select id="optionMP3Player" name="optionMP3Player" />
+ <option value="flash">Flash</option>
+ <option value="html5">HTML5</option>
+ </select><br />
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
- <a href="#" onclick="addInput('Black'); return false;">add</a><br />
+ <a href="#" onclick="addInput('Black'); return false;" id="listBlackAdd">add</a><br />
</div>
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
- <a href="#" onclick="addInput('White'); return false;">add</a><br />
+ <a href="#" onclick="addInput('White'); return false;" id="listWhiteAdd">add</a><br />
</div>
<div id="listSites">
<h2>Site List</h2>
<p>Run ChromeTaster on these sites:</p>
- <a href="#" onclick="addInput('Sites'); return false;">add</a><br />
+ <a href="#" onclick="addInput('Sites'); return false;" id="listSitesAdd">add</a><br />
</div>
<br />
<input onclick="saveOptions()" type="button" value="Save" />
<input onclick="eraseOptions()" type="button" value="Restore default" />
</div>
<img src="content_bottom.png" alt="" id="content_bottom">
</body>
</html>
\ No newline at end of file
diff --git a/script.js b/script.js
index b932c3f..3c48418 100644
--- a/script.js
+++ b/script.js
@@ -1,154 +1,167 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
var settings;
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function loadSettings() {
- var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
+ var defaultSettings = { 'shuffle': false, 'repeat': true, 'mp3player': 'flash', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
if (window.location.href.indexOf('show/audio')>0) {
fixaudiopagination();
}
if (checkurl(location.href, settings['listSites'])) {
setInterval(taste, 200);
}
});
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
+ var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
+ var post_url = 'http://www.tumblr.com/';
+
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
- song_embed[i].parentNode.style.height='54px';
-
- var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
- var post_url = 'http://www.tumblr.com/';
+ guaranteeheight(song_embed[i],54);
// Find the post's URL.
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
post_url = anchors[a].href;
}
}
}
+ //Remove # anchors...
+ if (post_url.indexOf('#')>=0) {
+ post_url = post_url.substring(0,post_url.indexOf('#'));
+ }
+
if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
//We check our white list to see if we should add it to the playlist.
var whitelisted = false;
var blacklisted = false;
//Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
- var post = document.getElementById('post'+post_id);
+ var post = document.getElementById('post_'+post_id);
for (itemWhite in settings['listWhite']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
whitelisted = true;
break;
}
}
// If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
if (!whitelisted) {
for (itemBlack in settings['listBlack']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
blacklisted = true;
break;
}
}
}
}
-
if (!blacklisted) {
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
}
}
last_embed = song_embed.length;
}
+function guaranteeheight(start_here,at_least) {
+ while(start_here.parentNode!=undefined||start_here.parentNode!=start_here.parentNode) {
+ if(start_here.parentNode.offsetHeight<at_least) {
+ start_here.parentNode.style.height=at_least+'px';
+ }
+ start_here=start_here.parentNode;
+ }
+}
+
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
loadSettings();
\ No newline at end of file
diff --git a/soundmanager2.js b/soundmanager2.js
index e4862cd..8415e40 100644
--- a/soundmanager2.js
+++ b/soundmanager2.js
@@ -1444,513 +1444,514 @@ if (_s.debugMode) {
_t._iO = _s._mergeObjects(oOptions);
_t.instanceOptions = _t._iO;
} else {
oOptions = _t.options;
_t._iO = oOptions;
_t.instanceOptions = _t._iO;
if (_t._lastURL && _t._lastURL != _t.url) {
_s._wDS('manURL');
_t._iO.url = _t.url;
_t.url = null;
}
}
if (typeof _t._iO.url == 'undefined') {
_t._iO.url = _t.url;
}
_s._wD('soundManager.load(): '+_t._iO.url, 1);
if (_t._iO.url == _t.url && _t.readyState !== 0 && _t.readyState != 2) {
_s._wDS('onURL', 1);
return false;
}
_t.url = _t._iO.url;
_t._lastURL = _t._iO.url;
_t.loaded = false;
_t.readyState = 1;
_t.playState = 0; // (oOptions.autoPlay?1:0); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)
try {
if (_s.flashVersion == 8) {
_s.o._load(_t.sID, _t._iO.url, _t._iO.stream, _t._iO.autoPlay, (_t._iO.whileloading?1:0));
} else {
_s.o._load(_t.sID, _t._iO.url, _t._iO.stream?true:false, _t._iO.autoPlay?true:false); // ,(_tO.whileloading?true:false)
if (_t._iO.isMovieStar && _t._iO.autoLoad && !_t._iO.autoPlay) {
// special case: MPEG4 content must start playing to load, then pause to prevent playing.
_t.pause();
}
}
} catch(e) {
_s._wDS('smError', 2);
_s._debugTS('onload', false);
_s.onerror();
_s.disable();
}
};
this.loadfailed = function() {
if (_t._iO.onloadfailed) {
_s._wD('SMSound.onloadfailed(): "'+_t.sID+'"');
_t._iO.onloadfailed.apply(_t);
}
};
this.unload = function() {
// Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3
// Flash 9/AS3: Close stream, preventing further load
if (_t.readyState !== 0) {
_s._wD('SMSound.unload(): "'+_t.sID+'"');
if (_t.readyState != 2) { // reset if not error
_t.setPosition(0, true); // reset current sound positioning
}
_s.o._unload(_t.sID, _s.nullURL);
// reset load/status flags
_t.resetProperties();
}
};
this.destruct = function() {
// kill sound within Flash
_s._wD('SMSound.destruct(): "'+_t.sID+'"');
_s.o._destroySound(_t.sID);
_s.destroySound(_t.sID, true); // ensure deletion from controller
};
this.play = function(oOptions) {
var fN = 'SMSound.play(): ';
if (!oOptions) {
oOptions = {};
}
_t._iO = _s._mergeObjects(oOptions, _t._iO);
_t._iO = _s._mergeObjects(_t._iO, _t.options);
_t.instanceOptions = _t._iO;
if (_t.playState == 1) {
var allowMulti = _t._iO.multiShot;
if (!allowMulti) {
_s._wD(fN+'"'+_t.sID+'" already playing (one-shot)', 1);
return false;
} else {
_s._wD(fN+'"'+_t.sID+'" already playing (multi-shot)', 1);
}
}
if (!_t.loaded) {
if (_t.readyState === 0) {
_s._wD(fN+'Attempting to load "'+_t.sID+'"', 1);
// try to get this sound playing ASAP
//_t._iO.stream = true; // breaks stream=false case?
_t._iO.autoPlay = true;
// TODO: need to investigate when false, double-playing
// if (typeof oOptions.autoPlay=='undefined') _tO.autoPlay = true; // only set autoPlay if unspecified here
_t.load(_t._iO); // try to get this sound playing ASAP
} else if (_t.readyState == 2) {
_s._wD(fN+'Could not load "'+_t.sID+'" - exiting', 2);
return false;
} else {
_s._wD(fN+'"'+_t.sID+'" is loading - attempting to play..', 1);
}
} else {
_s._wD(fN+'"'+_t.sID+'"');
}
if (_t.paused) {
_t.resume();
} else {
_t.playState = 1;
if (!_t.instanceCount || _s.flashVersion > 8) {
_t.instanceCount++;
}
_t.position = (typeof _t._iO.position != 'undefined' && !isNaN(_t._iO.position)?_t._iO.position:0);
if (_t._iO.onplay) {
_t._iO.onplay.apply(_t);
}
_t.setVolume(_t._iO.volume, true); // restrict volume to instance options only
_t.setPan(_t._iO.pan, true);
_s.o._start(_t.sID, _t._iO.loop || 1, (_s.flashVersion == 9?_t.position:_t.position / 1000));
}
};
this.start = this.play; // just for convenience
this.stop = function(bAll) {
if (_t.playState == 1) {
_t.playState = 0;
_t.paused = false;
// if (_s.defaultOptions.onstop) _s.defaultOptions.onstop.apply(_s);
if (_t._iO.onstop) {
_t._iO.onstop.apply(_t);
}
_s.o._stop(_t.sID, bAll);
_t.instanceCount = 0;
_t._iO = {};
// _t.instanceOptions = _t._iO;
}
};
this.setPosition = function(nMsecOffset, bNoDebug) {
if (typeof nMsecOffset == 'undefined') {
nMsecOffset = 0;
}
var offset = Math.min(_t.duration, Math.max(nMsecOffset, 0)); // position >= 0 and <= current available (loaded) duration
_t._iO.position = offset;
if (!bNoDebug) {
// _s._wD('SMSound.setPosition('+nMsecOffset+')'+(nMsecOffset != offset?', corrected value: '+offset:''));
}
_s.o._setPosition(_t.sID, (_s.flashVersion == 9?_t._iO.position:_t._iO.position / 1000), (_t.paused || !_t.playState)); // if paused or not playing, will not resume (by playing)
};
this.pause = function() {
if (_t.paused || _t.playState === 0) {
return false;
}
_s._wD('SMSound.pause()');
_t.paused = true;
_s.o._pause(_t.sID);
if (_t._iO.onpause) {
_t._iO.onpause.apply(_t);
}
};
this.resume = function() {
if (!_t.paused || _t.playState === 0) {
return false;
}
_s._wD('SMSound.resume()');
_t.paused = false;
_s.o._pause(_t.sID); // flash method is toggle-based (pause/resume)
if (_t._iO.onresume) {
_t._iO.onresume.apply(_t);
}
};
this.togglePause = function() {
_s._wD('SMSound.togglePause()');
if (_t.playState === 0) {
_t.play({
position: (_s.flashVersion == 9?_t.position:_t.position / 1000)
});
return false;
}
if (_t.paused) {
_t.resume();
} else {
_t.pause();
}
};
this.setPan = function(nPan, bInstanceOnly) {
if (typeof nPan == 'undefined') {
nPan = 0;
}
if (typeof bInstanceOnly == 'undefined') {
bInstanceOnly = false;
}
_s.o._setPan(_t.sID, nPan);
_t._iO.pan = nPan;
if (!bInstanceOnly) {
_t.pan = nPan;
}
};
this.setVolume = function(nVol, bInstanceOnly) {
if (typeof nVol == 'undefined') {
nVol = 100;
}
if (typeof bInstanceOnly == 'undefined') {
bInstanceOnly = false;
}
_s.o._setVolume(_t.sID, (_s.muted && !_t.muted) || _t.muted?0:nVol);
_t._iO.volume = nVol;
if (!bInstanceOnly) {
_t.volume = nVol;
}
};
this.mute = function() {
_t.muted = true;
_s.o._setVolume(_t.sID, 0);
};
this.unmute = function() {
_t.muted = false;
var hasIO = typeof _t._iO.volume != 'undefined';
_s.o._setVolume(_t.sID, hasIO?_t._iO.volume:_t.options.volume);
};
this.toggleMute = function() {
if (_t.muted) {
_t.unmute();
} else {
_t.mute();
}
};
// --- "private" methods called by Flash ---
this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration) {
if (!_t._iO.isMovieStar) {
_t.bytesLoaded = nBytesLoaded;
_t.bytesTotal = nBytesTotal;
_t.duration = Math.floor(nDuration);
_t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10);
if (_t.durationEstimate === undefined) {
// reported bug?
_t.durationEstimate = _t.duration;
}
if (_t.readyState != 3 && _t._iO.whileloading) {
_t._iO.whileloading.apply(_t);
}
} else {
_t.bytesLoaded = nBytesLoaded;
_t.bytesTotal = nBytesTotal;
_t.duration = Math.floor(nDuration);
_t.durationEstimate = _t.duration;
if (_t.readyState != 3 && _t._iO.whileloading) {
_t._iO.whileloading.apply(_t);
}
}
};
this._onid3 = function(oID3PropNames, oID3Data) {
// oID3PropNames: string array (names)
// ID3Data: string array (data)
_s._wD('SMSound._onid3(): "'+this.sID+'" ID3 data received.');
var oData = [];
for (var i=0, j = oID3PropNames.length; i<j; i++) {
oData[oID3PropNames[i]] = oID3Data[i];
// _s._wD(oID3PropNames[i]+': '+oID3Data[i]);
}
_t.id3 = _s._mergeObjects(_t.id3, oData);
if (_t._iO.onid3) {
_t._iO.onid3.apply(_t);
}
};
this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) {
if (isNaN(nPosition) || nPosition === null) {
return false; // Flash may return NaN at times
}
if (_t.playState === 0 && nPosition > 0) {
// can happen at the end of a video where nPosition == 33 for some reason, after finishing.???
// can also happen with a normal stop operation. This resets the position to 0.
// _s._writeDebug('Note: Not playing, but position = '+nPosition);
nPosition = 0;
}
_t.position = nPosition;
if (_s.flashVersion > 8) {
if (_t._iO.usePeakData && typeof oPeakData != 'undefined' && oPeakData) {
_t.peakData = {
left: oPeakData.leftPeak,
right: oPeakData.rightPeak
};
}
if (_t._iO.useWaveformData && typeof oWaveformDataLeft != 'undefined' && oWaveformDataLeft) {
_t.waveformData = {
left: oWaveformDataLeft.split(','),
right: oWaveformDataRight.split(',')
};
}
if (_t._iO.useEQData) {
if (typeof oEQData != 'undefined' && oEQData.leftEQ) {
var eqLeft = oEQData.leftEQ.split(',');
_t.eqData = eqLeft;
_t.eqData.left = eqLeft;
if (typeof oEQData.rightEQ != 'undefined' && oEQData.rightEQ) {
_t.eqData.right = oEQData.rightEQ.split(',');
}
}
}
}
if (_t.playState == 1) {
// special case/hack: ensure buffering is false (instant load from cache, thus buffering stuck at 1?)
if (_t.isBuffering) {
_t._onbufferchange(0);
}
if (_t._iO.whileplaying) {
_t._iO.whileplaying.apply(_t); // flash may call after actual finish
}
if (_t.loaded && _t._iO.onbeforefinish && _t._iO.onbeforefinishtime && !_t.didBeforeFinish && _t.duration - _t.position <= _t._iO.onbeforefinishtime) {
_s._wD('duration-position <= onbeforefinishtime: '+_t.duration+' - '+_t.position+' <= '+_t._iO.onbeforefinishtime+' ('+(_t.duration - _t.position)+')');
_t._onbeforefinish();
}
}
};
this._onload = function(bSuccess) {
var fN = 'SMSound._onload(): ';
bSuccess = (bSuccess == 1?true:false);
_s._wD(fN+'"'+_t.sID+'"'+(bSuccess?' loaded.':' failed to load? - '+_t.url), (bSuccess?1:2));
if (!bSuccess) {
if (_s.sandbox.noRemote === true) {
_s._wD(fN+_s._str('noNet'), 1);
}
if (_s.sandbox.noLocal === true) {
_s._wD(fN+_s._str('noLocal'), 1);
}
}
_t.loaded = bSuccess;
_t.readyState = bSuccess?3:2;
if (_t.readyState==2) {
_t.loadfailed();
}
if (_t._iO.onload) {
_t._iO.onload.apply(_t);
}
};
this._onbeforefinish = function() {
if (!_t.didBeforeFinish) {
_t.didBeforeFinish = true;
if (_t._iO.onbeforefinish) {
_s._wD('SMSound._onbeforefinish(): "'+_t.sID+'"');
_t._iO.onbeforefinish.apply(_t);
}
}
};
this._onjustbeforefinish = function(msOffset) {
// msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)
if (!_t.didJustBeforeFinish) {
_t.didJustBeforeFinish = true;
if (_t._iO.onjustbeforefinish) {
_s._wD('SMSound._onjustbeforefinish(): "'+_t.sID+'"');
_t._iO.onjustbeforefinish.apply(_t);
}
}
};
this._onfinish = function() {
// sound has finished playing
// TODO: calling user-defined onfinish() should happen after setPosition(0)
// OR: onfinish() and then setPosition(0) is bad.
if (_t._iO.onbeforefinishcomplete) {
_t._iO.onbeforefinishcomplete.apply(_t);
}
// reset some state items
_t.didBeforeFinish = false;
_t.didJustBeforeFinish = false;
if (_t.instanceCount) {
_t.instanceCount--;
if (!_t.instanceCount) {
// reset instance options
// _t.setPosition(0);
_t.playState = 0;
_t.paused = false;
_t.instanceCount = 0;
_t.instanceOptions = {};
}
if (!_t.instanceCount || _t._iO.multiShotEvents) {
// fire onfinish for last, or every instance
if (_t._iO.onfinish) {
_s._wD('SMSound._onfinish(): "'+_t.sID+'"');
_t._iO.onfinish.apply(_t);
}
}
} else {
if (_t.useVideo) {
// video has finished
// may need to reset position for next play call, "rewind"
// _t.setPosition(0);
}
// _t.setPosition(0);
}
};
this._onmetadata = function(oMetaData) {
// movieStar mode only
var fN = 'SMSound.onmetadata()';
_s._wD(fN);
// Contains a subset of metadata. Note that files may have their own unique metadata.
// http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html
if (!oMetaData.width && !oMetaData.height) {
_s._wDS('noWH');
oMetaData.width = 320;
oMetaData.height = 240;
}
_t.metadata = oMetaData; // potentially-large object from flash
_t.width = oMetaData.width;
_t.height = oMetaData.height;
if (_t._iO.onmetadata) {
_s._wD(fN+': "'+_t.sID+'"');
_t._iO.onmetadata.apply(_t);
}
_s._wD(fN+' complete');
};
this._onbufferchange = function(bIsBuffering) {
var fN = 'SMSound._onbufferchange()';
if (_t.playState === 0) {
// ignore if not playing
return false;
}
if (bIsBuffering == _t.isBuffering) {
// ignore initial "false" default, if matching
_s._wD(fN+': ignoring false default / loaded sound');
return false;
}
_t.isBuffering = (bIsBuffering == 1?true:false);
if (_t._iO.onbufferchange) {
_s._wD(fN+': '+bIsBuffering);
_t._iO.onbufferchange.apply(_t);
}
};
this._ondataerror = function(sError) {
// flash 9 wave/eq data handler
if (_t.playState > 0) { // hack: called at start, and end from flash at/after onfinish().
_s._wD('SMSound._ondataerror(): '+sError);
if (_t._iO.ondataerror) {
_t._iO.ondataerror.apply(_t);
}
} else {
// _s._wD('SMSound._ondataerror(): ignoring');
}
};
}; // SMSound()
this._onfullscreenchange = function(bFullScreen) {
_s._wD('onfullscreenchange(): '+bFullScreen);
_s.isFullScreen = (bFullScreen == 1?true:false);
if (!_s.isFullScreen) {
// attempt to restore window focus after leaving full-screen
try {
window.focus();
_s._wD('window.focus()');
} catch(e) {
// oh well
}
}
};
// register a few event handlers
if (window.addEventListener) {
window.addEventListener('focus', _s.handleFocus, false);
window.addEventListener('load', _s.beginDelayedInit, false);
window.addEventListener('unload', _s.destruct, false);
if (_s._tryInitOnFocus) {
window.addEventListener('mousemove', _s.handleFocus, false); // massive Safari focus hack
}
} else if (window.attachEvent) {
window.attachEvent('onfocus', _s.handleFocus);
window.attachEvent('onload', _s.beginDelayedInit);
window.attachEvent('unload', _s.destruct);
} else {
// no add/attachevent support - safe to assume no JS -> Flash either.
_s._debugTS('onload', false);
soundManager.onerror();
soundManager.disable();
}
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', _s.domContentLoaded, false);
}
} // SoundManager()
// var SM2_DEFER = true; // un-comment or define in your own script to prevent immediate SoundManager() constructor call+start-up.
// if deferring, construct later with window.soundManager = new SoundManager(); followed by soundManager.beginDelayedInit();
if (typeof SM2_DEFER == 'undefined' || !SM2_DEFER) {
soundManager = new SoundManager();
+ soundManager.beginDelayedInit();
}
\ No newline at end of file
diff --git a/tumblr.gif b/tumblr.gif
deleted file mode 100644
index 53fda22..0000000
Binary files a/tumblr.gif and /dev/null differ
|
bjornstar/TumTaster
|
2c699b95cda73d8d9affa3995b1cc08eba26027a
|
I do not understand how to use git, here is the 2nd half of the previous commit.
|
diff --git a/README b/README
index 594cc5f..caf0215 100644
--- a/README
+++ b/README
@@ -1,16 +1,16 @@
-ChromeTaster v0.4
+ChromeTaster v0.4.1
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/script.js b/script.js
index 3c6dc63..b932c3f 100644
--- a/script.js
+++ b/script.js
@@ -1,157 +1,154 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
var settings;
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function loadSettings() {
var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
+ if (window.location.href.indexOf('show/audio')>0) {
+ fixaudiopagination();
+ }
if (checkurl(location.href, settings['listSites'])) {
setInterval(taste, 200);
}
});
}
function checkurl(url, filter) {
for (var f in filter) {
var filterRegex;
filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
var re = new RegExp(filterRegex);
if (url.match(re)) {
return true;
}
}
return false;
}
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
song_embed[i].parentNode.style.height='54px';
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
var post_url = 'http://www.tumblr.com/';
// Find the post's URL.
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
- if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
+ if (anchors[a].href.indexOf('/post/'+post_id)>=0) {
post_url = anchors[a].href;
}
}
}
if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
//We check our white list to see if we should add it to the playlist.
var whitelisted = false;
var blacklisted = false;
//Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
var post = document.getElementById('post'+post_id);
for (itemWhite in settings['listWhite']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
whitelisted = true;
break;
}
}
// If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
if (!whitelisted) {
for (itemBlack in settings['listBlack']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
blacklisted = true;
break;
}
}
}
}
if (!blacklisted) {
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
}
}
last_embed = song_embed.length;
}
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
- if (currentpage.indexOf('show/audio')<0) {
- return;
- }
-
- var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
- if (isNaN(pagenumber)) {
- nextpagelink.href = currentpage+'/2';
- } else {
- nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
- }
- if (prevpagelink) {
- prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
- }
-
- var dashboard_controls = document.getElementById('dashboard_controls');
- if (dashboard_controls) {
- dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
- dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
- dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
- }
+ var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
+ if (isNaN(pagenumber)) {
+ nextpagelink.href = currentpage+'/2';
+ } else {
+ nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
+ }
+ if (prevpagelink) {
+ prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
+ }
+
+ var dashboard_controls = document.getElementById('dashboard_controls');
+ if (dashboard_controls) {
+ dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
+ dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
+ dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
+ }
}
-fixaudiopagination();
-
loadSettings();
\ No newline at end of file
|
bjornstar/TumTaster
|
0e30ee1ba37d9f0f43f17f7209711079e67711d6
|
v0.4.1 fixes a bug where the next page link would disappear and post urls without descriptions would get added as www.tumblr.com
|
diff --git a/manifest.json b/manifest.json
index d4eb01e..d59b0c6 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,22 +1,22 @@
{
"name": "ChromeTaster",
- "version": "0.4",
+ "version": "0.4.1",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 4a3c865..8dc57e2 100644
--- a/options.html
+++ b/options.html
@@ -1,205 +1,205 @@
<html>
<head>
<title>Options for ChromeTaster</title>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0 10px;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
color:#4F545A;
}
h1{
color:black;
}
a{
color:#4F545A;
text-decoration:none;
}
#content{
background: white url(content_bg.png) repeat-y;
display: block;
margin: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
padding-top: 5px;
width: 840px;
}
#content_top,#content_bottom{
display: inline;
height: 25px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
width: 900px;
}
#listBlack,#listWhite{
float:left;
width:300px;
margin-bottom:25px;
}
#listSites{
clear:left;
width:800px;
}
#listSites input{
width:400px;
}
</style>
<script type="text/javascript">
var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
console.log(settings['shuffle']);
console.log(settings['repeat']);
var select = document.getElementById("optionShuffle");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == settings['shuffle']) {
child.selected = "true";
break;
}
}
var select = document.getElementById("optionRepeat");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == settings['repeat']) {
child.selected = "true";
break;
}
}
for (var itemBlack in settings['listBlack']) {
addInput("Black", settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput("White", settings['listWhite'][itemWhite]);
}
for (var itemSites in settings['listSites']) {
addInput("Sites", settings['listSites'][itemSites]);
}
addInput("Black"); //prepare a blank input box.
addInput("White"); //prepare a blank input box.
addInput("Sites"); //prepare a blank input box.
}
function addInput(whichList, itemValue) {
if (itemValue == undefined) {
itemValue = "";
}
var garbageTruck = document.getElementById('list'+whichList);
garbageInput = document.createElement('input');
garbageInput.value = itemValue;
garbageInput.name = 'option'+whichList;
garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
garbageAdd = document.createElement('a');
garbageAdd.href = "#";
garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
garbageAdd.innerHTML = '<img src="x_7x7.png" /> ';
garbageLinebreak = document.createElement('br');
garbageTruck.appendChild(garbageAdd);
garbageTruck.appendChild(garbageInput);
garbageTruck.appendChild(garbageLinebreak);
}
function removeInput(garbageWhich) {
var garbageInput = document.getElementById(garbageWhich);
- garbageInput.parentNode.removeChild(garbageInput.nextSibling);
+ garbageInput.parentNode.removeChild(garbageInput.previousSibling);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
var settings = {};
var selectShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = selectShuffle.children[selectShuffle.selectedIndex].value;
var selectRepeat = document.getElementById('optionRepeat');
settings['repeat'] = selectRepeat.children[selectRepeat.selectedIndex].value;
settings['listWhite'] = [];
settings['listBlack'] = [];
settings['listSites'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != "") {
if (garbages[i].name.substring(0,11) == "optionWhite") {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionBlack") {
settings['listBlack'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionSites") {
settings['listSites'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
<div style="width:100%;height:64px;margin-bottom:12px;">
<img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
<h1 style="line-height:64px;">ChromeTaster Options</h1>
</div>
<img src="content_top.png?alpha" alt="" id="content_top">
<div id="content">
<label for="optionShuffle">Shuffle: </label>
<select id="optionShuffle" name="optionShuffle">
<option value="false">Off</option>
<option value="true">On</option>
</select>
<label for="optionRepeat">Repeat: </label>
<select id="optionRepeat" name="optionRepeat">
<option value="false">Off</option>
<option value="true">On</option>
</select>
<br />
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
<a href="#" onclick="addInput('Black'); return false;">add</a><br />
</div>
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
<a href="#" onclick="addInput('White'); return false;">add</a><br />
</div>
<div id="listSites">
<h2>Site List</h2>
<p>Run ChromeTaster on these sites:</p>
<a href="#" onclick="addInput('Sites'); return false;">add</a><br />
</div>
<br />
<input onclick="saveOptions()" type="button" value="Save" />
<input onclick="eraseOptions()" type="button" value="Restore default" />
</div>
<img src="content_bottom.png" alt="" id="content_bottom">
</body>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
ce354b97fb5ff4bc3b8e6f1d3454ca597b9d319a
|
Added options to control which pages ChromeTaster runs on. May not be perfect.
|
diff --git a/README b/README
index f262000..594cc5f 100644
--- a/README
+++ b/README
@@ -1,16 +1,16 @@
-ChromeTaster v0.3.1
+ChromeTaster v0.4
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/manifest.json b/manifest.json
index 4ea8ed3..d4eb01e 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,22 @@
{
"name": "ChromeTaster",
- "version": "0.3.1",
+ "version": "0.4",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
- "matches": [ "http://*/*", "https://*/*" ],
- "include_globs": [ "http://*.tumblr.com/*", "http://bjornstar.com/*", "http://toys.tumblrist.com/audio/*" ]
+ "matches": [ "http://*/*", "https://*/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 37a7776..4a3c865 100644
--- a/options.html
+++ b/options.html
@@ -1,181 +1,205 @@
<html>
-<head>
- <title>Options for ChromeTaster</title>
- <style type="text/css">
- html{
- color:black;
- font-family:arial,helvetica,sans-serif;
- margin:0;
- padding:0 10px;
- background-color:#2C4762;
- background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
- background-repeat:repeat-x;
- color:#4F545A;
- }
- h1{
- color:black;
- }
- a{
- color:#4F545A;
- text-decoration:none;
- }
- #content{
- background: white url(content_bg.png) repeat-y;
- display: block;
- margin: 0px;
- outline-color: #444;
- outline-style: none;
- outline-width: 0px;
- padding-bottom: 5px;
- padding-left: 30px;
- padding-right: 30px;
- padding-top: 5px;
- width: 840px;
- }
- #content_top,#content_bottom{
- display: inline;
- height: 25px;
- outline-color: #444;
- outline-style: none;
- outline-width: 0px;
- width: 900px;
- }
- </style>
- <script type="text/javascript">
-var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck']}; //initialize default values.
+ <head>
+ <title>Options for ChromeTaster</title>
+ <style type="text/css">
+ html{
+ color:black;
+ font-family:arial,helvetica,sans-serif;
+ margin:0;
+ padding:0 10px;
+ background-color:#2C4762;
+ background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
+ background-repeat:repeat-x;
+ color:#4F545A;
+ }
+ h1{
+ color:black;
+ }
+ a{
+ color:#4F545A;
+ text-decoration:none;
+ }
+ #content{
+ background: white url(content_bg.png) repeat-y;
+ display: block;
+ margin: 0px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ padding-bottom: 5px;
+ padding-left: 30px;
+ padding-right: 30px;
+ padding-top: 5px;
+ width: 840px;
+ }
+ #content_top,#content_bottom{
+ display: inline;
+ height: 25px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ width: 900px;
+ }
+ #listBlack,#listWhite{
+ float:left;
+ width:300px;
+ margin-bottom:25px;
+ }
+ #listSites{
+ clear:left;
+ width:800px;
+ }
+ #listSites input{
+ width:400px;
+ }
+ </style>
+ <script type="text/javascript">
+ var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
-function loadOptions() {
- var settings = localStorage['settings'];
+ function loadOptions() {
+ var settings = localStorage['settings'];
- if (settings == undefined) {
- settings = defaultSettings;
- } else {
- settings = JSON.parse(settings);
- }
+ if (settings == undefined) {
+ settings = defaultSettings;
+ } else {
+ settings = JSON.parse(settings);
+ }
- console.log(settings['shuffle']);
- console.log(settings['repeat']);
+ console.log(settings['shuffle']);
+ console.log(settings['repeat']);
- var select = document.getElementById("optionShuffle");
- for (var i = 0; i < select.children.length; i++) {
- var child = select.children[i];
- if (child.value == settings['shuffle']) {
- child.selected = "true";
- break;
- }
- }
-
- var select = document.getElementById("optionRepeat");
- for (var i = 0; i < select.children.length; i++) {
- var child = select.children[i];
- if (child.value == settings['repeat']) {
- child.selected = "true";
- break;
- }
- }
-
- for (var itemBlack in settings['listBlack']) {
- addInput("Black", settings['listBlack'][itemBlack]);
- }
-
- for (var itemWhite in settings['listWhite']) {
- addInput("White", settings['listWhite'][itemWhite]);
- }
-
- addInput("Black"); //prepare a blank input box.
- addInput("White"); //prepare a blank input box.
-}
+ var select = document.getElementById("optionShuffle");
+ for (var i = 0; i < select.children.length; i++) {
+ var child = select.children[i];
+ if (child.value == settings['shuffle']) {
+ child.selected = "true";
+ break;
+ }
+ }
+
+ var select = document.getElementById("optionRepeat");
+ for (var i = 0; i < select.children.length; i++) {
+ var child = select.children[i];
+ if (child.value == settings['repeat']) {
+ child.selected = "true";
+ break;
+ }
+ }
+
+ for (var itemBlack in settings['listBlack']) {
+ addInput("Black", settings['listBlack'][itemBlack]);
+ }
+
+ for (var itemWhite in settings['listWhite']) {
+ addInput("White", settings['listWhite'][itemWhite]);
+ }
+
+ for (var itemSites in settings['listSites']) {
+ addInput("Sites", settings['listSites'][itemSites]);
+ }
+
+ addInput("Black"); //prepare a blank input box.
+ addInput("White"); //prepare a blank input box.
+ addInput("Sites"); //prepare a blank input box.
+ }
-function addInput(whichList, itemValue) {
- if (itemValue == undefined) {
- itemValue = "";
- }
- var garbageTruck = document.getElementById('list'+whichList);
- garbageInput = document.createElement('input');
- garbageInput.value = itemValue;
- garbageInput.name = 'option'+whichList;
- garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
- garbageAdd = document.createElement('a');
- garbageAdd.href = "#";
- garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
- garbageAdd.innerText = "remove";
- garbageLinebreak = document.createElement('br');
- garbageTruck.appendChild(garbageInput);
- garbageTruck.appendChild(garbageAdd);
- garbageTruck.appendChild(garbageLinebreak);
-}
+ function addInput(whichList, itemValue) {
+ if (itemValue == undefined) {
+ itemValue = "";
+ }
+ var garbageTruck = document.getElementById('list'+whichList);
+ garbageInput = document.createElement('input');
+ garbageInput.value = itemValue;
+ garbageInput.name = 'option'+whichList;
+ garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
+ garbageAdd = document.createElement('a');
+ garbageAdd.href = "#";
+ garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
+ garbageAdd.innerHTML = '<img src="x_7x7.png" /> ';
+ garbageLinebreak = document.createElement('br');
+ garbageTruck.appendChild(garbageAdd);
+ garbageTruck.appendChild(garbageInput);
+ garbageTruck.appendChild(garbageLinebreak);
+ }
-function removeInput(garbageWhich) {
- var garbageInput = document.getElementById(garbageWhich);
- garbageInput.parentNode.removeChild(garbageInput.nextSibling);
- garbageInput.parentNode.removeChild(garbageInput.nextSibling);
- garbageInput.parentNode.removeChild(garbageInput);
-}
+ function removeInput(garbageWhich) {
+ var garbageInput = document.getElementById(garbageWhich);
+ garbageInput.parentNode.removeChild(garbageInput.nextSibling);
+ garbageInput.parentNode.removeChild(garbageInput.nextSibling);
+ garbageInput.parentNode.removeChild(garbageInput);
+ }
-function saveOptions() {
- var settings = {};
+ function saveOptions() {
+ var settings = {};
- var selectShuffle = document.getElementById('optionShuffle');
- settings['shuffle'] = selectShuffle.children[selectShuffle.selectedIndex].value;
- var selectRepeat = document.getElementById('optionRepeat');
- settings['repeat'] = selectRepeat.children[selectRepeat.selectedIndex].value;
+ var selectShuffle = document.getElementById('optionShuffle');
+ settings['shuffle'] = selectShuffle.children[selectShuffle.selectedIndex].value;
+ var selectRepeat = document.getElementById('optionRepeat');
+ settings['repeat'] = selectRepeat.children[selectRepeat.selectedIndex].value;
- settings['listWhite'] = [];
- settings['listBlack'] = [];
+ settings['listWhite'] = [];
+ settings['listBlack'] = [];
+ settings['listSites'] = [];
- var garbages = document.getElementsByTagName('input');
- for (var i = 0; i< garbages.length; i++) {
- if (garbages[i].value != "") {
- if (garbages[i].name.substring(0,11) == "optionWhite") {
- settings['listWhite'].push(garbages[i].value);
- } else if (garbages[i].name.substring(0,11) == "optionBlack") {
- settings['listBlack'].push(garbages[i].value);
- }
- }
- }
- localStorage['settings'] = JSON.stringify(settings);
- location.reload();
-}
+ var garbages = document.getElementsByTagName('input');
+ for (var i = 0; i< garbages.length; i++) {
+ if (garbages[i].value != "") {
+ if (garbages[i].name.substring(0,11) == "optionWhite") {
+ settings['listWhite'].push(garbages[i].value);
+ } else if (garbages[i].name.substring(0,11) == "optionBlack") {
+ settings['listBlack'].push(garbages[i].value);
+ } else if (garbages[i].name.substring(0,11) == "optionSites") {
+ settings['listSites'].push(garbages[i].value);
+ }
+ }
+ }
+ localStorage['settings'] = JSON.stringify(settings);
+ location.reload();
+ }
-function eraseOptions() {
- localStorage.removeItem('settings');
- location.reload();
-}
- </script>
-</head>
-<body onload="loadOptions()">
- <div style="width:100%;height:64px;margin-bottom:12px;">
- <img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
- <h1 style="line-height:64px;">ChromeTaster Options</h1>
- </div>
- <img src="content_top.png?alpha" alt="" id="content_top">
- <div id="content">
- <label for="optionShuffle">Shuffle: </label>
- <select id="optionShuffle" name="optionShuffle">
- <option value="false">Off</option>
- <option value="true">On</option>
- </select>
- <label for="optionRepeat">Repeat: </label>
- <select id="optionRepeat" name="optionRepeat">
- <option value="false">Off</option>
- <option value="true">On</option>
- </select>
- <br />
- <div id="listBlack">
- <h2>Black List</h2>
- <p>Do not add music with these words:</p>
- <a href="#" onclick="addInput('Black'); return false;">add</a><br />
- </div>
- <br />
- <div id="listWhite">
- <h2>White List</h2>
- <p>Always add music with these words:</p>
- <a href="#" onclick="addInput('White'); return false;">add</a><br />
- </div>
- <br />
- <button onclick="saveOptions()">Save</button>
- <button onclick="eraseOptions()">Restore default</button>
- </div>
- <img src="content_bottom.png" alt="" id="content_bottom">
-</body>
+ function eraseOptions() {
+ localStorage.removeItem('settings');
+ location.reload();
+ }
+ </script>
+ </head>
+ <body onload="loadOptions()">
+ <div style="width:100%;height:64px;margin-bottom:12px;">
+ <img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
+ <h1 style="line-height:64px;">ChromeTaster Options</h1>
+ </div>
+ <img src="content_top.png?alpha" alt="" id="content_top">
+ <div id="content">
+ <label for="optionShuffle">Shuffle: </label>
+ <select id="optionShuffle" name="optionShuffle">
+ <option value="false">Off</option>
+ <option value="true">On</option>
+ </select>
+ <label for="optionRepeat">Repeat: </label>
+ <select id="optionRepeat" name="optionRepeat">
+ <option value="false">Off</option>
+ <option value="true">On</option>
+ </select>
+ <br />
+ <div id="listBlack">
+ <h2>Black List</h2>
+ <p>Do not add music with these words:</p>
+ <a href="#" onclick="addInput('Black'); return false;">add</a><br />
+ </div>
+ <div id="listWhite">
+ <h2>White List</h2>
+ <p>Always add music with these words:</p>
+ <a href="#" onclick="addInput('White'); return false;">add</a><br />
+ </div>
+ <div id="listSites">
+ <h2>Site List</h2>
+ <p>Run ChromeTaster on these sites:</p>
+ <a href="#" onclick="addInput('Sites'); return false;">add</a><br />
+ </div>
+ <br />
+ <input onclick="saveOptions()" type="button" value="Save" />
+ <input onclick="eraseOptions()" type="button" value="Restore default" />
+ </div>
+ <img src="content_bottom.png" alt="" id="content_bottom">
+ </body>
</html>
\ No newline at end of file
diff --git a/script.js b/script.js
index 2674098..3c6dc63 100644
--- a/script.js
+++ b/script.js
@@ -1,143 +1,157 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
var settings;
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function loadSettings() {
- var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck']}; //initialize default values.
+ var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck'], 'listSites': ['http://*.tumblr.com/*', 'http://bjornstar.com/*'] }; //initialize default values.
chrome.extension.sendRequest('getSettings', function(response) {
savedSettings = response.settings;
if (savedSettings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(savedSettings);
}
- setInterval(taste, 200);
+ if (checkurl(location.href, settings['listSites'])) {
+ setInterval(taste, 200);
+ }
});
}
+function checkurl(url, filter) {
+ for (var f in filter) {
+ var filterRegex;
+ filterRegex=filter[f].replace(/\x2a/g, "(.*?)");
+ var re = new RegExp(filterRegex);
+ if (url.match(re)) {
+ return true;
+ }
+ }
+ return false;
+}
+
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
song_embed[i].parentNode.style.height='54px';
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
var post_url = 'http://www.tumblr.com/';
// Find the post's URL.
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
post_url = anchors[a].href;
}
}
}
if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
//We check our white list to see if we should add it to the playlist.
var whitelisted = false;
var blacklisted = false;
//Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
var post = document.getElementById('post'+post_id);
for (itemWhite in settings['listWhite']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
whitelisted = true;
break;
}
}
// If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
if (!whitelisted) {
for (itemBlack in settings['listBlack']) {
if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
blacklisted = true;
break;
}
}
}
}
if (!blacklisted) {
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
}
}
last_embed = song_embed.length;
}
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
if (currentpage.indexOf('show/audio')<0) {
return;
}
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
fixaudiopagination();
loadSettings();
\ No newline at end of file
|
bjornstar/TumTaster
|
8deff61a56fac395b9eb26bca5a912c068102496
|
Made the options prettier and added a button to remove songs.
|
diff --git a/README b/README
index 292c714..f262000 100644
--- a/README
+++ b/README
@@ -1,16 +1,16 @@
-ChromeTaster v0.3
+ChromeTaster v0.3.1
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/content_bg.png b/content_bg.png
new file mode 100644
index 0000000..4e831ab
Binary files /dev/null and b/content_bg.png differ
diff --git a/content_bottom.png b/content_bottom.png
new file mode 100644
index 0000000..61b096d
Binary files /dev/null and b/content_bottom.png differ
diff --git a/content_top.png b/content_top.png
new file mode 100644
index 0000000..587afd7
Binary files /dev/null and b/content_top.png differ
diff --git a/manifest.json b/manifest.json
index 2d53e22..4ea8ed3 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,23 @@
{
"name": "ChromeTaster",
- "version": "0.3",
+ "version": "0.3.1",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"include_globs": [ "http://*.tumblr.com/*", "http://bjornstar.com/*", "http://toys.tumblrist.com/audio/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 97ece44..37a7776 100644
--- a/options.html
+++ b/options.html
@@ -1,138 +1,181 @@
<html>
<head>
<title>Options for ChromeTaster</title>
+ <style type="text/css">
+ html{
+ color:black;
+ font-family:arial,helvetica,sans-serif;
+ margin:0;
+ padding:0 10px;
+ background-color:#2C4762;
+ background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
+ background-repeat:repeat-x;
+ color:#4F545A;
+ }
+ h1{
+ color:black;
+ }
+ a{
+ color:#4F545A;
+ text-decoration:none;
+ }
+ #content{
+ background: white url(content_bg.png) repeat-y;
+ display: block;
+ margin: 0px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ padding-bottom: 5px;
+ padding-left: 30px;
+ padding-right: 30px;
+ padding-top: 5px;
+ width: 840px;
+ }
+ #content_top,#content_bottom{
+ display: inline;
+ height: 25px;
+ outline-color: #444;
+ outline-style: none;
+ outline-width: 0px;
+ width: 900px;
+ }
+ </style>
<script type="text/javascript">
var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck']}; //initialize default values.
function loadOptions() {
var settings = localStorage['settings'];
if (settings == undefined) {
settings = defaultSettings;
} else {
settings = JSON.parse(settings);
}
console.log(settings['shuffle']);
console.log(settings['repeat']);
var select = document.getElementById("optionShuffle");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == settings['shuffle']) {
child.selected = "true";
break;
}
}
var select = document.getElementById("optionRepeat");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == settings['repeat']) {
child.selected = "true";
break;
}
}
for (var itemBlack in settings['listBlack']) {
addInput("Black", settings['listBlack'][itemBlack]);
}
for (var itemWhite in settings['listWhite']) {
addInput("White", settings['listWhite'][itemWhite]);
}
addInput("Black"); //prepare a blank input box.
addInput("White"); //prepare a blank input box.
}
function addInput(whichList, itemValue) {
if (itemValue == undefined) {
itemValue = "";
}
var garbageTruck = document.getElementById('list'+whichList);
garbageInput = document.createElement('input');
garbageInput.value = itemValue;
garbageInput.name = 'option'+whichList;
garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
garbageAdd = document.createElement('a');
garbageAdd.href = "#";
garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
garbageAdd.innerText = "remove";
garbageLinebreak = document.createElement('br');
garbageTruck.appendChild(garbageInput);
garbageTruck.appendChild(garbageAdd);
garbageTruck.appendChild(garbageLinebreak);
}
function removeInput(garbageWhich) {
var garbageInput = document.getElementById(garbageWhich);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput.nextSibling);
garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
var settings = {};
var selectShuffle = document.getElementById('optionShuffle');
settings['shuffle'] = selectShuffle.children[selectShuffle.selectedIndex].value;
var selectRepeat = document.getElementById('optionRepeat');
settings['repeat'] = selectRepeat.children[selectRepeat.selectedIndex].value;
settings['listWhite'] = [];
settings['listBlack'] = [];
var garbages = document.getElementsByTagName('input');
for (var i = 0; i< garbages.length; i++) {
if (garbages[i].value != "") {
if (garbages[i].name.substring(0,11) == "optionWhite") {
settings['listWhite'].push(garbages[i].value);
} else if (garbages[i].name.substring(0,11) == "optionBlack") {
settings['listBlack'].push(garbages[i].value);
}
}
}
localStorage['settings'] = JSON.stringify(settings);
location.reload();
}
function eraseOptions() {
localStorage.removeItem('settings');
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
- <div style="width:100%;height:64px;">
+ <div style="width:100%;height:64px;margin-bottom:12px;">
<img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
<h1 style="line-height:64px;">ChromeTaster Options</h1>
</div>
+ <img src="content_top.png?alpha" alt="" id="content_top">
+ <div id="content">
<label for="optionShuffle">Shuffle: </label>
<select id="optionShuffle" name="optionShuffle">
<option value="false">Off</option>
<option value="true">On</option>
</select>
<label for="optionRepeat">Repeat: </label>
<select id="optionRepeat" name="optionRepeat">
<option value="false">Off</option>
<option value="true">On</option>
</select>
<br />
<div id="listBlack">
<h2>Black List</h2>
<p>Do not add music with these words:</p>
<a href="#" onclick="addInput('Black'); return false;">add</a><br />
</div>
<br />
<div id="listWhite">
<h2>White List</h2>
<p>Always add music with these words:</p>
<a href="#" onclick="addInput('White'); return false;">add</a><br />
</div>
<br />
- <button onclick="saveOptions()">Save</button>
- <br />
+ <button onclick="saveOptions()">Save</button>
<button onclick="eraseOptions()">Restore default</button>
+ </div>
+ <img src="content_bottom.png" alt="" id="content_bottom">
</body>
</html>
\ No newline at end of file
diff --git a/popup.html b/popup.html
index 295ac3b..29f2701 100644
--- a/popup.html
+++ b/popup.html
@@ -1,259 +1,273 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a{
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
#nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
#nowplayingdiv span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
div#heading h1{
color: white;
float: left;
line-height:32px;
vertical-align:absmiddle;
margin-left:10px;
}
div#statistics{
position:absolute;
bottom:0%;
}
#controls{
text-align:center;
}
#statusbar{
position:relative;
height:12px;
background-color:#CDD568;
border:2px solid #eaf839;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
overflow:hidden;
margin-top:4px;
}
+.remove{
+position:absolute;
+right:8px;
+top:8px;
+}
+
.position, .position2, .loading{
position:absolute;
left:0px;
bottom:0px;
height:12px;
}
.position{
background-color: #3B440F;
border-right:2px solid #3B440F;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
}
.position2{
background-color:#eaf839;
}
.loading {
background-color:#BBC552;
}
</style>
<div id="heading" style="width:100%;height:64px;"><img src="tumblr-audio-icon-64.png" style="float:left;" /><h1>ChromeTaster</h1></div>
-<div id="statistics"><span>No songs found.</span></div>
+<div id="statistics"><span> </span></div>
<div id="nowplayingdiv"><span id="nowplaying">Now Playing: </span>
<div id="statusbar">
<div id="loading" class="loading"> </div>
<div id="position2" class="position2"> </div>
<div id="position" class="position"> </div>
</div>
</div>
<p id="controls"><a href="javascript:void(sm.stopAll())">■</a> <a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
-var pl = bg.playlist;
+var pl = sm.sounds;
+
+function remove(song_id) {
+ sm.destroySound(song_id);
+ var song_li = document.getElementById(song_id);
+ song_li.parentNode.removeChild(song_li);
+}
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
update_nowplaying();
}
function get_currentsong() {
var song_nowplaying = null;
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
return song_nowplaying;
}
function update_nowplaying() {
var current_song = get_currentsong();
if (current_song) {
var nowplaying = document.getElementById('nowplaying');
nowplaying.innerHTML = 'Now Playing: '+current_song.sID;
}
}
function update_statistics() {
var count_songs = 0;
count_songs = sm.soundIDs.length;
var statistics = document.getElementById('statistics');
- statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
+ //statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
}
function playnextsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playnextsong(current_song_sID);
update_nowplaying();
}
function playrandomsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
update_nowplaying();
}
update_nowplaying();
update_statistics();
document.write('<ol class="playlist">');
for (x in pl) {
- document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
+ document.write('<li id="'+pl[x].sID+'"><a href="javascript:void(play(\''+pl[x].url+'\',\''+pl[x].sID+'\'))">'+pl[x].sID+'</a><a class="remove" href="javascript:void(remove(\''+pl[x].sID+'\'))"><img src="x_7x7.png" /></a></li>\r\n');
}
document.write('</ol>');
var div_loading = document.getElementById('loading');
var div_position = document.getElementById('position');
var div_position2 = document.getElementById('position2');
function updateStatus() {
var current_song = get_currentsong();
- if (current_song.bytesTotal > 0) {
- div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
+ if (current_song != undefined) {
+ if (current_song.bytesTotal > 0) {
+ div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
+ }
+ div_position.style.width = "20px";
+ div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
+ div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
}
- div_position.style.width = "20px";
- div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
- div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
}
setInterval(updateStatus, 200);
</script>
</html>
\ No newline at end of file
diff --git a/x_7x7.png b/x_7x7.png
new file mode 100644
index 0000000..b93532d
Binary files /dev/null and b/x_7x7.png differ
|
bjornstar/TumTaster
|
b65f2d2f8e12851c75dbed194d3165d095cb7d92
|
Added whitelist/blacklist and refactored settings.
|
diff --git a/README b/README
index ce71255..292c714 100644
--- a/README
+++ b/README
@@ -1,14 +1,16 @@
-ChromeTaster v0.2.1
+ChromeTaster v0.3
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
+v0.3 Now has blacklists and whitelists so that you can prevent some songs from getting put onto your playlist. You can put in a username, artist, or song name. It will do partial matches, so be careful what you put in there.
+
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/background.html b/background.html
index 6393d40..3cb8bd9 100644
--- a/background.html
+++ b/background.html
@@ -1,57 +1,61 @@
<html>
<script type="text/javascript" src="soundmanager2.js"></script>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
- chrome.extension.onRequest.addListener(
+ chrome.extension.onRequest.addListener( // Yes, this is ugly, I know. I'll fix it later.
function(song, sender, sendResponse) {
- sendResponse({});
- playlist[song.song_url] = song.post_url;
- var mySoundObject = soundManager.createSound({
- id: song.post_url,
- url: song.song_url,
- onloadfailed: function(){playnextsong(song.post_url)},
- onfinish: function(){playnextsong(song.post_url)}
- });
+ if (song == 'getSettings') {
+ sendResponse({settings: localStorage["settings"]});
+ } else {
+ playlist[song.song_url] = song.post_url;
+ var mySoundObject = soundManager.createSound({
+ id: song.post_url,
+ url: song.song_url,
+ onloadfailed: function(){playnextsong(song.post_url)},
+ onfinish: function(){playnextsong(song.post_url)}
+ });
+ sendResponse({});
+ }
});
function playnextsong(previous_song) {
var bad_idea = null;
var first_song = null;
var next_song = null;
for (x in soundManager.sounds) {
if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
next_song = soundManager.sounds[x].sID;
}
bad_idea = soundManager.sounds[x].sID;
if (first_song == null) {
first_song = soundManager.sounds[x].sID;
}
}
if (localStorage["shuffle"]) {
var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
next_song = soundManager.soundIDs[s];
}
if (localStorage["repeat"] && bad_idea == previous_song) {
next_song = first_song;
}
if (next_song != null) {
var soundNext = soundManager.getSoundById(next_song);
soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
mySoundObject.play();
}
</script>
<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/manifest.json b/manifest.json
index 457f8ff..2d53e22 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,23 @@
{
"name": "ChromeTaster",
- "version": "0.2.1",
+ "version": "0.3",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"include_globs": [ "http://*.tumblr.com/*", "http://bjornstar.com/*", "http://toys.tumblrist.com/audio/*" ]
} ]
}
\ No newline at end of file
diff --git a/options.html b/options.html
index 7d3384d..97ece44 100644
--- a/options.html
+++ b/options.html
@@ -1,70 +1,138 @@
<html>
<head>
<title>Options for ChromeTaster</title>
<script type="text/javascript">
-var defaultShuffle = false;
-var defaultRepeat = true;
+var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck']}; //initialize default values.
function loadOptions() {
- var shuffle = localStorage["shuffle"];
- var repeat = localStorage["repeat"];
+ var settings = localStorage['settings'];
- if (shuffle == undefined) {
- shuffle = defaultShuffle;
- }
+ if (settings == undefined) {
+ settings = defaultSettings;
+ } else {
+ settings = JSON.parse(settings);
+ }
- if (repeat == undefined) {
- repeat = defaultRepeat;
- }
+ console.log(settings['shuffle']);
+ console.log(settings['repeat']);
var select = document.getElementById("optionShuffle");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
- if (child.value == shuffle) {
+ if (child.value == settings['shuffle']) {
child.selected = "true";
break;
}
}
var select = document.getElementById("optionRepeat");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
- if (child.value == repeat) {
+ if (child.value == settings['repeat']) {
child.selected = "true";
break;
}
}
+
+ for (var itemBlack in settings['listBlack']) {
+ addInput("Black", settings['listBlack'][itemBlack]);
+ }
+
+ for (var itemWhite in settings['listWhite']) {
+ addInput("White", settings['listWhite'][itemWhite]);
+ }
+
+ addInput("Black"); //prepare a blank input box.
+ addInput("White"); //prepare a blank input box.
+}
+
+function addInput(whichList, itemValue) {
+ if (itemValue == undefined) {
+ itemValue = "";
+ }
+ var garbageTruck = document.getElementById('list'+whichList);
+ garbageInput = document.createElement('input');
+ garbageInput.value = itemValue;
+ garbageInput.name = 'option'+whichList;
+ garbageInput.id = 'option'+whichList+document.getElementsByTagName('input').length;
+ garbageAdd = document.createElement('a');
+ garbageAdd.href = "#";
+ garbageAdd.setAttribute('onclick', 'removeInput(\'option'+whichList+document.getElementsByTagName('input').length+'\'); return false;');
+ garbageAdd.innerText = "remove";
+ garbageLinebreak = document.createElement('br');
+ garbageTruck.appendChild(garbageInput);
+ garbageTruck.appendChild(garbageAdd);
+ garbageTruck.appendChild(garbageLinebreak);
+}
+
+function removeInput(garbageWhich) {
+ var garbageInput = document.getElementById(garbageWhich);
+ garbageInput.parentNode.removeChild(garbageInput.nextSibling);
+ garbageInput.parentNode.removeChild(garbageInput.nextSibling);
+ garbageInput.parentNode.removeChild(garbageInput);
}
function saveOptions() {
- var selectShuffle = document.getElementById("optionShuffle");
- localStorage["shuffle"] = selectShuffle.children[selectShuffle.selectedIndex].value;
- var selectRepeat = document.getElementById("optionRepeat");
- localStorage["repeat"] = selectRepeat.children[selectRepeat.selectedIndex].value;
+ var settings = {};
+
+ var selectShuffle = document.getElementById('optionShuffle');
+ settings['shuffle'] = selectShuffle.children[selectShuffle.selectedIndex].value;
+ var selectRepeat = document.getElementById('optionRepeat');
+ settings['repeat'] = selectRepeat.children[selectRepeat.selectedIndex].value;
+
+ settings['listWhite'] = [];
+ settings['listBlack'] = [];
+
+ var garbages = document.getElementsByTagName('input');
+ for (var i = 0; i< garbages.length; i++) {
+ if (garbages[i].value != "") {
+ if (garbages[i].name.substring(0,11) == "optionWhite") {
+ settings['listWhite'].push(garbages[i].value);
+ } else if (garbages[i].name.substring(0,11) == "optionBlack") {
+ settings['listBlack'].push(garbages[i].value);
+ }
+ }
+ }
+ localStorage['settings'] = JSON.stringify(settings);
+ location.reload();
}
function eraseOptions() {
- localStorage.removeItem("shuffle");
- localStorage.removeItem("repeat");
+ localStorage.removeItem('settings');
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
- <h1>ChromeTaster Options</h1>
+ <div style="width:100%;height:64px;">
+ <img src="tumblr-audio-icon-64.png" style="float:left;padding-right:10px;" />
+ <h1 style="line-height:64px;">ChromeTaster Options</h1>
+ </div>
<label for="optionShuffle">Shuffle: </label>
<select id="optionShuffle" name="optionShuffle">
<option value="false">Off</option>
<option value="true">On</option>
</select>
<label for="optionRepeat">Repeat: </label>
<select id="optionRepeat" name="optionRepeat">
<option value="false">Off</option>
<option value="true">On</option>
</select>
+ <br />
+ <div id="listBlack">
+ <h2>Black List</h2>
+ <p>Do not add music with these words:</p>
+ <a href="#" onclick="addInput('Black'); return false;">add</a><br />
+ </div>
+ <br />
+ <div id="listWhite">
+ <h2>White List</h2>
+ <p>Always add music with these words:</p>
+ <a href="#" onclick="addInput('White'); return false;">add</a><br />
+ </div>
<br />
<button onclick="saveOptions()">Save</button>
<br />
<button onclick="eraseOptions()">Restore default</button>
</body>
</html>
\ No newline at end of file
diff --git a/script.js b/script.js
index 7fcfe79..2674098 100644
--- a/script.js
+++ b/script.js
@@ -1,104 +1,143 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
+var settings;
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
+function loadSettings() {
+ var defaultSettings = { 'shuffle': 'false', 'repeat': 'true', 'listBlack': ['beatles'], 'listWhite': ['bjorn', 'beck']}; //initialize default values.
+ chrome.extension.sendRequest('getSettings', function(response) {
+ savedSettings = response.settings;
+ if (savedSettings == undefined) {
+ settings = defaultSettings;
+ } else {
+ settings = JSON.parse(savedSettings);
+ }
+ setInterval(taste, 200);
+ });
+}
+
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
song_embed[i].parentNode.style.height='54px';
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
-
- //Alright, here's the tough part. We gotta find the permalink for post to go with this audio file.
- //There's probably a million ways to do this better.
-
var post_url = 'http://www.tumblr.com/';
- if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
- post_url = document.getElementById('permalink_'+post_id).parentNode.getAttribute('href');
- } else {
- var anchors = document.getElementsByTagName('a');
- for (var a in anchors) {
- if (anchors[a].href) {
- if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
- post_url = anchors[a].href;
- }
- }
- }
- }
-
- chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
+ // Find the post's URL.
+ var anchors = document.getElementsByTagName('a');
+ for (var a in anchors) {
+ if (anchors[a].href) {
+ if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
+ post_url = anchors[a].href;
+ }
+ }
+ }
+
+ if (window.location.href.substring(0,28)!='http://www.tumblr.com/reblog') { //If you're reblogging it don't add it to the playlist, it's already there.
+
+ //We check our white list to see if we should add it to the playlist.
+ var whitelisted = false;
+ var blacklisted = false;
+
+ //Only do contextual white list and black list on the dashboard, maybe I can come up with a universal way to do it in a later revision.
+
+ if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
+ var post = document.getElementById('post'+post_id);
+
+ for (itemWhite in settings['listWhite']) {
+ if (post.innerHTML.toLowerCase().indexOf(settings['listWhite'][itemWhite].toLowerCase()) >= 0) {
+ whitelisted = true;
+ break;
+ }
+ }
+
+ // If it's not on the white list, we check our black list to see if we shouldn't add it to the playlist.
+ if (!whitelisted) {
+ for (itemBlack in settings['listBlack']) {
+ if (post.innerHTML.toLowerCase().indexOf(settings['listBlack'][itemBlack].toLowerCase()) >= 0) {
+ blacklisted = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (!blacklisted) {
+ chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
+ }
+ }
}
}
last_embed = song_embed.length;
}
-setInterval(taste, 200);
-
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
if (currentpage.indexOf('show/audio')<0) {
return;
}
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
-fixaudiopagination();
\ No newline at end of file
+fixaudiopagination();
+
+loadSettings();
\ No newline at end of file
|
bjornstar/TumTaster
|
46a96e005d76410771e94f4a2e834570045124fa
|
Increment version number.
|
diff --git a/README b/README
index 5eac2b5..ce71255 100644
--- a/README
+++ b/README
@@ -1,14 +1,14 @@
-ChromeTaster v0.2
+ChromeTaster v0.2.1
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/manifest.json b/manifest.json
index 919d4f4..457f8ff 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,23 @@
{
"name": "ChromeTaster",
- "version": "0.2",
+ "version": "0.2.1",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"include_globs": [ "http://*.tumblr.com/*", "http://bjornstar.com/*", "http://toys.tumblrist.com/audio/*" ]
} ]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
4328e1cb1526106cc490bd78d316e54be0342040
|
Added a loading/progress bar.
|
diff --git a/popup.html b/popup.html
index f3870d1..295ac3b 100644
--- a/popup.html
+++ b/popup.html
@@ -1,200 +1,259 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
- a {
+ a{
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
- div#nowplaying {
+ #nowplayingdiv {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
clear: left;
}
- div#nowplaying span{
+ #nowplayingdiv span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
div#heading h1{
color: white;
float: left;
line-height:32px;
vertical-align:absmiddle;
margin-left:10px;
}
div#statistics{
position:absolute;
bottom:0%;
}
#controls{
text-align:center;
}
+#statusbar{
+position:relative;
+height:12px;
+background-color:#CDD568;
+border:2px solid #eaf839;
+border-radius:2px;
+-moz-border-radius:2px;
+-webkit-border-radius:2px;
+overflow:hidden;
+margin-top:4px;
+}
+
+.position, .position2, .loading{
+position:absolute;
+left:0px;
+bottom:0px;
+height:12px;
+}
+.position{
+background-color: #3B440F;
+border-right:2px solid #3B440F;
+border-radius:2px;
+-moz-border-radius:2px;
+-webkit-border-radius:2px;
+}
+.position2{
+background-color:#eaf839;
+}
+.loading {
+background-color:#BBC552;
+}
+
+
</style>
<div id="heading" style="width:100%;height:64px;"><img src="tumblr-audio-icon-64.png" style="float:left;" /><h1>ChromeTaster</h1></div>
<div id="statistics"><span>No songs found.</span></div>
-<div id="nowplaying"><span>Now Playing: </span></div>
+<div id="nowplayingdiv"><span id="nowplaying">Now Playing: </span>
+<div id="statusbar">
+<div id="loading" class="loading"> </div>
+<div id="position2" class="position2"> </div>
+<div id="position" class="position"> </div>
+</div>
+</div>
+
<p id="controls"><a href="javascript:void(sm.stopAll())">■</a> <a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
+ update_nowplaying();
}
function get_currentsong() {
var song_nowplaying = null;
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
return song_nowplaying;
}
function update_nowplaying() {
var current_song = get_currentsong();
if (current_song) {
var nowplaying = document.getElementById('nowplaying');
- nowplaying.innerHTML = '<span>Now Playing: '+current_song.sID+'</span>';
+ nowplaying.innerHTML = 'Now Playing: '+current_song.sID;
}
}
function update_statistics() {
var count_songs = 0;
count_songs = sm.soundIDs.length;
var statistics = document.getElementById('statistics');
statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
}
function playnextsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playnextsong(current_song_sID);
update_nowplaying();
}
function playrandomsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
update_nowplaying();
}
update_nowplaying();
update_statistics();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
+
+var div_loading = document.getElementById('loading');
+var div_position = document.getElementById('position');
+var div_position2 = document.getElementById('position2');
+
+function updateStatus() {
+ var current_song = get_currentsong();
+ if (current_song.bytesTotal > 0) {
+ div_loading.style.width = (100 * current_song.bytesLoaded / current_song.bytesTotal) + '%';
+ }
+ div_position.style.width = "20px";
+ div_position.style.left = (100 * current_song.position / current_song.durationEstimate) + '%';
+ div_position2.style.width = (100 * current_song.position / current_song.durationEstimate) + '%';
+}
+
+setInterval(updateStatus, 200);
+
+
</script>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
cb9484690723cd1304953f5475e6ec0dd3f089c0
|
Incremented version number and added flash security warning to README.
|
diff --git a/README b/README
index 63b9f1d..5eac2b5 100644
--- a/README
+++ b/README
@@ -1,8 +1,14 @@
-ChromeTaster v0.1
+ChromeTaster v0.2
By Bjorn Stromberg
This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
+IMPORTANT: To get MP3 playback to work you must add this extension to the flash allow list. You must visit this page - http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html and add the following line:
+
+chrome-extension:\\igkglbhdogeemdmnfdjgapgacfhgiikd\
+
+I have tried Chrome's HTML5 support, but found their player to be absolutely unusable due to the amateur hour 0.5 second buffer causing awful interaction delays. When they fix this I'll switch it over to HTML5, until then you must add this extension to your flash allow list.
+
ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
diff --git a/manifest.json b/manifest.json
index dcdcdd0..919d4f4 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,23 +1,23 @@
{
"name": "ChromeTaster",
- "version": "0.1",
+ "version": "0.2",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
"default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
"16": "tumblr-audio-icon-16.png",
"32": "tumblr-audio-icon-32.png",
"48": "tumblr-audio-icon-48.png",
"64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"include_globs": [ "http://*.tumblr.com/*", "http://bjornstar.com/*", "http://toys.tumblrist.com/audio/*" ]
} ]
}
\ No newline at end of file
|
bjornstar/TumTaster
|
beb72f4f098189a726f49315bc76b3e6bdfded07
|
Changed icon to tumblr audio icon, added a few sizes, fixed script.js to only fix next/prev links on show/audio, made popup a little prettier.
|
diff --git a/manifest.json b/manifest.json
index c2c491f..dcdcdd0 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,20 +1,23 @@
{
"name": "ChromeTaster",
"version": "0.1",
"description": "A Chrome extension that keeps track of the MP3s you see and queues them up for playback. (Currently only works on Tumblr)",
"browser_action": {
- "default_icon": "tumblr.gif",
+ "default_icon": "tumblr-audio-icon-16.png",
"default_title": "ChromeTaster",
"popup": "popup.html"
},
"icons": {
- "16": "tumblr.gif"
+ "16": "tumblr-audio-icon-16.png",
+ "32": "tumblr-audio-icon-32.png",
+ "48": "tumblr-audio-icon-48.png",
+ "64": "tumblr-audio-icon-64.png"
},
"background_page": "background.html",
"options_page" : "options.html",
"content_scripts": [ {
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"include_globs": [ "http://*.tumblr.com/*", "http://bjornstar.com/*", "http://toys.tumblrist.com/audio/*" ]
} ]
}
\ No newline at end of file
diff --git a/popup.html b/popup.html
index 517e4b9..f3870d1 100644
--- a/popup.html
+++ b/popup.html
@@ -1,186 +1,200 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a {
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
div#nowplaying {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
- height: 17px;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
+ clear: left;
}
div#nowplaying span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
+ div#heading h1{
+ color: white;
+ float: left;
+ line-height:32px;
+ vertical-align:absmiddle;
+ margin-left:10px;
+ }
+ div#statistics{
+ position:absolute;
+ bottom:0%;
+ }
+ #controls{
+ text-align:center;
+ }
</style>
-<h1>ChromeTaster</h1>
+<div id="heading" style="width:100%;height:64px;"><img src="tumblr-audio-icon-64.png" style="float:left;" /><h1>ChromeTaster</h1></div>
<div id="statistics"><span>No songs found.</span></div>
<div id="nowplaying"><span>Now Playing: </span></div>
-<p><a href="javascript:void(sm.stopAll())">■</a> <a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
+<p id="controls"><a href="javascript:void(sm.stopAll())">■</a> <a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
}
function get_currentsong() {
var song_nowplaying = null;
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
return song_nowplaying;
}
function update_nowplaying() {
var current_song = get_currentsong();
if (current_song) {
var nowplaying = document.getElementById('nowplaying');
nowplaying.innerHTML = '<span>Now Playing: '+current_song.sID+'</span>';
}
}
function update_statistics() {
var count_songs = 0;
count_songs = sm.soundIDs.length;
var statistics = document.getElementById('statistics');
statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
}
function playnextsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playnextsong(current_song_sID);
update_nowplaying();
}
function playrandomsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
update_nowplaying();
}
update_nowplaying();
update_statistics();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
</script>
</html>
\ No newline at end of file
diff --git a/script.js b/script.js
index 673df1d..7fcfe79 100644
--- a/script.js
+++ b/script.js
@@ -1,104 +1,104 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
song_embed[i].parentNode.style.height='54px';
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
//Alright, here's the tough part. We gotta find the permalink for post to go with this audio file.
//There's probably a million ways to do this better.
var post_url = 'http://www.tumblr.com/';
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
post_url = document.getElementById('permalink_'+post_id).parentNode.getAttribute('href');
} else {
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
post_url = anchors[a].href;
}
}
}
}
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
last_embed = song_embed.length;
}
setInterval(taste, 200);
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
- if (currentpage.indexOf('dashboard')>=0) {
+ if (currentpage.indexOf('show/audio')<0) {
return;
}
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
fixaudiopagination();
\ No newline at end of file
diff --git a/tumblr-audio-icon-16.png b/tumblr-audio-icon-16.png
new file mode 100644
index 0000000..52cd862
Binary files /dev/null and b/tumblr-audio-icon-16.png differ
diff --git a/tumblr-audio-icon-32.png b/tumblr-audio-icon-32.png
new file mode 100644
index 0000000..b8aec94
Binary files /dev/null and b/tumblr-audio-icon-32.png differ
diff --git a/tumblr-audio-icon-48.png b/tumblr-audio-icon-48.png
new file mode 100644
index 0000000..e280d5c
Binary files /dev/null and b/tumblr-audio-icon-48.png differ
diff --git a/tumblr-audio-icon-64.png b/tumblr-audio-icon-64.png
new file mode 100644
index 0000000..dd6f9ad
Binary files /dev/null and b/tumblr-audio-icon-64.png differ
|
bjornstar/TumTaster
|
c051fdeba8b6fe5f096da1e04c490cf5d9f5bb3d
|
I forgot to exclude the dashboard, that was unfortunate.
|
diff --git a/script.js b/script.js
index 44fbd2d..673df1d 100644
--- a/script.js
+++ b/script.js
@@ -1,100 +1,104 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
song_embed[i].parentNode.style.height='54px';
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
//Alright, here's the tough part. We gotta find the permalink for post to go with this audio file.
//There's probably a million ways to do this better.
var post_url = 'http://www.tumblr.com/';
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
post_url = document.getElementById('permalink_'+post_id).parentNode.getAttribute('href');
} else {
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
post_url = anchors[a].href;
}
}
}
}
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
last_embed = song_embed.length;
}
setInterval(taste, 200);
function fixaudiopagination() {
var nextpagelink = document.getElementById('next_page_link');
var prevpagelink = document.getElementById('previous_page_link');
var currentpage = window.location.href;
+ if (currentpage.indexOf('dashboard')>=0) {
+ return;
+ }
+
var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
if (isNaN(pagenumber)) {
nextpagelink.href = currentpage+'/2';
} else {
nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
if (prevpagelink) {
prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
}
var dashboard_controls = document.getElementById('dashboard_controls');
if (dashboard_controls) {
dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
}
}
fixaudiopagination();
\ No newline at end of file
|
bjornstar/TumTaster
|
e6b3306317c11cead6a0780b7b7efeb604777403
|
Fixed up the prev/next buttons on the show/audio pages on tumblr.
|
diff --git a/script.js b/script.js
index cd1c8ae..44fbd2d 100644
--- a/script.js
+++ b/script.js
@@ -1,75 +1,100 @@
function addGlobalStyle(css) {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
}
var tumblr_ico = 'data:image/gif;base64,R0lGODlhEAAQAOZuAD9cdyA3TT5bdkBdeCA3Tj1adTZSbCI6VEFeeUtphDhVb0VjfiM7UjdTbiE4T0dlgEhmgjxYc0lnglZfajRQazlVcENgezpWcbrAxzxZdDtYcyM6UT5adSQ7UkRhfDNPaUhlgUJgezlWcDdUbsDJ1FBpgSI5UCE5UL3EzlZtgz1ZdOHh5UFfepadpt/i6Ofo7cDI0is8TVljbjtXcj9JVi8/UTZSbbS6w3CHnTdTbThUbkVifTpXckdlgUlmgkdkgEpngzZTbSs6Sr/I0TpXcV9wgkZkf2V6j0JfejRJXjNMYzhPZUBbdDtYckFbc46hsuHm7D1YcWZ/lkRifUZkgCI6UUpogzVJXrvEzkhmgThUb4WZrOHl7EVifqu0v72/xba9xipDYENhfEZjf0lngyg0QkpohDRQajVRax82TUtphd/f4+vu8yg/WP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAG4ALAAAAAAQABAAAAfYgG5tg4SFhYIHZooJao2OjWEdbT4SZJZQbE6KZoxqkg8PPSBbbGxllZZAVgxtCwtjT1ylMjhSIFkQEKxiHh6lv2wwTEZUPxttCCxIQy6lGBgtNVM7XccAAANRKKVlSVdLIRYWVW0FBRwCJGwvZdgDAwgIJm1NGhERWCtrZecC/gAn2lQQceECmDVrJmg4UiJDBhUO2jQYoUOLF4QYixDhMSOigY82UtzA+IWGAgUVCLQ5QwGNSyUxJpQpIyRIjgYqD3z4cKZnz5Yu0Rwg4CaN0aNIAygN4CYQADs=';
var tumtaster_style = 'background-image:url('+tumblr_ico+'); background-repeat:no-repeat; background-position: 6px 5px; line-height:27px; height:27px; width:207px; vertical-align:middle; font-size:10px; display:block !important; text-align:right; margin-top:1px; font-family:helvetica,arial,sans-serif; text-decoration:none; color:#000000; float:left;';
try {
document.styleSheets[0].insertRule('a.tumtaster {'+tumtaster_style+'}', 0);
} catch (e) {
addGlobalStyle('a.tumtaster {'+tumtaster_style+'}');
}
var last_embed = 0;
var song_embed = document.getElementsByTagName('embed');
function taste() {
for (var i=last_embed;i<song_embed.length;i++) {
if (song_embed[i].getAttribute('src').indexOf('/swf/audio_player') >= 0) {
var song_url = song_embed[i].getAttribute('src').substring(song_embed[i].getAttribute('src').indexOf('audio_file=')+11);
var song_bgcolor = song_url.substring(song_url.length-6);
var song_color = '777777';
song_url = song_url.replace('&color='+song_bgcolor,'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio');
if (song_embed[i].getAttribute('src').indexOf('audio_player_black') >= 0) {
song_bgcolor = '000000';
song_color = 'FFFFFF';
}
var dl_a = document.createElement('a');
dl_a.setAttribute('href', song_url);
dl_a.setAttribute('style', 'background-color: #'+song_bgcolor+'; color: #'+song_color+'; text-decoration: none;');
dl_a.setAttribute('class', 'tumtaster');
dl_a.innerHTML = 'Click to download ';
var dl_span = document.createElement('span');
var dl_br = document.createElement('br');
dl_span.appendChild(dl_br);
dl_span.appendChild(dl_a);
song_embed[i].parentNode.appendChild(dl_span);
song_embed[i].parentNode.style.height='54px';
var post_id = song_url.match(/audio_file\/(\d*)\//)[1];
//Alright, here's the tough part. We gotta find the permalink for post to go with this audio file.
//There's probably a million ways to do this better.
var post_url = 'http://www.tumblr.com/';
if (window.location.href.substring(0,31)=='http://www.tumblr.com/dashboard' || window.location.href.substring(0,36)=='http://www.tumblr.com/show/audio/by/') {
post_url = document.getElementById('permalink_'+post_id).parentNode.getAttribute('href');
} else {
var anchors = document.getElementsByTagName('a');
for (var a in anchors) {
if (anchors[a].href) {
if (anchors[a].href.indexOf('/post/'+post_id+'/')>=0) {
post_url = anchors[a].href;
}
}
}
}
chrome.extension.sendRequest({song_url: song_url, post_id: post_id, post_url: post_url});
}
}
last_embed = song_embed.length;
}
-setInterval(taste, 200);
\ No newline at end of file
+setInterval(taste, 200);
+
+function fixaudiopagination() {
+ var nextpagelink = document.getElementById('next_page_link');
+ var prevpagelink = document.getElementById('previous_page_link');
+ var currentpage = window.location.href;
+
+ var pagenumber = parseInt(currentpage.substring(currentpage.lastIndexOf('/')+1));
+ if (isNaN(pagenumber)) {
+ nextpagelink.href = currentpage+'/2';
+ } else {
+ nextpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
+ }
+ if (prevpagelink) {
+ prevpagelink.href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
+ }
+
+ var dashboard_controls = document.getElementById('dashboard_controls');
+ if (dashboard_controls) {
+ dashboard_controls.children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+1;
+ dashboard_controls.children[1].children[0].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber-1);
+ dashboard_controls.children[1].children[2].href = currentpage.substring(0,currentpage.lastIndexOf('/')+1)+(pagenumber+1);
+ }
+}
+
+fixaudiopagination();
\ No newline at end of file
|
bjornstar/TumTaster
|
fe8927ec06187aa17ff499e3ef8f2e75d2b24d2c
|
Added a real options page with shuffle and repeat.
|
diff --git a/background.html b/background.html
index 334dcc5..6393d40 100644
--- a/background.html
+++ b/background.html
@@ -1,40 +1,57 @@
<html>
<script type="text/javascript" src="soundmanager2.js"></script>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
chrome.extension.onRequest.addListener(
function(song, sender, sendResponse) {
sendResponse({});
playlist[song.song_url] = song.post_url;
var mySoundObject = soundManager.createSound({
id: song.post_url,
url: song.song_url,
onloadfailed: function(){playnextsong(song.post_url)},
onfinish: function(){playnextsong(song.post_url)}
});
});
function playnextsong(previous_song) {
- var bad_idea;
- for (x in playlist) {
- if (playlist[x] != previous_song && bad_idea == previous_song) {
- var mySoundObject = soundManager.getSoundById(playlist[x]);
- mySoundObject.play();
- return;
+ var bad_idea = null;
+ var first_song = null;
+ var next_song = null;
+
+ for (x in soundManager.sounds) {
+ if (soundManager.sounds[x].sID != previous_song && bad_idea == previous_song && next_song == null) {
+ next_song = soundManager.sounds[x].sID;
+ }
+ bad_idea = soundManager.sounds[x].sID;
+ if (first_song == null) {
+ first_song = soundManager.sounds[x].sID;
}
- bad_idea = playlist[x];
+ }
+
+ if (localStorage["shuffle"]) {
+ var s = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ next_song = soundManager.soundIDs[s];
+ }
+
+ if (localStorage["repeat"] && bad_idea == previous_song) {
+ next_song = first_song;
+ }
+
+ if (next_song != null) {
+ var soundNext = soundManager.getSoundById(next_song);
+ soundNext.play();
}
}
function playrandomsong(previous_song) {
var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
- var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
- mySoundObject.play();
- return;
+ var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
+ mySoundObject.play();
}
</script>
<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/options.html b/options.html
index f25224e..7d3384d 100644
--- a/options.html
+++ b/options.html
@@ -1,50 +1,70 @@
<html>
<head>
- <title>Options for Color Chooser</title>
+ <title>Options for ChromeTaster</title>
<script type="text/javascript">
-var defaultColor = "blue";
+var defaultShuffle = false;
+var defaultRepeat = true;
function loadOptions() {
- var favColor = localStorage["favColor"];
+ var shuffle = localStorage["shuffle"];
+ var repeat = localStorage["repeat"];
- // valid colors are red, blue, green and yellow
- if (favColor == undefined || (favColor != "red" && favColor != "blue" && favColor != "green" && favColor != "yellow")) {
- favColor = defaultColor;
- }
+ if (shuffle == undefined) {
+ shuffle = defaultShuffle;
+ }
- var select = document.getElementById("color");
- for (var i = 0; i < select.children.length; i++) {
- var child = select.children[i];
- if (child.value == favColor) {
- child.selected = "true";
- break;
- }
- }
+ if (repeat == undefined) {
+ repeat = defaultRepeat;
+ }
+
+ var select = document.getElementById("optionShuffle");
+ for (var i = 0; i < select.children.length; i++) {
+ var child = select.children[i];
+ if (child.value == shuffle) {
+ child.selected = "true";
+ break;
+ }
+ }
+
+ var select = document.getElementById("optionRepeat");
+ for (var i = 0; i < select.children.length; i++) {
+ var child = select.children[i];
+ if (child.value == repeat) {
+ child.selected = "true";
+ break;
+ }
+ }
}
function saveOptions() {
- var select = document.getElementById("color");
- var color = select.children[select.selectedIndex].value;
- localStorage["favColor"] = color;
+ var selectShuffle = document.getElementById("optionShuffle");
+ localStorage["shuffle"] = selectShuffle.children[selectShuffle.selectedIndex].value;
+ var selectRepeat = document.getElementById("optionRepeat");
+ localStorage["repeat"] = selectRepeat.children[selectRepeat.selectedIndex].value;
}
function eraseOptions() {
- localStorage.removeItem("favColor");
+ localStorage.removeItem("shuffle");
+ localStorage.removeItem("repeat");
location.reload();
}
</script>
</head>
<body onload="loadOptions()">
- <h1>Favorite Color</h1>
- <select id="color">
- <option value="blue">Blue</option>
- <option value="red">Red</option>
- <option value="green">Green</option>
- <option value="yellow">Yellow</option>
+ <h1>ChromeTaster Options</h1>
+ <label for="optionShuffle">Shuffle: </label>
+ <select id="optionShuffle" name="optionShuffle">
+ <option value="false">Off</option>
+ <option value="true">On</option>
</select>
+ <label for="optionRepeat">Repeat: </label>
+ <select id="optionRepeat" name="optionRepeat">
+ <option value="false">Off</option>
+ <option value="true">On</option>
+ </select>
<br />
<button onclick="saveOptions()">Save</button>
<br />
<button onclick="eraseOptions()">Restore default</button>
</body>
</html>
\ No newline at end of file
diff --git a/popup.html b/popup.html
index df99cfc..517e4b9 100644
--- a/popup.html
+++ b/popup.html
@@ -1,177 +1,186 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a {
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
div#nowplaying {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: 17px;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
}
div#nowplaying span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
</style>
<h1>ChromeTaster</h1>
+<div id="statistics"><span>No songs found.</span></div>
<div id="nowplaying"><span>Now Playing: </span></div>
-<p><a href="javascript:void(sm.stopAll())">Stop</a> <a href="javascript:void(pause())">Pause</a> <a href="javascript:void(sm.resumeAll())">Resume</a> <a href="javascript:void(playnextsong())">Next</a> <a href="javascript:void(playrandomsong())">Random</a></p>
+<p><a href="javascript:void(sm.stopAll())">■</a> <a href="javascript:void(pause())">❙ ❙</a> <a href="javascript:void(sm.resumeAll())">▶</a> <a href="javascript:void(playnextsong())">▶▶</a> <a href="javascript:void(playrandomsong())">Random</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
}
function get_currentsong() {
var song_nowplaying = null;
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
return song_nowplaying;
}
function update_nowplaying() {
var current_song = get_currentsong();
if (current_song) {
var nowplaying = document.getElementById('nowplaying');
nowplaying.innerHTML = '<span>Now Playing: '+current_song.sID+'</span>';
}
}
+function update_statistics() {
+ var count_songs = 0;
+ count_songs = sm.soundIDs.length;
+ var statistics = document.getElementById('statistics');
+ statistics.innerHTML = '<span>'+count_songs+' songs found.</span>';
+}
+
function playnextsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playnextsong(current_song_sID);
update_nowplaying();
}
function playrandomsong() {
var current_song = get_currentsong();
var current_song_sID;
if (current_song) {
current_song.stop();
current_song_sID = current_song.sID;
}
bg.playrandomsong(current_song_sID);
update_nowplaying();
}
update_nowplaying();
+update_statistics();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
</script>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
729e01b7450b190859d86f893cf0ae33f1b1f1b3
|
Added shuffle, still needs work to prevent repeats.
|
diff --git a/background.html b/background.html
index ca6ca19..334dcc5 100644
--- a/background.html
+++ b/background.html
@@ -1,32 +1,40 @@
<html>
<script type="text/javascript" src="soundmanager2.js"></script>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
chrome.extension.onRequest.addListener(
function(song, sender, sendResponse) {
sendResponse({});
playlist[song.song_url] = song.post_url;
var mySoundObject = soundManager.createSound({
id: song.post_url,
url: song.song_url,
onloadfailed: function(){playnextsong(song.post_url)},
onfinish: function(){playnextsong(song.post_url)}
});
});
function playnextsong(previous_song) {
var bad_idea;
for (x in playlist) {
if (playlist[x] != previous_song && bad_idea == previous_song) {
var mySoundObject = soundManager.getSoundById(playlist[x]);
mySoundObject.play();
return;
}
bad_idea = playlist[x];
}
}
+
+ function playrandomsong(previous_song) {
+ var x = Math.floor(Math.random()*soundManager.soundIDs.length+1);
+ var mySoundObject = soundManager.getSoundById(soundManager.soundIDs[x]);
+ mySoundObject.play();
+ return;
+ }
+
</script>
<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/popup.html b/popup.html
index 821b969..df99cfc 100644
--- a/popup.html
+++ b/popup.html
@@ -1,162 +1,177 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a {
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
div#nowplaying {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: 17px;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
}
div#nowplaying span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
</style>
<h1>ChromeTaster</h1>
<div id="nowplaying"><span>Now Playing: </span></div>
-<p><a href="javascript:void(sm.stopAll())">Stop</a> <a href="javascript:void(pause())">Pause</a> <a href="javascript:void(sm.resumeAll())">Resume</a> <a href="javascript:void(playnextsong())">Next</a></p>
+<p><a href="javascript:void(sm.stopAll())">Stop</a> <a href="javascript:void(pause())">Pause</a> <a href="javascript:void(sm.resumeAll())">Resume</a> <a href="javascript:void(playnextsong())">Next</a> <a href="javascript:void(playrandomsong())">Random</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
function pause() {
current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
}
function get_currentsong() {
var song_nowplaying = null;
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
return song_nowplaying;
}
function update_nowplaying() {
- var song_nowplaying = get_currentsong();
- if (song_nowplaying) {
+ var current_song = get_currentsong();
+ if (current_song) {
var nowplaying = document.getElementById('nowplaying');
- nowplaying.innerHTML = '<span>Now Playing: '+song_nowplaying.sID+'</span>';
+ nowplaying.innerHTML = '<span>Now Playing: '+current_song.sID+'</span>';
}
}
function playnextsong() {
- current_song = get_currentsong();
- current_song.stop();
- bg.playnextsong(current_song.sID);
+ var current_song = get_currentsong();
+ var current_song_sID;
+ if (current_song) {
+ current_song.stop();
+ current_song_sID = current_song.sID;
+ }
+ bg.playnextsong(current_song_sID);
update_nowplaying();
}
+function playrandomsong() {
+ var current_song = get_currentsong();
+ var current_song_sID;
+ if (current_song) {
+ current_song.stop();
+ current_song_sID = current_song.sID;
+ }
+ bg.playrandomsong(current_song_sID);
+ update_nowplaying();
+}
+
update_nowplaying();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
</script>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
16ae972c23f4e68a3714bbecedc7e1e2f7f85f90
|
Fixed pause to use the current song.
|
diff --git a/popup.html b/popup.html
index d960b92..821b969 100644
--- a/popup.html
+++ b/popup.html
@@ -1,162 +1,162 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a {
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
div#nowplaying {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: 17px;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
}
div#nowplaying span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
</style>
<h1>ChromeTaster</h1>
<div id="nowplaying"><span>Now Playing: </span></div>
<p><a href="javascript:void(sm.stopAll())">Stop</a> <a href="javascript:void(pause())">Pause</a> <a href="javascript:void(sm.resumeAll())">Resume</a> <a href="javascript:void(playnextsong())">Next</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
function pause() {
- current_song = sm.getSoundById(bg.nowplaying);
+ current_song = get_currentsong();
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
}
function get_currentsong() {
var song_nowplaying = null;
for (sound in sm.sounds) {
if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
song_nowplaying = sm.sounds[sound];
}
}
return song_nowplaying;
}
function update_nowplaying() {
var song_nowplaying = get_currentsong();
if (song_nowplaying) {
var nowplaying = document.getElementById('nowplaying');
nowplaying.innerHTML = '<span>Now Playing: '+song_nowplaying.sID+'</span>';
}
}
function playnextsong() {
current_song = get_currentsong();
current_song.stop();
bg.playnextsong(current_song.sID);
update_nowplaying();
}
update_nowplaying();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
</script>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
7b7f75429b842db4490a695268bd4694149d2969
|
Iterate through sounds to find the one that's playing rather than trying to keep two variables in sync. Need better way to update nowplaying for onplay.
|
diff --git a/background.html b/background.html
index 29eee4c..ca6ca19 100644
--- a/background.html
+++ b/background.html
@@ -1,44 +1,32 @@
<html>
<script type="text/javascript" src="soundmanager2.js"></script>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
chrome.extension.onRequest.addListener(
function(song, sender, sendResponse) {
sendResponse({});
playlist[song.song_url] = song.post_url;
var mySoundObject = soundManager.createSound({
id: song.post_url,
url: song.song_url,
onloadfailed: function(){playnextsong(song.post_url)},
- onplay: function(){set_nowplaying(song.post_url)},
onfinish: function(){playnextsong(song.post_url)}
});
});
- function set_nowplaying(post_url) {
- nowplaying = post_url;
- }
-
- function paused() {
- console.log('paused');
- }
-
function playnextsong(previous_song) {
- if(!previous_song) {
- previous_song = nowplaying;
- }
var bad_idea;
for (x in playlist) {
if (playlist[x] != previous_song && bad_idea == previous_song) {
var mySoundObject = soundManager.getSoundById(playlist[x]);
mySoundObject.play();
return;
}
bad_idea = playlist[x];
}
}
</script>
<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/popup.html b/popup.html
index 1491d19..d960b92 100644
--- a/popup.html
+++ b/popup.html
@@ -1,153 +1,162 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a {
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
div#nowplaying {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: 17px;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
}
div#nowplaying span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
</style>
<h1>ChromeTaster</h1>
<div id="nowplaying"><span>Now Playing: </span></div>
<p><a href="javascript:void(sm.stopAll())">Stop</a> <a href="javascript:void(pause())">Pause</a> <a href="javascript:void(sm.resumeAll())">Resume</a> <a href="javascript:void(playnextsong())">Next</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
function pause() {
current_song = sm.getSoundById(bg.nowplaying);
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
- bg.set_nowplaying = post_url;
- update_nowplaying();
+}
+
+function get_currentsong() {
+ var song_nowplaying = null;
+ for (sound in sm.sounds) {
+ if (sm.sounds[sound].playState == 1 && !song_nowplaying) {
+ song_nowplaying = sm.sounds[sound];
+ }
+ }
+ return song_nowplaying;
}
function update_nowplaying() {
- if (bg.nowplaying) {
+ var song_nowplaying = get_currentsong();
+ if (song_nowplaying) {
var nowplaying = document.getElementById('nowplaying');
- nowplaying.innerHTML = '<span>Now Playing: '+bg.nowplaying+'</span>';
- }
+ nowplaying.innerHTML = '<span>Now Playing: '+song_nowplaying.sID+'</span>';
+ }
}
function playnextsong() {
- current_song = sm.getSoundById(bg.nowplaying);
+ current_song = get_currentsong();
current_song.stop();
- bg.playnextsong(bg.nowplaying);
+ bg.playnextsong(current_song.sID);
update_nowplaying();
}
update_nowplaying();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
</script>
</html>
\ No newline at end of file
|
bjornstar/TumTaster
|
ee10193cbdad9b6cd5f4decc922285312035d032
|
Added onloadfailed event to soundmanager, triggers when an mp3 fails to load. ChromeTaster can then handle this event. Current setting is to skip to the next track.
|
diff --git a/background.html b/background.html
index 3fcbf31..29eee4c 100644
--- a/background.html
+++ b/background.html
@@ -1,43 +1,44 @@
<html>
<script type="text/javascript" src="soundmanager2.js"></script>
<script type="text/javascript">
var playlist = new Array();
var nowplaying = null;
chrome.extension.onRequest.addListener(
function(song, sender, sendResponse) {
sendResponse({});
playlist[song.song_url] = song.post_url;
var mySoundObject = soundManager.createSound({
id: song.post_url,
url: song.song_url,
- onplay: function(){nowplaying = this.id},
+ onloadfailed: function(){playnextsong(song.post_url)},
+ onplay: function(){set_nowplaying(song.post_url)},
onfinish: function(){playnextsong(song.post_url)}
});
});
function set_nowplaying(post_url) {
nowplaying = post_url;
}
function paused() {
console.log('paused');
}
function playnextsong(previous_song) {
if(!previous_song) {
previous_song = nowplaying;
}
var bad_idea;
for (x in playlist) {
if (playlist[x] != previous_song && bad_idea == previous_song) {
var mySoundObject = soundManager.getSoundById(playlist[x]);
mySoundObject.play();
return;
}
bad_idea = playlist[x];
}
}
</script>
-<h1>Tumtaster</h1>
+<h1>ChromeTaster</h1>
</html>
\ No newline at end of file
diff --git a/popup.html b/popup.html
index a42aa4c..1491d19 100644
--- a/popup.html
+++ b/popup.html
@@ -1,153 +1,153 @@
<html>
<style type="text/css">
html{
color:black;
font-family:arial,helvetica,sans-serif;
margin:0;
padding:0;
background-color:#2C4762;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAARHCAIAAAC9OZ68AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc9JREFUeNrsVlF2wzAIQzvXLrKD7PyqYwMWdry+fi8fvDYuAQESrn3//H6Z2RtjM5QztjPEGZshPil+SD/aOB/vSDx6LPg5Iz7amclz4BBcyzthSP+DBV6NSfhZYGOPAa3N41642P3Zc/Vz7nnyN4sYvMEn/VhyjV5i5Lzw0GMWH+8x95r3PrDmKz3d59Kfrx5fuDH7ljgcS/QpejPqDNzuj4ml+3ptOM3WIi+yb1nv1sfJRWbfWWrvHPSeDSysfCjzEDzBkzssztOVT6O+4BRvcsze7dpB8c2eBc993rb0dNehzNAGtyeulQdMrdZaFi7pb5LjVm9XLRR9ouJkwTN5zVUDkRuhcxRenrWOyqklJ0LP/XvjSosHzhmmb/Js1Ysd+COaMJlrzE60XeOrZid2tB4SPO8x0a/qj7Jre7yeD6IXK3pRvMRhX/LmPsg5L99jf0Zturus8hvCD3q/Bt+w+P+hJVs1E7uFdYfnvnIO5V0me0x33hWHdZfEe1VHdtytlQvrfSH3KKrmw3/0gkVvYw/s/Kqc0Lkh61TMdV9i7vV4zr0XvdN+Dm5CPiNfnvvdzpu7r2gX9vk9/thjjz322GOfGN7/h3js39tLgAEA5+M4ca0bVE0AAAAASUVORK5CYII=);
background-repeat:repeat-x;
}
h1{
color:black;
}
a {
color:white;
text-decoration:none;
}
ol{
background-attachment: scroll;
background-clip: border-box;
background-color: #2C4762;
background-image: none;
background-origin: padding-box;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: block;
list-style-type:none;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 20px;
padding-left: 20px;
padding-right: 20px;
padding-top: 20px;
}
li a{
color:#444;
}
li{
background-color: white;
border-bottom-color: #BBB;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-style: solid;
border-bottom-width: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
display: list-item;
margin-bottom: 10px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: #444;
outline-style: none;
outline-width: 0px;
padding-bottom: 15px;
padding-left: 20px;
padding-right: 20px;
padding-top: 15px;
position: relative;
word-wrap: break-word;
}
div#nowplaying {
background-attachment: scroll;
background-clip: border-box;
background-color: #BBC552;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAARCAMAAAAi9pZaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRFzdVozdRozNRozNRnfqYzEAAAADRJREFUeNpci8kRADAIAjn67zmI4yc+FBYESWQ0C9TeJUrisCaHiT7UR6natdbYr1/wBBgAClIAMo7zpuYAAAAASUVORK5CYII=);
background-origin: padding-box;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
color: #C4CDD6;
display: block;
font-family: 'Lucida Grande', Verdana, sans-serif;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: 17px;
line-height: normal;
outline-color: #C4CDD6;
outline-style: none;
outline-width: 0px;
padding-bottom: 9px;
padding-left: 10px;
padding-right: 10px;
padding-top: 8px;
position: relative;
}
div#nowplaying span{
color: #3B440F;
cursor: auto;
display: inline;
height: 0px;
outline-color: #3B440F;
outline-style: none;
outline-width: 0px;
text-decoration: none;
width: 0px;
}
</style>
<h1>ChromeTaster</h1>
<div id="nowplaying"><span>Now Playing: </span></div>
<p><a href="javascript:void(sm.stopAll())">Stop</a> <a href="javascript:void(pause())">Pause</a> <a href="javascript:void(sm.resumeAll())">Resume</a> <a href="javascript:void(playnextsong())">Next</a></p>
<script type="text/javascript">
var bg = chrome.extension.getBackgroundPage();
var sm = bg.soundManager;
var pl = bg.playlist;
-var nowplaying = document.getElementById('nowplaying');
function pause() {
current_song = sm.getSoundById(bg.nowplaying);
current_song.pause();
}
function play(song_url,post_url) {
sm.stopAll();
var mySoundObject = sm.getSoundById(post_url);
mySoundObject.play();
bg.set_nowplaying = post_url;
update_nowplaying();
}
function update_nowplaying() {
if (bg.nowplaying) {
+ var nowplaying = document.getElementById('nowplaying');
nowplaying.innerHTML = '<span>Now Playing: '+bg.nowplaying+'</span>';
}
}
function playnextsong() {
current_song = sm.getSoundById(bg.nowplaying);
current_song.stop();
bg.playnextsong(bg.nowplaying);
update_nowplaying();
}
update_nowplaying();
document.write('<ol class="playlist">');
for (x in pl) {
document.write('<li><a href="javascript:void(play(\''+x+'\',\''+pl[x]+'\'))">'+pl[x]+'</a><br />\r\n');
}
document.write('</ol>');
</script>
</html>
\ No newline at end of file
diff --git a/soundmanager2.js b/soundmanager2.js
index b47f07e..e4862cd 100644
--- a/soundmanager2.js
+++ b/soundmanager2.js
@@ -1,553 +1,554 @@
/*!
SoundManager 2: Javascript Sound for the Web
--------------------------------------------
http://schillmania.com/projects/soundmanager2/
Copyright (c) 2007, Scott Schiller. All rights reserved.
Code provided under the BSD License:
http://schillmania.com/projects/soundmanager2/license.txt
V2.95b.20100101
*/
/*jslint undef: true, bitwise: true, newcap: true, immed: true */
var soundManager = null;
function SoundManager(smURL, smID) {
this.flashVersion = 8; // version of flash to require, either 8 or 9. Some API features require Flash 9.
this.debugMode = true; // enable debugging output (div#soundmanager-debug, OR console if available+configured)
this.debugFlash = false; // enable debugging output inside SWF, troubleshoot Flash/browser issues
this.useConsole = true; // use firebug/safari console.log()-type debug console if available
this.consoleOnly = false; // if console is being used, do not create/write to #soundmanager-debug
this.waitForWindowLoad = false; // force SM2 to wait for window.onload() before trying to call soundManager.onload()
this.nullURL = 'null.mp3'; // path to "null" (empty) MP3 file, used to unload sounds (Flash 8 only)
this.allowPolling = true; // allow flash to poll for status update (required for whileplaying() events, peak, sound spectrum functions to work.)
this.useFastPolling = false; // uses 1 msec flash timer interval (vs. default of 20) for higher callback frequency, best combined with useHighPerformance
this.useMovieStar = false; // enable support for Flash 9.0r115+ (codename "MovieStar") MPEG4 audio+video formats (AAC, M4V, FLV, MOV etc.)
this.bgColor = '#ffffff'; // movie (.swf) background color, '#000000' useful if showing on-screen/full-screen video etc.
this.useHighPerformance = false; // position:fixed flash movie can help increase js/flash speed, minimize lag
this.flashLoadTimeout = 1000; // msec to wait for flash movie to load before failing (0 = infinity)
this.wmode = null; // mode to render the flash movie in - null, transparent, opaque (last two allow layering of HTML on top)
this.allowFullScreen = true; // enter full-screen (via double-click on movie) for flash 9+ video
this.allowScriptAccess = 'always'; // for scripting the SWF (object/embed property), either 'always' or 'sameDomain'
this.defaultOptions = {
'autoLoad': false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can)
'stream': true, // allows playing before entire file has loaded (recommended)
'autoPlay': false, // enable playing of file as soon as possible (much faster if "stream" is true)
'onid3': null, // callback function for "ID3 data is added/available"
'onload': null, // callback function for "load finished"
+ 'onloadfailed': null, // callback function for "load failed"
'whileloading': null, // callback function for "download progress update" (X of Y bytes received)
'onplay': null, // callback for "play" start
'onpause': null, // callback for "pause"
'onresume': null, // callback for "resume" (pause toggle)
'whileplaying': null, // callback during play (position update)
'onstop': null, // callback for "user stop"
'onfinish': null, // callback function for "sound finished playing"
'onbeforefinish': null, // callback for "before sound finished playing (at [time])"
'onbeforefinishtime': 5000, // offset (milliseconds) before end of sound to trigger beforefinish (eg. 1000 msec = 1 second)
'onbeforefinishcomplete':null, // function to call when said sound finishes playing
'onjustbeforefinish':null, // callback for [n] msec before end of current sound
'onjustbeforefinishtime':200, // [n] - if not using, set to 0 (or null handler) and event will not fire.
'multiShot': true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time
'multiShotEvents': false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled
'position': null, // offset (milliseconds) to seek to within loaded sound data.
'pan': 0, // "pan" settings, left-to-right, -100 to 100
'volume': 100 // self-explanatory. 0-100, the latter being the max.
};
this.flash9Options = { // flash 9-only options, merged into defaultOptions if flash 9 is being used
'isMovieStar': null, // "MovieStar" MPEG4 audio/video mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
'usePeakData': false, // enable left/right channel peak (level) data
'useWaveformData': false, // enable sound spectrum (raw waveform data) - WARNING: CPU-INTENSIVE: may set CPUs on fire.
'useEQData': false, // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.
'onbufferchange': null, // callback for "isBuffering" property change
'ondataerror': null // callback for waveform/eq data access error (flash playing audio in other tabs/domains)
};
this.movieStarOptions = { // flash 9.0r115+ MPEG4 audio/video options, merged into defaultOptions if flash 9+movieStar mode is enabled
'onmetadata': null, // callback for when video width/height etc. are received
'useVideo': false, // if loading movieStar content, whether to show video
'bufferTime': null // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try up to 3 seconds)
};
// jslint global declarations
/*global SM2_DEFER, sm2Debugger, alert, console, document, navigator, setTimeout, window */
var SMSound = null; // defined later
var _s = this;
var _sm = 'soundManager';
this.version = null;
this.versionNumber = 'V2.95b.20100101';
this.movieURL = null;
this.url = null;
this.altURL = null;
this.swfLoaded = false;
this.enabled = false;
this.o = null;
this.id = (smID || 'sm2movie');
this.oMC = null;
this.sounds = {};
this.soundIDs = [];
this.muted = false;
this.isFullScreen = false; // set later by flash 9+
this.isIE = (navigator.userAgent.match(/MSIE/i));
this.isSafari = (navigator.userAgent.match(/safari/i));
this.debugID = 'soundmanager-debug';
this.debugURLParam = /([#?&])debug=1/i;
this.specialWmodeCase = false;
this._onready = [];
this._debugOpen = true;
this._didAppend = false;
this._appendSuccess = false;
this._didInit = false;
this._disabled = false;
this._windowLoaded = false;
this._hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');
this._debugLevels = ['log', 'info', 'warn', 'error'];
this._defaultFlashVersion = 8;
this._oRemoved = null;
this._oRemovedHTML = null;
var _$ = function(sID) {
return document.getElementById(sID);
};
this.filePatterns = {
flash8: /\.mp3(\?.*)?$/i,
flash9: /\.mp3(\?.*)?$/i
};
this.netStreamTypes = ['aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'mp4v', '3gp', '3g2']; // Flash v9.0r115+ "moviestar" formats
this.netStreamPattern = new RegExp('\\.('+this.netStreamTypes.join('|')+')(\\?.*)?$', 'i');
this.filePattern = null;
this.features = {
buffering: false,
peakData: false,
waveformData: false,
eqData: false,
movieStar: false
};
this.sandbox = {
'type': null,
'types': {
'remote': 'remote (domain-based) rules',
'localWithFile': 'local with file access (no internet access)',
'localWithNetwork': 'local with network (internet access only, no local access)',
'localTrusted': 'local, trusted (local+internet access)'
},
'description': null,
'noRemote': null,
'noLocal': null
};
this._setVersionInfo = function() {
if (_s.flashVersion != 8 && _s.flashVersion != 9) {
alert(_s._str('badFV',_s.flashVersion,_s._defaultFlashVersion));
_s.flashVersion = _s._defaultFlashVersion;
}
_s.version = _s.versionNumber+(_s.flashVersion == 9?' (AS3/Flash 9)':' (AS2/Flash 8)');
// set up default options
if (_s.flashVersion > 8) {
_s.defaultOptions = _s._mergeObjects(_s.defaultOptions, _s.flash9Options);
_s.features.buffering = true;
}
if (_s.flashVersion > 8 && _s.useMovieStar) {
// flash 9+ support for movieStar formats as well as MP3
_s.defaultOptions = _s._mergeObjects(_s.defaultOptions, _s.movieStarOptions);
_s.filePatterns.flash9 = new RegExp('\\.(mp3|'+_s.netStreamTypes.join('|')+')(\\?.*)?$', 'i');
_s.features.movieStar = true;
} else {
_s.useMovieStar = false;
_s.features.movieStar = false;
}
_s.filePattern = _s.filePatterns[(_s.flashVersion != 8?'flash9':'flash8')];
_s.movieURL = (_s.flashVersion == 8?'soundmanager2.swf':'soundmanager2_flash9.swf');
_s.features.peakData = _s.features.waveformData = _s.features.eqData = (_s.flashVersion > 8);
};
this._overHTTP = (document.location?document.location.protocol.match(/http/i):null);
this._waitingforEI = false;
this._initPending = false;
this._tryInitOnFocus = (this.isSafari && typeof document.hasFocus == 'undefined');
this._isFocused = (typeof document.hasFocus != 'undefined'?document.hasFocus():null);
this._okToDisable = !this._tryInitOnFocus;
this.useAltURL = !this._overHTTP; // use altURL if not "online"
var flashCPLink = 'http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html';
this.strings = {
notReady: 'Not loaded yet - wait for soundManager.onload() before calling sound-related methods',
appXHTML: _sm+'_createMovie(): appendChild/innerHTML set failed. May be app/xhtml+xml DOM-related.',
swf404: _sm+': Verify that %s is a valid path.',
tryDebug: 'Try '+_sm+'.debugFlash = true for more security details (output goes to SWF.)',
checkSWF: 'See SWF output for more debug info.',
localFail: _sm+': Non-HTTP page ('+document.location.protocol+' URL?) Review Flash player security settings for this special case:\n'+flashCPLink+'\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/',
waitFocus: _sm+': Special case: Waiting for focus-related event..',
waitImpatient: _sm+': Getting impatient, still waiting for Flash%s...',
waitForever: _sm+': Waiting indefinitely for Flash...',
needFunction: _sm+'.onready(): Function object expected',
badID: 'Warning: Sound ID "%s" should be a string, starting with a non-numeric character',
fl9Vid: 'flash 9 required for video. Exiting.',
noMS: 'MovieStar mode not enabled. Exiting.',
spcWmode: _sm+'._createMovie(): Removing wmode, preventing win32 below-the-fold SWF loading issue',
currentObj: '--- '+_sm+'._debug(): Current sound objects ---',
waitEI: _sm+'._initMovie(): Waiting for ExternalInterface call from Flash..',
waitOnload: _sm+': Waiting for window.onload()',
docLoaded: _sm+': Document already loaded',
onload: _sm+'.initComplete(): calling soundManager.onload()',
onloadOK: _sm+'.onload() complete',
init: '-- '+_sm+'.init() --',
didInit: _sm+'.init(): Already called?',
flashJS: _sm+': Attempting to call Flash from JS..',
noPolling: _sm+': Polling (whileloading()/whileplaying() support) is disabled.',
secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html',
badRemove: 'Warning: Failed to remove flash movie.',
peakWave: 'Warning: peak/waveform/eqData features unsupported for non-MP3 formats',
shutdown: _sm+'.disable(): Shutting down',
queue: _sm+'.onready(): Queueing handler',
smFail: _sm+': Failed to initialise.',
smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.',
manURL: 'SMSound.load(): Using manually-assigned URL',
onURL: _sm+'.load(): current URL already assigned.',
badFV: 'soundManager.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.'
};
this._str = function() { // o [,items to replace]
var params = Array.prototype.slice.call(arguments); // real array, please
var o = params.shift(); // first arg
var str = _s.strings && _s.strings[o]?_s.strings[o]:'';
if (str && params && params.length) {
for (var i=0, j=params.length; i<j; i++) {
str = str.replace('%s',params[i]);
}
}
return str;
};
// --- public methods ---
this.supported = function() {
return (_s._didInit && !_s._disabled);
};
this.getMovie = function(smID) {
return _s.isIE?window[smID]:(_s.isSafari?_$(smID) || document[smID]:_$(smID));
};
this.loadFromXML = function(sXmlUrl) {
try {
_s.o._loadFromXML(sXmlUrl);
} catch(e) {
_s._failSafely();
return true;
}
};
this.createSound = function(oOptions) {
var _cs = 'soundManager.createSound(): ';
if (!_s._didInit) {
throw _s._complain(_cs+_s._str('notReady'), arguments.callee.caller);
}
if (arguments.length == 2) {
// function overloading in JS! :) ..assume simple createSound(id,url) use case
oOptions = {
'id': arguments[0],
'url': arguments[1]
};
}
var thisOptions = _s._mergeObjects(oOptions); // inherit SM2 defaults
var _tO = thisOptions; // alias
if (_tO.id.toString().charAt(0).match(/^[0-9]$/)) { // hopefully this isn't buggy regexp-fu. :D
_s._wD(_cs+_s._str('badID',_tO.id), 2);
}
_s._wD(_cs+_tO.id+' ('+_tO.url+')', 1);
if (_s._idCheck(_tO.id, true)) {
_s._wD(_cs+_tO.id+' exists', 1);
return _s.sounds[_tO.id];
}
if (_s.flashVersion > 8 && _s.useMovieStar) {
if (_tO.isMovieStar === null) {
_tO.isMovieStar = (_tO.url.match(_s.netStreamPattern)?true:false);
}
if (_tO.isMovieStar) {
_s._wD(_cs+'using MovieStar handling');
}
if (_tO.isMovieStar && (_tO.usePeakData || _tO.useWaveformData || _tO.useEQData)) {
_s._wDS('peakWave');
_tO.usePeakData = false;
_tO.useWaveformData = false;
_tO.useEQData = false;
}
}
_s.sounds[_tO.id] = new SMSound(_tO);
_s.soundIDs[_s.soundIDs.length] = _tO.id;
// AS2:
if (_s.flashVersion == 8) {
_s.o._createSound(_tO.id, _tO.onjustbeforefinishtime);
} else {
_s.o._createSound(_tO.id, _tO.url, _tO.onjustbeforefinishtime, _tO.usePeakData, _tO.useWaveformData, _tO.useEQData, _tO.isMovieStar, (_tO.isMovieStar?_tO.useVideo:false), (_tO.isMovieStar?_tO.bufferTime:false));
}
if (_tO.autoLoad || _tO.autoPlay) {
// TODO: does removing timeout here cause problems?
if (_s.sounds[_tO.id]) {
_s.sounds[_tO.id].load(_tO);
}
}
if (_tO.autoPlay) {
_s.sounds[_tO.id].play();
}
return _s.sounds[_tO.id];
};
this.createVideo = function(oOptions) {
var fN = 'soundManager.createVideo(): ';
if (arguments.length == 2) {
oOptions = {
'id': arguments[0],
'url': arguments[1]
};
}
if (_s.flashVersion >= 9) {
oOptions.isMovieStar = true;
oOptions.useVideo = true;
} else {
_s._wD(fN+_s._str('f9Vid'), 2);
return false;
}
if (!_s.useMovieStar) {
_s._wD(fN+_s._str('noMS'), 2);
}
return _s.createSound(oOptions);
};
this.destroySound = function(sID, bFromSound) {
// explicitly destroy a sound before normal page unload, etc.
if (!_s._idCheck(sID)) {
return false;
}
for (var i=0; i<_s.soundIDs.length; i++) {
if (_s.soundIDs[i] == sID) {
_s.soundIDs.splice(i, 1);
continue;
}
}
// conservative option: avoid crash with flash 8
// calling destroySound() within a sound onload() might crash firefox, certain flavours of winXP+flash 8??
// if (_s.flashVersion != 8) {
_s.sounds[sID].unload();
// }
if (!bFromSound) {
// ignore if being called from SMSound instance
_s.sounds[sID].destruct();
}
delete _s.sounds[sID];
};
this.destroyVideo = this.destroySound;
this.load = function(sID, oOptions) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].load(oOptions);
};
this.unload = function(sID) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].unload();
};
this.play = function(sID, oOptions) {
var fN = 'soundManager.play(): ';
if (!_s._didInit) {
throw _s._complain(fN+_s._str('notReady'), arguments.callee.caller);
}
if (!_s._idCheck(sID)) {
if (typeof oOptions != 'Object') {
oOptions = {
url: oOptions
}; // overloading use case: play('mySound','/path/to/some.mp3');
}
if (oOptions && oOptions.url) {
// overloading use case, creation+playing of sound: .play('someID',{url:'/path/to.mp3'});
_s._wD(fN+'attempting to create "'+sID+'"', 1);
oOptions.id = sID;
_s.createSound(oOptions);
} else {
return false;
}
}
_s.sounds[sID].play(oOptions);
};
this.start = this.play; // just for convenience
this.setPosition = function(sID, nMsecOffset) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].setPosition(nMsecOffset);
};
this.stop = function(sID) {
if (!_s._idCheck(sID)) {
return false;
}
_s._wD('soundManager.stop('+sID+')', 1);
_s.sounds[sID].stop();
};
this.stopAll = function() {
_s._wD('soundManager.stopAll()', 1);
for (var oSound in _s.sounds) {
if (_s.sounds[oSound] instanceof SMSound) {
_s.sounds[oSound].stop(); // apply only to sound objects
}
}
};
this.pause = function(sID) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].pause();
};
this.pauseAll = function() {
for (var i=_s.soundIDs.length; i--;) {
_s.sounds[_s.soundIDs[i]].pause();
}
};
this.resume = function(sID) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].resume();
};
this.resumeAll = function() {
for (var i=_s.soundIDs.length; i--;) {
_s.sounds[_s.soundIDs[i]].resume();
}
};
this.togglePause = function(sID) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].togglePause();
};
this.setPan = function(sID, nPan) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].setPan(nPan);
};
this.setVolume = function(sID, nVol) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].setVolume(nVol);
};
this.mute = function(sID) {
var fN = 'soundManager.mute(): ';
if (typeof sID != 'string') {
sID = null;
}
if (!sID) {
_s._wD(fN+'Muting all sounds');
for (var i=_s.soundIDs.length; i--;) {
_s.sounds[_s.soundIDs[i]].mute();
}
_s.muted = true;
} else {
if (!_s._idCheck(sID)) {
return false;
}
_s._wD(fN+'Muting "'+sID+'"');
_s.sounds[sID].mute();
}
};
this.muteAll = function() {
_s.mute();
};
this.unmute = function(sID) {
var fN = 'soundManager.unmute(): ';
if (typeof sID != 'string') {
sID = null;
}
if (!sID) {
_s._wD(fN+'Unmuting all sounds');
for (var i=_s.soundIDs.length; i--;) {
_s.sounds[_s.soundIDs[i]].unmute();
}
_s.muted = false;
} else {
if (!_s._idCheck(sID)) {
return false;
}
_s._wD(fN+'Unmuting "'+sID+'"');
_s.sounds[sID].unmute();
}
};
this.unmuteAll = function() {
_s.unmute();
};
this.toggleMute = function(sID) {
if (!_s._idCheck(sID)) {
return false;
}
_s.sounds[sID].toggleMute();
};
this.getMemoryUse = function() {
if (_s.flashVersion == 8) {
// not supported in Flash 8
return 0;
}
if (_s.o) {
return parseInt(_s.o._getMemoryUse(), 10);
}
};
this.disable = function(bNoDisable) {
// destroy all functions
if (typeof bNoDisable == 'undefined') {
bNoDisable = false;
}
if (_s._disabled) {
return false;
}
_s._disabled = true;
_s._wDS('shutdown', 1);
for (var i=_s.soundIDs.length; i--;) {
_s._disableObject(_s.sounds[_s.soundIDs[i]]);
}
_s.initComplete(bNoDisable); // fire "complete", despite fail
// _s._disableObject(_s); // taken out to allow reboot()
};
this.canPlayURL = function(sURL) {
return (sURL?(sURL.match(_s.filePattern)?true:false):null);
};
this.getSoundById = function(sID, suppressDebug) {
if (!sID) {
throw new Error('SoundManager.getSoundById(): sID is null/undefined');
}
var result = _s.sounds[sID];
if (!result && !suppressDebug) {
@@ -976,970 +977,980 @@ if (_s.debugMode) {
o.style.display = 'none';
} else {
oT.innerHTML = '-';
o.style.display = 'block';
}
_s._debugOpen = !_s._debugOpen;
};
this._toggleDebug._protected = true;
this._debug = function() {
_s._wDS('currentObj', 1);
for (var i=0, j = _s.soundIDs.length; i<j; i++) {
_s.sounds[_s.soundIDs[i]]._debug();
}
};
this._debugTS = function(sEventType, bSuccess, sMessage) {
// troubleshooter debug hooks
if (typeof sm2Debugger != 'undefined') {
try {
sm2Debugger.handleEvent(sEventType, bSuccess, sMessage);
} catch(e) {
// oh well
}
}
};
this._debugTS._protected = true;
this._mergeObjects = function(oMain, oAdd) {
// non-destructive merge
var o1 = {}; // clone o1
for (var i in oMain) {
if (oMain.hasOwnProperty(i)) {
o1[i] = oMain[i];
}
}
var o2 = (typeof oAdd == 'undefined'?_s.defaultOptions:oAdd);
for (var o in o2) {
if (o2.hasOwnProperty(o) && typeof o1[o] == 'undefined') {
o1[o] = o2[o];
}
}
return o1;
};
this.createMovie = function(sURL) {
if (sURL) {
_s.url = sURL;
}
_s._initMovie();
};
this.go = this.createMovie; // nice alias
this._initMovie = function() {
// attempt to get, or create, movie
if (_s.o) {
return false; // may already exist
}
_s.o = _s.getMovie(_s.id); // (inline markup)
if (!_s.o) {
if (!_s.oRemoved) {
// try to create
_s._createMovie(_s.id, _s.url);
} else {
// try to re-append removed movie after reboot()
if (!_s.isIE) {
_s.oMC.appendChild(_s.oRemoved);
} else {
_s.oMC.innerHTML = _s.oRemovedHTML;
}
_s.oRemoved = null;
_s._didAppend = true;
}
_s.o = _s.getMovie(_s.id);
}
if (_s.o) {
// _s._wD('soundManager._initMovie(): Got '+_s.o.nodeName+' element ('+(_s._didAppend?'created via JS':'static HTML')+')',1);
if (_s.flashLoadTimeout > 0) {
_s._wDS('waitEI');
}
}
if (typeof _s.oninitmovie == 'function') {
setTimeout(_s.oninitmovie, 1);
}
};
this.waitForExternalInterface = function() {
if (_s._waitingForEI) {
return false;
}
_s._waitingForEI = true;
if (_s._tryInitOnFocus && !_s._isFocused) {
_s._wDS('waitFocus');
return false;
}
if (_s.flashLoadTimeout > 0) {
if (!_s._didInit) {
var p = _s.getMoviePercent();
_s._wD(_s._str('waitImpatient',(p == 100?' (SWF loaded)':(p > 0?' (SWF '+p+'% loaded)':''))));
}
setTimeout(function() {
var p = _s.getMoviePercent();
if (!_s._didInit) {
_s._wD(_sm+': No Flash response within reasonable time after document load.\nLikely causes: '+(p === null || p === 0?'Loading '+_s.movieURL+' may have failed (and/or Flash '+_s.flashVersion+'+ not present?), ':'')+'Flash blocked or JS-Flash security error.'+(_s.debugFlash?' '+_s._str('checkSWF'): ''), 2);
if (!_s._overHTTP) {
_s._wDS('localFail', 2);
if (!_s.debugFlash) {
_s._wDS('tryDebug', 2);
}
}
if (p === 0) {
// 404, or blocked from loading?
_s._wD(_s._str('swf404',_s.url));
}
_s._debugTS('flashtojs', false, ': Timed out'+(_s._overHTTP)?' (Check flash security or flash blockers)':' (No plugin/missing SWF?)');
}
// if still not initialized and no other options, give up
if (!_s._didInit && _s._okToDisable) {
_s._failSafely(true); // don't disable, for reboot()
}
},
_s.flashLoadTimeout);
} else if (!_s._didInit) {
_s._wDS('waitForever');
}
};
this.getMoviePercent = function() {
return (_s.o && typeof _s.o.PercentLoaded != 'undefined'?_s.o.PercentLoaded():null);
};
this.handleFocus = function() {
if (_s._isFocused || !_s._tryInitOnFocus) {
return true;
}
_s._okToDisable = true;
_s._isFocused = true;
_s._wD('soundManager.handleFocus()');
if (_s._tryInitOnFocus) {
// giant Safari 3.1 hack - assume window in focus if mouse is moving, since document.hasFocus() not currently implemented.
window.removeEventListener('mousemove', _s.handleFocus, false);
}
// allow init to restart
_s._waitingForEI = false;
setTimeout(_s.waitForExternalInterface, 500);
// detach event
if (window.removeEventListener) {
window.removeEventListener('focus', _s.handleFocus, false);
} else if (window.detachEvent) {
window.detachEvent('onfocus', _s.handleFocus);
}
};
this.initComplete = function(bNoDisable) {
if (_s._didInit) {
return false;
}
_s._didInit = true;
_s._wD('-- SoundManager 2 '+(_s._disabled?'failed to load':'loaded')+' ('+(_s._disabled?'security/load error':'OK')+') --', 1);
if (_s._disabled || bNoDisable) {
// _s._wD('soundManager.initComplete(): calling soundManager.onerror()',1);
_s._processOnReady();
_s._debugTS('onload', false);
_s.onerror.apply(window);
return false;
} else {
_s._debugTS('onload', true);
}
if (_s.waitForWindowLoad && !_s._windowLoaded) {
_s._wDS('waitOnload');
if (window.addEventListener) {
window.addEventListener('load', _s._initUserOnload, false);
} else if (window.attachEvent) {
window.attachEvent('onload', _s._initUserOnload);
}
return false;
} else {
if (_s.waitForWindowLoad && _s._windowLoaded) {
_s._wDS('docLoaded');
}
_s._initUserOnload();
}
};
this._addOnReady = function(oMethod, oScope) {
_s._onready.push({
'method': oMethod,
'scope': (oScope || null),
'fired': false
});
};
this._processOnReady = function() {
if (!_s._didInit) {
// not ready yet.
return false;
}
var status = {
success: (!_s._disabled)
};
var queue = [];
for (var i=0, j = _s._onready.length; i<j; i++) {
if (_s._onready[i].fired !== true) {
queue.push(_s._onready[i]);
}
}
if (queue.length) {
_s._wD(_sm+': Firing '+queue.length+' onready() item'+(queue.length > 1?'s':''));
for (i = 0, j = queue.length; i<j; i++) {
if (queue[i].scope) {
queue[i].method.apply(queue[i].scope, [status]);
} else {
queue[i].method(status);
}
queue[i].fired = true;
}
}
};
this._initUserOnload = function() {
window.setTimeout(function() {
_s._processOnReady();
_s._wDS('onload', 1);
// call user-defined "onload", scoped to window
_s.onload.apply(window);
_s._wDS('onloadOK', 1);
});
};
this.init = function() {
_s._wDS('init');
// called after onload()
_s._initMovie();
if (_s._didInit) {
_s._wDS('didInit');
return false;
}
// event cleanup
if (window.removeEventListener) {
window.removeEventListener('load', _s.beginDelayedInit, false);
} else if (window.detachEvent) {
window.detachEvent('onload', _s.beginDelayedInit);
}
try {
_s._wDS('flashJS');
_s.o._externalInterfaceTest(false); // attempt to talk to Flash
if (!_s.allowPolling) {
_s._wDS('noPolling', 1);
} else {
_s._setPolling(true, _s.useFastPolling?true:false);
}
if (!_s.debugMode) {
_s.o._disableDebug();
}
_s.enabled = true;
_s._debugTS('jstoflash', true);
} catch(e) {
_s._wD('js/flash exception: '+e.toString());
_s._debugTS('jstoflash', false);
_s._failSafely(true); // don't disable, for reboot()
_s.initComplete();
return false;
}
_s.initComplete();
};
this.beginDelayedInit = function() {
// _s._wD('soundManager.beginDelayedInit()');
_s._windowLoaded = true;
setTimeout(_s.waitForExternalInterface, 500);
setTimeout(_s.beginInit, 20);
};
this.beginInit = function() {
if (_s._initPending) {
return false;
}
_s.createMovie(); // ensure creation if not already done
_s._initMovie();
_s._initPending = true;
return true;
};
this.domContentLoaded = function() {
if (document.removeEventListener) {
document.removeEventListener('DOMContentLoaded', _s.domContentLoaded, false);
}
_s.go();
};
this._externalInterfaceOK = function(flashDate) {
// callback from flash for confirming that movie loaded, EI is working etc.
// flashDate = approx. timing/delay info for JS/flash bridge
if (_s.swfLoaded) {
return false;
}
var eiTime = new Date().getTime();
_s._wD('soundManager._externalInterfaceOK()'+(flashDate?' (~'+(eiTime - flashDate)+' ms)':''));
_s._debugTS('swf', true);
_s._debugTS('flashtojs', true);
_s.swfLoaded = true;
_s._tryInitOnFocus = false;
if (_s.isIE) {
// IE needs a timeout OR delay until window.onload - may need TODO: investigating
setTimeout(_s.init, 100);
} else {
_s.init();
}
};
this._setSandboxType = function(sandboxType) {
var sb = _s.sandbox;
sb.type = sandboxType;
sb.description = sb.types[(typeof sb.types[sandboxType] != 'undefined'?sandboxType:'unknown')];
_s._wD('Flash security sandbox type: '+sb.type);
if (sb.type == 'localWithFile') {
sb.noRemote = true;
sb.noLocal = false;
_s._wDS('secNote', 2);
} else if (sb.type == 'localWithNetwork') {
sb.noRemote = false;
sb.noLocal = true;
} else if (sb.type == 'localTrusted') {
sb.noRemote = false;
sb.noLocal = false;
}
};
this.reboot = function() {
// attempt to reset and init SM2
_s._wD('soundManager.reboot()');
if (_s.soundIDs.length) {
_s._wD('Destroying '+_s.soundIDs.length+' SMSound objects...');
}
for (var i=_s.soundIDs.length; i--;) {
_s.sounds[_s.soundIDs[i]].destruct();
}
// trash ze flash
try {
if (_s.isIE) {
_s.oRemovedHTML = _s.o.innerHTML;
}
_s.oRemoved = _s.o.parentNode.removeChild(_s.o);
_s._wD('Flash movie removed.');
} catch(e) {
// uh-oh.
_s._wDS('badRemove', 2);
}
// actually, force recreate of movie.
_s.oRemovedHTML = null;
_s.oRemoved = null;
_s.enabled = false;
_s._didInit = false;
_s._waitingForEI = false;
_s._initPending = false;
_s._didAppend = false;
_s._appendSuccess = false;
_s._disabled = false;
_s._waitingforEI = true;
_s.swfLoaded = false;
_s.soundIDs = {};
_s.sounds = [];
_s.o = null;
for (i = _s._onready.length; i--;) {
_s._onready[i].fired = false;
}
_s._wD(_sm+': Rebooting...');
window.setTimeout(soundManager.beginDelayedInit, 20);
};
this.destruct = function() {
_s._wD('soundManager.destruct()');
_s.disable(true);
};
// SMSound (sound object)
SMSound = function(oOptions) {
var _t = this;
this.sID = oOptions.id;
this.url = oOptions.url;
this.options = _s._mergeObjects(oOptions);
this.instanceOptions = this.options; // per-play-instance-specific options
this._iO = this.instanceOptions; // short alias
// assign property defaults (volume, pan etc.)
this.pan = this.options.pan;
this.volume = this.options.volume;
this._lastURL = null;
this._debug = function() {
if (_s.debugMode) {
var stuff = null;
var msg = [];
var sF = null;
var sfBracket = null;
var maxLength = 64; // # of characters of function code to show before truncating
for (stuff in _t.options) {
if (_t.options[stuff] !== null) {
if (_t.options[stuff] instanceof Function) {
// handle functions specially
sF = _t.options[stuff].toString();
sF = sF.replace(/\s\s+/g, ' '); // normalize spaces
sfBracket = sF.indexOf('{');
msg[msg.length] = ' '+stuff+': {'+sF.substr(sfBracket+1, (Math.min(Math.max(sF.indexOf('\n') - 1, maxLength), maxLength))).replace(/\n/g, '')+'... }';
} else {
msg[msg.length] = ' '+stuff+': '+_t.options[stuff];
}
}
}
_s._wD('SMSound() merged options: {\n'+msg.join(', \n')+'\n}');
}
};
this._debug();
this.id3 = {
/*
Name/value pairs set via Flash when available - see reference for names (download documentation):
http://livedocs.macromedia.com/flash/8/
Previously-live URL:
http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001567.html
(eg., this.id3.songname or this.id3['songname'])
*/
};
this.resetProperties = function(bLoaded) {
_t.bytesLoaded = null;
_t.bytesTotal = null;
_t.position = null;
_t.duration = null;
_t.durationEstimate = null;
_t.loaded = false;
_t.playState = 0;
_t.paused = false;
_t.readyState = 0; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success
_t.muted = false;
_t.didBeforeFinish = false;
_t.didJustBeforeFinish = false;
_t.isBuffering = false;
_t.instanceOptions = {};
_t.instanceCount = 0;
_t.peakData = {
left: 0,
right: 0
};
_t.waveformData = {
left: [],
right: []
};
_t.eqData = [];
// dirty hack for now: also have left/right arrays off this, maintain compatibility
_t.eqData.left = [];
_t.eqData.right = [];
};
_t.resetProperties();
// --- public methods ---
this.load = function(oOptions) {
if (typeof oOptions != 'undefined') {
_t._iO = _s._mergeObjects(oOptions);
_t.instanceOptions = _t._iO;
} else {
oOptions = _t.options;
_t._iO = oOptions;
_t.instanceOptions = _t._iO;
if (_t._lastURL && _t._lastURL != _t.url) {
_s._wDS('manURL');
_t._iO.url = _t.url;
_t.url = null;
}
}
if (typeof _t._iO.url == 'undefined') {
_t._iO.url = _t.url;
}
_s._wD('soundManager.load(): '+_t._iO.url, 1);
if (_t._iO.url == _t.url && _t.readyState !== 0 && _t.readyState != 2) {
_s._wDS('onURL', 1);
return false;
}
_t.url = _t._iO.url;
_t._lastURL = _t._iO.url;
_t.loaded = false;
_t.readyState = 1;
_t.playState = 0; // (oOptions.autoPlay?1:0); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)
try {
if (_s.flashVersion == 8) {
_s.o._load(_t.sID, _t._iO.url, _t._iO.stream, _t._iO.autoPlay, (_t._iO.whileloading?1:0));
} else {
_s.o._load(_t.sID, _t._iO.url, _t._iO.stream?true:false, _t._iO.autoPlay?true:false); // ,(_tO.whileloading?true:false)
if (_t._iO.isMovieStar && _t._iO.autoLoad && !_t._iO.autoPlay) {
// special case: MPEG4 content must start playing to load, then pause to prevent playing.
_t.pause();
}
}
} catch(e) {
_s._wDS('smError', 2);
_s._debugTS('onload', false);
_s.onerror();
_s.disable();
}
};
+
+ this.loadfailed = function() {
+ if (_t._iO.onloadfailed) {
+ _s._wD('SMSound.onloadfailed(): "'+_t.sID+'"');
+ _t._iO.onloadfailed.apply(_t);
+ }
+ };
this.unload = function() {
// Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3
// Flash 9/AS3: Close stream, preventing further load
if (_t.readyState !== 0) {
_s._wD('SMSound.unload(): "'+_t.sID+'"');
if (_t.readyState != 2) { // reset if not error
_t.setPosition(0, true); // reset current sound positioning
}
_s.o._unload(_t.sID, _s.nullURL);
// reset load/status flags
_t.resetProperties();
}
};
this.destruct = function() {
// kill sound within Flash
_s._wD('SMSound.destruct(): "'+_t.sID+'"');
_s.o._destroySound(_t.sID);
_s.destroySound(_t.sID, true); // ensure deletion from controller
};
this.play = function(oOptions) {
var fN = 'SMSound.play(): ';
if (!oOptions) {
oOptions = {};
}
_t._iO = _s._mergeObjects(oOptions, _t._iO);
_t._iO = _s._mergeObjects(_t._iO, _t.options);
_t.instanceOptions = _t._iO;
if (_t.playState == 1) {
var allowMulti = _t._iO.multiShot;
if (!allowMulti) {
_s._wD(fN+'"'+_t.sID+'" already playing (one-shot)', 1);
return false;
} else {
_s._wD(fN+'"'+_t.sID+'" already playing (multi-shot)', 1);
}
}
if (!_t.loaded) {
if (_t.readyState === 0) {
_s._wD(fN+'Attempting to load "'+_t.sID+'"', 1);
// try to get this sound playing ASAP
//_t._iO.stream = true; // breaks stream=false case?
_t._iO.autoPlay = true;
// TODO: need to investigate when false, double-playing
// if (typeof oOptions.autoPlay=='undefined') _tO.autoPlay = true; // only set autoPlay if unspecified here
_t.load(_t._iO); // try to get this sound playing ASAP
} else if (_t.readyState == 2) {
_s._wD(fN+'Could not load "'+_t.sID+'" - exiting', 2);
return false;
} else {
_s._wD(fN+'"'+_t.sID+'" is loading - attempting to play..', 1);
}
} else {
_s._wD(fN+'"'+_t.sID+'"');
}
if (_t.paused) {
_t.resume();
} else {
_t.playState = 1;
if (!_t.instanceCount || _s.flashVersion > 8) {
_t.instanceCount++;
}
_t.position = (typeof _t._iO.position != 'undefined' && !isNaN(_t._iO.position)?_t._iO.position:0);
if (_t._iO.onplay) {
_t._iO.onplay.apply(_t);
}
_t.setVolume(_t._iO.volume, true); // restrict volume to instance options only
_t.setPan(_t._iO.pan, true);
_s.o._start(_t.sID, _t._iO.loop || 1, (_s.flashVersion == 9?_t.position:_t.position / 1000));
}
};
this.start = this.play; // just for convenience
this.stop = function(bAll) {
if (_t.playState == 1) {
_t.playState = 0;
_t.paused = false;
// if (_s.defaultOptions.onstop) _s.defaultOptions.onstop.apply(_s);
if (_t._iO.onstop) {
_t._iO.onstop.apply(_t);
}
_s.o._stop(_t.sID, bAll);
_t.instanceCount = 0;
_t._iO = {};
// _t.instanceOptions = _t._iO;
}
};
this.setPosition = function(nMsecOffset, bNoDebug) {
if (typeof nMsecOffset == 'undefined') {
nMsecOffset = 0;
}
var offset = Math.min(_t.duration, Math.max(nMsecOffset, 0)); // position >= 0 and <= current available (loaded) duration
_t._iO.position = offset;
if (!bNoDebug) {
// _s._wD('SMSound.setPosition('+nMsecOffset+')'+(nMsecOffset != offset?', corrected value: '+offset:''));
}
_s.o._setPosition(_t.sID, (_s.flashVersion == 9?_t._iO.position:_t._iO.position / 1000), (_t.paused || !_t.playState)); // if paused or not playing, will not resume (by playing)
};
this.pause = function() {
if (_t.paused || _t.playState === 0) {
return false;
}
_s._wD('SMSound.pause()');
_t.paused = true;
_s.o._pause(_t.sID);
if (_t._iO.onpause) {
_t._iO.onpause.apply(_t);
}
};
this.resume = function() {
if (!_t.paused || _t.playState === 0) {
return false;
}
_s._wD('SMSound.resume()');
_t.paused = false;
_s.o._pause(_t.sID); // flash method is toggle-based (pause/resume)
if (_t._iO.onresume) {
_t._iO.onresume.apply(_t);
}
};
this.togglePause = function() {
_s._wD('SMSound.togglePause()');
if (_t.playState === 0) {
_t.play({
position: (_s.flashVersion == 9?_t.position:_t.position / 1000)
});
return false;
}
if (_t.paused) {
_t.resume();
} else {
_t.pause();
}
};
this.setPan = function(nPan, bInstanceOnly) {
if (typeof nPan == 'undefined') {
nPan = 0;
}
if (typeof bInstanceOnly == 'undefined') {
bInstanceOnly = false;
}
_s.o._setPan(_t.sID, nPan);
_t._iO.pan = nPan;
if (!bInstanceOnly) {
_t.pan = nPan;
}
};
this.setVolume = function(nVol, bInstanceOnly) {
if (typeof nVol == 'undefined') {
nVol = 100;
}
if (typeof bInstanceOnly == 'undefined') {
bInstanceOnly = false;
}
_s.o._setVolume(_t.sID, (_s.muted && !_t.muted) || _t.muted?0:nVol);
_t._iO.volume = nVol;
if (!bInstanceOnly) {
_t.volume = nVol;
}
};
this.mute = function() {
_t.muted = true;
_s.o._setVolume(_t.sID, 0);
};
this.unmute = function() {
_t.muted = false;
var hasIO = typeof _t._iO.volume != 'undefined';
_s.o._setVolume(_t.sID, hasIO?_t._iO.volume:_t.options.volume);
};
this.toggleMute = function() {
if (_t.muted) {
_t.unmute();
} else {
_t.mute();
}
};
// --- "private" methods called by Flash ---
this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration) {
if (!_t._iO.isMovieStar) {
_t.bytesLoaded = nBytesLoaded;
_t.bytesTotal = nBytesTotal;
_t.duration = Math.floor(nDuration);
_t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10);
if (_t.durationEstimate === undefined) {
// reported bug?
_t.durationEstimate = _t.duration;
}
if (_t.readyState != 3 && _t._iO.whileloading) {
_t._iO.whileloading.apply(_t);
}
} else {
_t.bytesLoaded = nBytesLoaded;
_t.bytesTotal = nBytesTotal;
_t.duration = Math.floor(nDuration);
_t.durationEstimate = _t.duration;
if (_t.readyState != 3 && _t._iO.whileloading) {
_t._iO.whileloading.apply(_t);
}
}
};
this._onid3 = function(oID3PropNames, oID3Data) {
// oID3PropNames: string array (names)
// ID3Data: string array (data)
_s._wD('SMSound._onid3(): "'+this.sID+'" ID3 data received.');
var oData = [];
for (var i=0, j = oID3PropNames.length; i<j; i++) {
oData[oID3PropNames[i]] = oID3Data[i];
// _s._wD(oID3PropNames[i]+': '+oID3Data[i]);
}
_t.id3 = _s._mergeObjects(_t.id3, oData);
if (_t._iO.onid3) {
_t._iO.onid3.apply(_t);
}
};
this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) {
if (isNaN(nPosition) || nPosition === null) {
return false; // Flash may return NaN at times
}
if (_t.playState === 0 && nPosition > 0) {
// can happen at the end of a video where nPosition == 33 for some reason, after finishing.???
// can also happen with a normal stop operation. This resets the position to 0.
// _s._writeDebug('Note: Not playing, but position = '+nPosition);
nPosition = 0;
}
_t.position = nPosition;
if (_s.flashVersion > 8) {
if (_t._iO.usePeakData && typeof oPeakData != 'undefined' && oPeakData) {
_t.peakData = {
left: oPeakData.leftPeak,
right: oPeakData.rightPeak
};
}
if (_t._iO.useWaveformData && typeof oWaveformDataLeft != 'undefined' && oWaveformDataLeft) {
_t.waveformData = {
left: oWaveformDataLeft.split(','),
right: oWaveformDataRight.split(',')
};
}
if (_t._iO.useEQData) {
if (typeof oEQData != 'undefined' && oEQData.leftEQ) {
var eqLeft = oEQData.leftEQ.split(',');
_t.eqData = eqLeft;
_t.eqData.left = eqLeft;
if (typeof oEQData.rightEQ != 'undefined' && oEQData.rightEQ) {
_t.eqData.right = oEQData.rightEQ.split(',');
}
}
}
}
if (_t.playState == 1) {
// special case/hack: ensure buffering is false (instant load from cache, thus buffering stuck at 1?)
if (_t.isBuffering) {
_t._onbufferchange(0);
}
if (_t._iO.whileplaying) {
_t._iO.whileplaying.apply(_t); // flash may call after actual finish
}
if (_t.loaded && _t._iO.onbeforefinish && _t._iO.onbeforefinishtime && !_t.didBeforeFinish && _t.duration - _t.position <= _t._iO.onbeforefinishtime) {
_s._wD('duration-position <= onbeforefinishtime: '+_t.duration+' - '+_t.position+' <= '+_t._iO.onbeforefinishtime+' ('+(_t.duration - _t.position)+')');
_t._onbeforefinish();
}
}
};
this._onload = function(bSuccess) {
var fN = 'SMSound._onload(): ';
bSuccess = (bSuccess == 1?true:false);
_s._wD(fN+'"'+_t.sID+'"'+(bSuccess?' loaded.':' failed to load? - '+_t.url), (bSuccess?1:2));
if (!bSuccess) {
if (_s.sandbox.noRemote === true) {
_s._wD(fN+_s._str('noNet'), 1);
}
if (_s.sandbox.noLocal === true) {
_s._wD(fN+_s._str('noLocal'), 1);
}
}
_t.loaded = bSuccess;
_t.readyState = bSuccess?3:2;
+ if (_t.readyState==2) {
+ _t.loadfailed();
+ }
if (_t._iO.onload) {
_t._iO.onload.apply(_t);
}
};
this._onbeforefinish = function() {
if (!_t.didBeforeFinish) {
_t.didBeforeFinish = true;
if (_t._iO.onbeforefinish) {
_s._wD('SMSound._onbeforefinish(): "'+_t.sID+'"');
_t._iO.onbeforefinish.apply(_t);
}
}
};
this._onjustbeforefinish = function(msOffset) {
// msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)
if (!_t.didJustBeforeFinish) {
_t.didJustBeforeFinish = true;
if (_t._iO.onjustbeforefinish) {
_s._wD('SMSound._onjustbeforefinish(): "'+_t.sID+'"');
_t._iO.onjustbeforefinish.apply(_t);
}
}
};
this._onfinish = function() {
// sound has finished playing
// TODO: calling user-defined onfinish() should happen after setPosition(0)
// OR: onfinish() and then setPosition(0) is bad.
if (_t._iO.onbeforefinishcomplete) {
_t._iO.onbeforefinishcomplete.apply(_t);
}
// reset some state items
_t.didBeforeFinish = false;
_t.didJustBeforeFinish = false;
if (_t.instanceCount) {
_t.instanceCount--;
if (!_t.instanceCount) {
// reset instance options
// _t.setPosition(0);
_t.playState = 0;
_t.paused = false;
_t.instanceCount = 0;
_t.instanceOptions = {};
}
if (!_t.instanceCount || _t._iO.multiShotEvents) {
// fire onfinish for last, or every instance
if (_t._iO.onfinish) {
_s._wD('SMSound._onfinish(): "'+_t.sID+'"');
_t._iO.onfinish.apply(_t);
}
}
} else {
if (_t.useVideo) {
// video has finished
// may need to reset position for next play call, "rewind"
// _t.setPosition(0);
}
// _t.setPosition(0);
}
};
this._onmetadata = function(oMetaData) {
// movieStar mode only
var fN = 'SMSound.onmetadata()';
_s._wD(fN);
// Contains a subset of metadata. Note that files may have their own unique metadata.
// http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html
if (!oMetaData.width && !oMetaData.height) {
_s._wDS('noWH');
oMetaData.width = 320;
oMetaData.height = 240;
}
_t.metadata = oMetaData; // potentially-large object from flash
_t.width = oMetaData.width;
_t.height = oMetaData.height;
if (_t._iO.onmetadata) {
_s._wD(fN+': "'+_t.sID+'"');
_t._iO.onmetadata.apply(_t);
}
_s._wD(fN+' complete');
};
this._onbufferchange = function(bIsBuffering) {
var fN = 'SMSound._onbufferchange()';
if (_t.playState === 0) {
// ignore if not playing
return false;
}
if (bIsBuffering == _t.isBuffering) {
// ignore initial "false" default, if matching
_s._wD(fN+': ignoring false default / loaded sound');
return false;
}
_t.isBuffering = (bIsBuffering == 1?true:false);
if (_t._iO.onbufferchange) {
_s._wD(fN+': '+bIsBuffering);
_t._iO.onbufferchange.apply(_t);
}
};
this._ondataerror = function(sError) {
// flash 9 wave/eq data handler
if (_t.playState > 0) { // hack: called at start, and end from flash at/after onfinish().
_s._wD('SMSound._ondataerror(): '+sError);
if (_t._iO.ondataerror) {
_t._iO.ondataerror.apply(_t);
}
} else {
// _s._wD('SMSound._ondataerror(): ignoring');
}
};
}; // SMSound()
this._onfullscreenchange = function(bFullScreen) {
_s._wD('onfullscreenchange(): '+bFullScreen);
_s.isFullScreen = (bFullScreen == 1?true:false);
if (!_s.isFullScreen) {
// attempt to restore window focus after leaving full-screen
try {
window.focus();
_s._wD('window.focus()');
} catch(e) {
// oh well
}
}
};
// register a few event handlers
if (window.addEventListener) {
window.addEventListener('focus', _s.handleFocus, false);
window.addEventListener('load', _s.beginDelayedInit, false);
window.addEventListener('unload', _s.destruct, false);
if (_s._tryInitOnFocus) {
window.addEventListener('mousemove', _s.handleFocus, false); // massive Safari focus hack
}
} else if (window.attachEvent) {
window.attachEvent('onfocus', _s.handleFocus);
window.attachEvent('onload', _s.beginDelayedInit);
window.attachEvent('unload', _s.destruct);
} else {
// no add/attachevent support - safe to assume no JS -> Flash either.
_s._debugTS('onload', false);
soundManager.onerror();
soundManager.disable();
}
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', _s.domContentLoaded, false);
}
} // SoundManager()
// var SM2_DEFER = true; // un-comment or define in your own script to prevent immediate SoundManager() constructor call+start-up.
// if deferring, construct later with window.soundManager = new SoundManager(); followed by soundManager.beginDelayedInit();
if (typeof SM2_DEFER == 'undefined' || !SM2_DEFER) {
soundManager = new SoundManager();
}
\ No newline at end of file
|
bjornstar/TumTaster
|
3e41a69f36ccdcf65fa99d22be724523b3d1a2f6
|
Added README
|
diff --git a/README b/README
new file mode 100644
index 0000000..63b9f1d
--- /dev/null
+++ b/README
@@ -0,0 +1,8 @@
+ChromeTaster v0.1
+By Bjorn Stromberg
+
+This is a Chrome extension that slurps up all the links to MP3s that you see and queues them up for playback. It's built on top of a greasemonkey script that I wrote called TumTaster that creates download links for MP3s on Tumblr.
+
+ChromeTaster uses SoundManager2 for it's MP3 playback. You can get more information about SoundManager2 at: http://www.schillmania.com/projects/soundmanager2
+
+
|
tef/crawler
|
0465616eee1c2785e0cd3a066dde97ee4bff89e9
|
more moving shit around, one session per scraper thread, usin links everywhere
|
diff --git a/crawler.py b/crawler.py
index ea545df..ae61338 100644
--- a/crawler.py
+++ b/crawler.py
@@ -1,62 +1,380 @@
-#!/usr/bin/env python2.5
+#!/usr/bin/python
"""An example website downloader, similar in functionality to
-a primitive wget. It has one third party dependency (requests), and
-is written for Python 2.5. MIT License"""
+a primitive wget. needs hanzo-warc-tools and requests """
-import sys
-import os.path
import logging
+import threading
+import os
+import re
+import os.path
+import sys
+from urlparse import urlparse, urlunparse
+from HTMLParser import HTMLParser, HTMLParseError
from optparse import OptionParser
+from datetime import datetime
+from threading import Thread,Condition,Lock
+from collections import deque, namedtuple
+from contextlib import contextmanager
+from uuid import uuid4
-from scraper import scrape, Scraper, ScraperQueue
+# third party deps
+import requests
+from hanzo.warctools import warc
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.add_option("-L", "--log-level", dest="log_level")
parser.add_option("-P", "--prefix", dest="roots", action="append",
help="download urls if they match this prefix, can be given multiple times")
parser.add_option("--pool", dest="pool_size")
parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info", roots = [])
+
+
+
+Link = namedtuple('Link','url depth ')
+
+
+class Scraper(Thread):
+ def __init__(self, queue, output_directory, name, **args):
+ self.queue = queue
+ if not output_directory:
+ output_directory = os.getcwd()
+ self.output = output_directory
+ Thread.__init__(self, name=name, **args)
+ self.session = requests.session()
+
+ def run(self):
+ if not os.path.exists(self.output):
+ os.makedirs(self.output)
+ filename = os.path.join(self.output, self.getName()+".warc")
+ logging.debug("Creating file: %s"%filename)
+ with open(filename,"ab") as fh:
+ while self.queue.active():
+ with self.queue.consume_top() as link:
+ if link:
+ self.scrape(link, fh)
+ logging.info(self.getName()+" exiting")
+
+ def scrape(self, link, fh):
+ (depth, url) = link
+ logging.info(self.getName()+" getting "+url)
+ try:
+ response = self.session.get(url)
+
+ except requests.exceptions.RequestException as ex:
+ logging.warn("Can't fetch url: %s error:%s"%(url,ex))
+ return
+
+ links = self.extract_links(response, depth)
+
+ if links:
+ self.queue.enqueue(links)
+
+ self.write(response, fh)
+
+
+ def extract_links(self,response, depth):
+ links = ()
+ content_type = response.headers['Content-Type']
+ if content_type.find('html') > -1:
+ try:
+ html = LinkParser()
+ html.feed(response.text)
+ html.close()
+ links = html.get_abs_links(response.url, depth)
+
+ except HTMLParseError,ex:
+ logging.warning("failed to extract links for %s, %s"%(url,ex))
+
+ else:
+ logging.debug("skipping extracting links for %s:"%response.url)
+
+ return links
+
+ def write(self,response, fh):
+
+ request=response.request
+ request_id = "<uin:uuid:%s>"%uuid4()
+ response_id = "<uin:uuid:%s>"%uuid4()
+ date = warc.warc_datetime_str(datetime.utcnow())
+
+ request_raw = ["%s %s HTTP/1.1"%(request.method, request.full_url)]
+ request_raw.extend("%s: %s"%(k,v) for k,v in request.headers.iteritems())
+ content = request._enc_data
+ request_raw.extend([("Content-Length: %d"%len(content)),"",content])
+ request_raw = "\r\n".join(str(s) for s in request_raw)
+
+ response_raw = ["HTTP/1.1 %d -"%(response.status_code)]
+ response_raw.extend("%s: %s"%(k,v) for k,v in response.headers.iteritems())
+ content=response.content
+ response_raw.extend([("Content-Length: %d"%len(content)),"",content])
+ response_raw = "\r\n".join(str(s) for s in response_raw)
+
+ requestw = warc.make_request(request_id, date, request.url, ('application/http;msgtype=request', request_raw), response_id)
+ responsew = warc.make_response(response_id, date, response.url, ('application/http;msgtype=response', response_raw), request_id)
+
+ requestw.write_to(fh)
+ responsew.write_to(fh)
+
+
+
+
+class ScraperQueue(object):
+ """
+ Created with an initial set of urls to read, a set of roots to constrain
+ all links by, and a recursion limit, this is a queue of yet to be read urls.
+
+ There are three basic methods consume_top, active and enqueue
+
+ """
+ def __init__(self, urls, roots, limit):
+ self.unread_set = set()
+ self.unread_queue = deque()
+ self.visited = set()
+
+ self.roots=roots
+ self.limit=limit
+ self.excluded = set()
+ self.active_consumers=0
+
+ self.update_lock = Lock()
+ self.waiting_consumers = Condition()
+
+ self.enqueue(Link(u, 0) for u in urls)
+
+ def active(self):
+ """Returns True if there are items waiting to be read,
+ or False if the queue is empty, and no-one is currently processing an item
+
+ If someone is processing an item, then it blocks until it can return True or False
+ as above
+ """
+ if self.unread_queue:
+ return True
+ elif self.active_consumers == 0:
+ return False
+ else:
+ self.waiting_consumers.acquire()
+ while (not self.unread_queue) and self.active_consumers > 0:
+ logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
+ self.waiting_consumers.wait()
+ logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
+ self.waiting_consumers.release()
+ return bool(self.unread_queue)
+
+
+ def enqueue(self, links):
+ """Updates the queue with the new links at a given depth"""
+ with self.update_lock:
+ for url,depth in links:
+ if self.will_follow(url) and (self.limit is None or depth < self.limit):
+ self.unread_set.add(url)
+ self.unread_queue.append((depth,url))
+
+ else:
+ self.excluded.add(url)
+ logging.debug("Excluding %s" %url)
+
+
+ def consume_top(self):
+ """Because we need to track when consumers are active (and potentially
+ adding things to the queue), we use a contextmanager to take
+ the top of the queue:
+
+ i.e with queue.consume_top() as top: ...
+
+ Will return None if the queue is currently empty
+ """
+ @contextmanager
+ def manager():
+ if not self.unread_queue:
+ yield None
+ else:
+ out=None
+ with self.update_lock:
+ if self.unread_queue:
+ self.active_consumers+=1
+ out =self.unread_queue.popleft()
+ yield out
+ # error handling
+ if out:
+ with self.update_lock:
+ url = out[1]
+ self.visited.add(url)
+ self.unread_set.remove(url)
+ self.active_consumers-=1
+ self.wake_up_consumers()
+
+ return manager()
+
+
+
+ def will_follow(self, url):
+ if url not in self.unread_set and url not in self.visited:
+ return any(url.startswith(root) for root in self.roots)
+ return False
+
+
+
+ def wake_up_consumers(self):
+ # if there is data to be processed or nothing happening
+ if self.unread_queue or self.active_consumers == 0:
+ logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
+ self.waiting_consumers.acquire()
+ self.waiting_consumers.notifyAll()
+ self.waiting_consumers.release()
+
+
+
+
+
+def attr_extractor(*names):
+ def _extractor(attrs):
+ return [value for key,value in attrs if key in names and value]
+ return _extractor
+
+def meta_extractor(attrs):
+ content = [value for key,value in attrs if key =="content" and value]
+ urls = []
+ for value in content:
+ for pair in value.split(";"):
+ bits = pair.split("=",2)
+ if len(bits)>1 and bits[0].lower()=="url":
+ urls.append(bits[1].strip())
+ return urls
+
+
+
+class LinkParser(HTMLParser):
+ def __init__(self):
+ self.links = []
+ HTMLParser.__init__(self)
+ self.base = None
+
+ self.tag_extractor = {
+ "a": attr_extractor("href"),
+ "applet": attr_extractor("code"),
+ "area": attr_extractor("href"),
+ "bgsound": attr_extractor("src"),
+ "body": attr_extractor("background"),
+ "embed": attr_extractor("href","src"),
+ "fig": attr_extractor("src"),
+ "form": attr_extractor("action"),
+ "frame": attr_extractor("src"),
+ "iframe": attr_extractor("src"),
+ "img": attr_extractor("href","src","lowsrc"),
+ "input": attr_extractor("src"),
+ "link": attr_extractor("href"),
+ "layer": attr_extractor("src"),
+ "object": attr_extractor("data"),
+ "overlay": attr_extractor("src"),
+ "script": attr_extractor("src"),
+ "table": attr_extractor("background"),
+ "td": attr_extractor("background"),
+ "th": attr_extractor("background"),
+
+ "meta": meta_extractor,
+ "base": self.base_extractor,
+ }
+
+ def base_extractor(self, attrs):
+ base = [value for key,value in attrs if key == "href" and value]
+ if base:
+ self.base = base[-1]
+ return ()
+
+ def handle_starttag(self, tag, attrs):
+ extractor = self.tag_extractor.get(tag, None)
+ if extractor:
+ self.links.extend(extractor(attrs))
+
+
+ def get_abs_links(self, url, base_depth):
+ if self.base:
+ url = self.base
+ full_urls = []
+ root = urlparse(url)
+ root_dir = os.path.split(root.path)[0]
+ for link in self.links:
+ parsed = urlparse(link)
+ if not parsed.netloc: # does it have no protocol or host, i.e relative
+ if parsed.path.startswith("/"):
+ parsed = root[0:2] + parsed[2:5] + (None,)
+ else:
+ dir = root_dir
+ path = parsed.path
+ while True:
+ if path.startswith("../"):
+ path=path[3:]
+ dir=os.path.split(dir)[0]
+ elif path.startswith("./"):
+ path=path[2:]
+ else:
+ break
+
+ parsed = root[0:2] + (os.path.join(dir, path),) + parsed[3:5] + (None,)
+ new_link = urlunparse(parsed)
+ logging.debug("relative %s -> %s"%(link, new_link))
+ link=new_link
+
+ else:
+ logging.debug("absolute %s"%link)
+ full_urls.append(link)
+ return [Link(link, base_depth+1) for link in full_urls]
+
+def scrape(scraper, queue, pool_size):
+ pool = [scraper(queue=queue, name="scraper-%d"%name) for name in range(pool_size)]
+ for p in pool:
+ p.start()
+
+ for p in pool:
+ p.join()
+
+ read, excluded = queue.visited, queue.excluded
+
+ logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
+
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
queue = ScraperQueue(
urls,
roots = options.roots if options.roots else [os.path.split(url)[0] for url in urls],
limit=max(0,int(options.recursion_limit)) if options.recursion_limit else None,
)
def scraper(**args):
return Scraper(
output_directory=options.output_directory,
**args
)
scrape(
queue = queue,
scraper=scraper,
pool_size=max(1,int(options.pool_size)),
)
return 0
+
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/scraper/__init__.py b/scraper/__init__.py
deleted file mode 100644
index aea6a88..0000000
--- a/scraper/__init__.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""A bulk downloader"""
-from __future__ import with_statement
-
-
-import logging
-import threading
-import os
-import re
-import os.path
-
-from datetime import datetime
-from urlparse import urlparse
-from threading import Thread,Condition,Lock
-from collections import deque, namedtuple
-from contextlib import contextmanager
-from uuid import uuid4
-
-from .htmlparser import LinkParser, HTMLParseError
-
-import requests
-try:
- from hanzo.warctools import warc
-except:
- WarcRecord = None
-
-Link = namedtuple('Link','url depth ')
-
-def scrape(scraper, queue, pool_size):
- pool = [scraper(queue=queue, name="scraper-%d"%name) for name in range(pool_size)]
- for p in pool:
- p.start()
-
- for p in pool:
- p.join()
-
- read, excluded = queue.visited, queue.excluded
-
- logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
-
-class Scraper(Thread):
- def __init__(self, queue, output_directory, name, **args):
- self.queue = queue
- if not output_directory:
- output_directory = os.getcwd()
- self.output = output_directory
- Thread.__init__(self, name=name, **args)
-
- def run(self):
- if not os.path.exists(self.output):
- os.makedirs(self.output)
- filename = os.path.join(self.output, self.getName()+".warc")
- logging.debug("Creating file: %s"%filename)
- with open(filename,"ab") as fh:
- while self.queue.active():
- with self.queue.consume_top() as link:
- if link:
- self.scrape(link, fh)
- logging.info(self.getName()+" exiting")
-
- def scrape(self, link, fh):
- (depth, url) = link
- logging.info(self.getName()+" getting "+url)
- try:
- response = requests.get(url)
-
- except requests.exceptions.RequestException as ex:
- logging.warn("Can't fetch url: %s error:%s"%(url,ex))
- return
-
- links = self.extract_links(response)
-
- if links:
- self.queue.enqueue(Link(lnk, depth+1) for lnk in links)
-
- self.write(response, fh)
-
-
- def extract_links(self,response):
- links = ()
- content_type = response.headers['Content-Type']
- if content_type.find('html') > -1:
- try:
- html = LinkParser()
- html.feed(response.text)
- html.close()
- links = html.get_abs_links(response.url)
-
- except HTMLParseError,ex:
- logging.warning("failed to extract links for %s, %s"%(url,ex))
-
- else:
- logging.debug("skipping extracting links for %s:"%response.url)
-
- return links
-
- def write(self,response, fh):
-
- request=response.request
- request_id = "<uin:uuid:%s>"%uuid4()
- response_id = "<uin:uuid:%s>"%uuid4()
- date = warc.warc_datetime_str(datetime.utcnow())
-
- request_raw = ["%s %s HTTP/1.1"%(request.method, request.full_url)]
- request_raw.extend("%s: %s"%(k,v) for k,v in request.headers.iteritems())
- content = request._enc_data
- request_raw.extend([("Content-Length: %d"%len(content)),"",content])
- request_raw = "\r\n".join(str(s) for s in request_raw)
-
- response_raw = ["HTTP/1.1 %d -"%(response.status_code)]
- response_raw.extend("%s: %s"%(k,v) for k,v in response.headers.iteritems())
- content=response.content
- response_raw.extend([("Content-Length: %d"%len(content)),"",content])
- response_raw = "\r\n".join(str(s) for s in response_raw)
-
- requestw = warc.make_request(request_id, date, request.url, ('application/http;msgtype=request', request_raw), response_id)
- responsew = warc.make_response(response_id, date, response.url, ('application/http;msgtype=response', response_raw), request_id)
-
- requestw.write_to(fh)
- responsew.write_to(fh)
-
-
-
-
-class ScraperQueue(object):
- """
- Created with an initial set of urls to read, a set of roots to constrain
- all links by, and a recursion limit, this is a queue of yet to be read urls.
-
- There are three basic methods consume_top, active and enqueue
-
- """
- def __init__(self, urls, roots, limit):
- self.unread_set = set()
- self.unread_queue = deque()
- self.visited = set()
-
- self.roots=roots
- self.limit=limit
- self.excluded = set()
- self.active_consumers=0
-
- self.update_lock = Lock()
- self.waiting_consumers = Condition()
-
- self.enqueue(Link(u, 0) for u in urls)
-
- def active(self):
- """Returns True if there are items waiting to be read,
- or False if the queue is empty, and no-one is currently processing an item
-
- If someone is processing an item, then it blocks until it can return True or False
- as above
- """
- if self.unread_queue:
- return True
- elif self.active_consumers == 0:
- return False
- else:
- self.waiting_consumers.acquire()
- while (not self.unread_queue) and self.active_consumers > 0:
- logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
- self.waiting_consumers.wait()
- logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
- self.waiting_consumers.release()
- return bool(self.unread_queue)
-
-
- def enqueue(self, links):
- """Updates the queue with the new links at a given depth"""
- with self.update_lock:
- for url,depth in links:
- if self.will_follow(url) and (self.limit is None or depth < self.limit):
- self.unread_set.add(url)
- self.unread_queue.append((depth,url))
-
- else:
- self.excluded.add(url)
- logging.debug("Excluding %s" %url)
-
-
- def consume_top(self):
- """Because we need to track when consumers are active (and potentially
- adding things to the queue), we use a contextmanager to take
- the top of the queue:
-
- i.e with queue.consume_top() as top: ...
-
- Will return None if the queue is currently empty
- """
- @contextmanager
- def manager():
- if not self.unread_queue:
- yield None
- else:
- out=None
- with self.update_lock:
- if self.unread_queue:
- self.active_consumers+=1
- out =self.unread_queue.popleft()
- yield out
- # error handling
- if out:
- with self.update_lock:
- url = out[1]
- self.visited.add(url)
- self.unread_set.remove(url)
- self.active_consumers-=1
- self.wake_up_consumers()
-
- return manager()
-
-
-
- def will_follow(self, url):
- if url not in self.unread_set and url not in self.visited:
- return any(url.startswith(root) for root in self.roots)
- return False
-
-
-
- def wake_up_consumers(self):
- # if there is data to be processed or nothing happening
- if self.unread_queue or self.active_consumers == 0:
- logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
- self.waiting_consumers.acquire()
- self.waiting_consumers.notifyAll()
- self.waiting_consumers.release()
-
diff --git a/scraper/htmlparser.py b/scraper/htmlparser.py
deleted file mode 100644
index 8f7e547..0000000
--- a/scraper/htmlparser.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""Simplified html parser that extracts urls from a document"""
-
-import logging
-import os.path
-
-from urlparse import urlparse, urlunparse
-from HTMLParser import HTMLParser, HTMLParseError
-
-__all__ = ["LinkParser", "HTMLParseError"]
-
-def attr_extractor(*names):
- def _extractor(attrs):
- return [value for key,value in attrs if key in names and value]
- return _extractor
-
-def meta_extractor(attrs):
- content = [value for key,value in attrs if key =="content" and value]
- urls = []
- for value in content:
- for pair in value.split(";"):
- bits = pair.split("=",2)
- if len(bits)>1 and bits[0].lower()=="url":
- urls.append(bits[1].strip())
- return urls
-
-
-
-class LinkParser(HTMLParser):
- def __init__(self):
- self.links = []
- HTMLParser.__init__(self)
- self.base = None
-
- self.tag_extractor = {
- "a": attr_extractor("href"),
- "applet": attr_extractor("code"),
- "area": attr_extractor("href"),
- "bgsound": attr_extractor("src"),
- "body": attr_extractor("background"),
- "embed": attr_extractor("href","src"),
- "fig": attr_extractor("src"),
- "form": attr_extractor("action"),
- "frame": attr_extractor("src"),
- "iframe": attr_extractor("src"),
- "img": attr_extractor("href","src","lowsrc"),
- "input": attr_extractor("src"),
- "link": attr_extractor("href"),
- "layer": attr_extractor("src"),
- "object": attr_extractor("data"),
- "overlay": attr_extractor("src"),
- "script": attr_extractor("src"),
- "table": attr_extractor("background"),
- "td": attr_extractor("background"),
- "th": attr_extractor("background"),
-
- "meta": meta_extractor,
- "base": self.base_extractor,
- }
-
- def base_extractor(self, attrs):
- base = [value for key,value in attrs if key == "href" and value]
- if base:
- self.base = base[-1]
- return ()
-
- def handle_starttag(self, tag, attrs):
- extractor = self.tag_extractor.get(tag, None)
- if extractor:
- self.links.extend(extractor(attrs))
-
-
- def get_abs_links(self, url):
- if self.base:
- url = self.base
- full_urls = []
- root = urlparse(url)
- root_dir = os.path.split(root.path)[0]
- for link in self.links:
- parsed = urlparse(link)
- if not parsed.netloc: # does it have no protocol or host, i.e relative
- if parsed.path.startswith("/"):
- parsed = root[0:2] + parsed[2:5] + (None,)
- else:
- dir = root_dir
- path = parsed.path
- while True:
- if path.startswith("../"):
- path=path[3:]
- dir=os.path.split(dir)[0]
- elif path.startswith("./"):
- path=path[2:]
- else:
- break
-
- parsed = root[0:2] + (os.path.join(dir, path),) + parsed[3:5] + (None,)
- new_link = urlunparse(parsed)
- logging.debug("relative %s -> %s"%(link, new_link))
- link=new_link
-
- else:
- logging.debug("absolute %s"%link)
- full_urls.append(link)
- return full_urls
|
tef/crawler
|
d3056c24cfa4ee4bcfd228d1e741f50f993a6e39
|
append only
|
diff --git a/scraper/__init__.py b/scraper/__init__.py
index fe11c53..aea6a88 100644
--- a/scraper/__init__.py
+++ b/scraper/__init__.py
@@ -1,228 +1,228 @@
"""A bulk downloader"""
from __future__ import with_statement
import logging
import threading
import os
import re
import os.path
from datetime import datetime
from urlparse import urlparse
from threading import Thread,Condition,Lock
from collections import deque, namedtuple
from contextlib import contextmanager
from uuid import uuid4
from .htmlparser import LinkParser, HTMLParseError
import requests
try:
from hanzo.warctools import warc
except:
WarcRecord = None
Link = namedtuple('Link','url depth ')
def scrape(scraper, queue, pool_size):
pool = [scraper(queue=queue, name="scraper-%d"%name) for name in range(pool_size)]
for p in pool:
p.start()
for p in pool:
p.join()
read, excluded = queue.visited, queue.excluded
logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
class Scraper(Thread):
def __init__(self, queue, output_directory, name, **args):
self.queue = queue
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
Thread.__init__(self, name=name, **args)
def run(self):
if not os.path.exists(self.output):
os.makedirs(self.output)
filename = os.path.join(self.output, self.getName()+".warc")
logging.debug("Creating file: %s"%filename)
- with open(filename,"wb") as fh:
+ with open(filename,"ab") as fh:
while self.queue.active():
- with self.queue.consume_top() as top:
- if top:
- (depth, url) = top
- self.scrape(url, depth, fh)
+ with self.queue.consume_top() as link:
+ if link:
+ self.scrape(link, fh)
logging.info(self.getName()+" exiting")
- def scrape(self, url, depth, fh):
+ def scrape(self, link, fh):
+ (depth, url) = link
logging.info(self.getName()+" getting "+url)
try:
response = requests.get(url)
except requests.exceptions.RequestException as ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return
links = self.extract_links(response)
if links:
self.queue.enqueue(Link(lnk, depth+1) for lnk in links)
self.write(response, fh)
def extract_links(self,response):
links = ()
content_type = response.headers['Content-Type']
if content_type.find('html') > -1:
try:
html = LinkParser()
html.feed(response.text)
html.close()
links = html.get_abs_links(response.url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
else:
logging.debug("skipping extracting links for %s:"%response.url)
return links
def write(self,response, fh):
request=response.request
request_id = "<uin:uuid:%s>"%uuid4()
response_id = "<uin:uuid:%s>"%uuid4()
date = warc.warc_datetime_str(datetime.utcnow())
request_raw = ["%s %s HTTP/1.1"%(request.method, request.full_url)]
request_raw.extend("%s: %s"%(k,v) for k,v in request.headers.iteritems())
content = request._enc_data
request_raw.extend([("Content-Length: %d"%len(content)),"",content])
request_raw = "\r\n".join(str(s) for s in request_raw)
response_raw = ["HTTP/1.1 %d -"%(response.status_code)]
response_raw.extend("%s: %s"%(k,v) for k,v in response.headers.iteritems())
content=response.content
response_raw.extend([("Content-Length: %d"%len(content)),"",content])
response_raw = "\r\n".join(str(s) for s in response_raw)
requestw = warc.make_request(request_id, date, request.url, ('application/http;msgtype=request', request_raw), response_id)
responsew = warc.make_response(response_id, date, response.url, ('application/http;msgtype=response', response_raw), request_id)
requestw.write_to(fh)
responsew.write_to(fh)
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
self.unread_set = set()
self.unread_queue = deque()
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
self.enqueue(Link(u, 0) for u in urls)
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
return bool(self.unread_queue)
def enqueue(self, links):
"""Updates the queue with the new links at a given depth"""
with self.update_lock:
for url,depth in links:
if self.will_follow(url) and (self.limit is None or depth < self.limit):
self.unread_set.add(url)
self.unread_queue.append((depth,url))
else:
self.excluded.add(url)
logging.debug("Excluding %s" %url)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
out=None
with self.update_lock:
if self.unread_queue:
self.active_consumers+=1
out =self.unread_queue.popleft()
yield out
# error handling
if out:
with self.update_lock:
url = out[1]
self.visited.add(url)
self.unread_set.remove(url)
self.active_consumers-=1
self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
|
tef/crawler
|
422ff8e4678fd6036d1dca75b3964ec3020579e4
|
we make warcs :3
|
diff --git a/scraper/__init__.py b/scraper/__init__.py
index 2fcb11c..fe11c53 100644
--- a/scraper/__init__.py
+++ b/scraper/__init__.py
@@ -1,233 +1,228 @@
"""A bulk downloader"""
from __future__ import with_statement
import logging
import threading
import os
import re
import os.path
+from datetime import datetime
from urlparse import urlparse
from threading import Thread,Condition,Lock
from collections import deque, namedtuple
from contextlib import contextmanager
+from uuid import uuid4
from .htmlparser import LinkParser, HTMLParseError
import requests
try:
- from hanzo.warctools import WarcRecord
+ from hanzo.warctools import warc
except:
WarcRecord = None
Link = namedtuple('Link','url depth ')
def scrape(scraper, queue, pool_size):
pool = [scraper(queue=queue, name="scraper-%d"%name) for name in range(pool_size)]
for p in pool:
p.start()
for p in pool:
p.join()
read, excluded = queue.visited, queue.excluded
logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
class Scraper(Thread):
- def __init__(self, queue, output_directory, **args):
+ def __init__(self, queue, output_directory, name, **args):
self.queue = queue
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
- Thread.__init__(self, **args)
+ Thread.__init__(self, name=name, **args)
def run(self):
- while self.queue.active():
- with self.queue.consume_top() as top:
- if top:
- (depth, url) = top
- self.scrape(url, depth)
- logging.info(self.getName()+" exiting")
-
- def scrape(self, url, depth):
+ if not os.path.exists(self.output):
+ os.makedirs(self.output)
+ filename = os.path.join(self.output, self.getName()+".warc")
+ logging.debug("Creating file: %s"%filename)
+ with open(filename,"wb") as fh:
+ while self.queue.active():
+ with self.queue.consume_top() as top:
+ if top:
+ (depth, url) = top
+ self.scrape(url, depth, fh)
+ logging.info(self.getName()+" exiting")
+
+ def scrape(self, url, depth, fh):
logging.info(self.getName()+" getting "+url)
try:
response = requests.get(url)
except requests.exceptions.RequestException as ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return
links = self.extract_links(response)
if links:
self.queue.enqueue(Link(lnk, depth+1) for lnk in links)
- self.write(response)
+ self.write(response, fh)
def extract_links(self,response):
links = ()
content_type = response.headers['Content-Type']
if content_type.find('html') > -1:
try:
html = LinkParser()
html.feed(response.text)
html.close()
links = html.get_abs_links(response.url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
else:
logging.debug("skipping extracting links for %s:"%response.url)
return links
- def write(self,response):
- url = response.url
- data = response.content
- try:
- filename = get_file_name(self.output, url)
- create_necessary_dirs(filename)
- logging.debug("Creating file: %s"%filename)
- with open(filename,"wb") as foo:
- foo.write(data)
- except StandardError, e:
- logging.warn(e)
+ def write(self,response, fh):
+
+ request=response.request
+ request_id = "<uin:uuid:%s>"%uuid4()
+ response_id = "<uin:uuid:%s>"%uuid4()
+ date = warc.warc_datetime_str(datetime.utcnow())
+
+ request_raw = ["%s %s HTTP/1.1"%(request.method, request.full_url)]
+ request_raw.extend("%s: %s"%(k,v) for k,v in request.headers.iteritems())
+ content = request._enc_data
+ request_raw.extend([("Content-Length: %d"%len(content)),"",content])
+ request_raw = "\r\n".join(str(s) for s in request_raw)
+
+ response_raw = ["HTTP/1.1 %d -"%(response.status_code)]
+ response_raw.extend("%s: %s"%(k,v) for k,v in response.headers.iteritems())
+ content=response.content
+ response_raw.extend([("Content-Length: %d"%len(content)),"",content])
+ response_raw = "\r\n".join(str(s) for s in response_raw)
+
+ requestw = warc.make_request(request_id, date, request.url, ('application/http;msgtype=request', request_raw), response_id)
+ responsew = warc.make_response(response_id, date, response.url, ('application/http;msgtype=response', response_raw), request_id)
+
+ requestw.write_to(fh)
+ responsew.write_to(fh)
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
self.unread_set = set()
self.unread_queue = deque()
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
self.enqueue(Link(u, 0) for u in urls)
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
return bool(self.unread_queue)
def enqueue(self, links):
"""Updates the queue with the new links at a given depth"""
with self.update_lock:
for url,depth in links:
if self.will_follow(url) and (self.limit is None or depth < self.limit):
self.unread_set.add(url)
self.unread_queue.append((depth,url))
else:
self.excluded.add(url)
logging.debug("Excluding %s" %url)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
out=None
with self.update_lock:
if self.unread_queue:
self.active_consumers+=1
out =self.unread_queue.popleft()
yield out
# error handling
if out:
with self.update_lock:
url = out[1]
self.visited.add(url)
self.unread_set.remove(url)
self.active_consumers-=1
self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
-# todo strip this out in lieu of warcs
-re_strip = re.compile(r"[^\w\d\-_]")
-
-def clean_query(arg):
- if arg:
- return re.sub(re_strip,"_", arg)
- else:
- return ""
-def get_file_name(output_dir, url):
- data = urlparse(url)
- path = data.path[1:] if data.path.startswith("/") else path
- if path.endswith("/"):
- path = path+"index.html";
-
- path = path + "."+clean_query(data.query) if data.query else path
-
- filename = os.path.join(output_dir+"/", data.netloc, path)
-
- return filename
-
-def create_necessary_dirs(filename):
- dir = os.path.dirname(filename)
- if not os.path.exists(dir):
- os.makedirs(dir)
-
|
tef/crawler
|
c8d46fb5511d46eeb7e3286422b75a5255713882
|
refactoring for requests
|
diff --git a/scraper/__init__.py b/scraper/__init__.py
index 8c02ec6..2fcb11c 100644
--- a/scraper/__init__.py
+++ b/scraper/__init__.py
@@ -1,234 +1,233 @@
"""A bulk downloader"""
from __future__ import with_statement
import logging
import threading
import os
import re
import os.path
from urlparse import urlparse
from threading import Thread,Condition,Lock
from collections import deque, namedtuple
from contextlib import contextmanager
from .htmlparser import LinkParser, HTMLParseError
import requests
+try:
+ from hanzo.warctools import WarcRecord
+except:
+ WarcRecord = None
Link = namedtuple('Link','url depth ')
def scrape(scraper, queue, pool_size):
pool = [scraper(queue=queue, name="scraper-%d"%name) for name in range(pool_size)]
for p in pool:
p.start()
for p in pool:
p.join()
read, excluded = queue.visited, queue.excluded
logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
class Scraper(Thread):
def __init__(self, queue, output_directory, **args):
self.queue = queue
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
Thread.__init__(self, **args)
def run(self):
while self.queue.active():
with self.queue.consume_top() as top:
if top:
(depth, url) = top
self.scrape(url, depth)
logging.info(self.getName()+" exiting")
def scrape(self, url, depth):
logging.info(self.getName()+" getting "+url)
- (data, links) = self.fetch(url)
-
- if data:
- self.save_url(self.output,url, data)
- if links:
- self.queue.enqueue(Link(lnk, depth+1) for lnk in links)
-
-
- def fetch(self, url):
- """Returns a tuple of ("data", [links])"""
- logging.debug("fetching %s"%url)
try:
response = requests.get(url)
- content_type = response.headers['Content-Type']
- data = response.text
-
- if content_type.find("html") >= 0:
- links = self.extract_links(url, data)
- else:
- logging.debug("skipping extracting links for %s:"%url)
- links = ()
- return (data, links)
except requests.exceptions.RequestException as ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
- return (None, ())
+ return
- def extract_links(self,url, data):
- links = ()
- try:
- html = LinkParser()
- html.feed(data)
- html.close()
- links = html.get_abs_links(url)
+ links = self.extract_links(response)
+
+ if links:
+ self.queue.enqueue(Link(lnk, depth+1) for lnk in links)
- except HTMLParseError,ex:
- logging.warning("failed to extract links for %s, %s"%(url,ex))
+ self.write(response)
+
+ def extract_links(self,response):
+ links = ()
+ content_type = response.headers['Content-Type']
+ if content_type.find('html') > -1:
+ try:
+ html = LinkParser()
+ html.feed(response.text)
+ html.close()
+ links = html.get_abs_links(response.url)
+
+ except HTMLParseError,ex:
+ logging.warning("failed to extract links for %s, %s"%(url,ex))
+
+ else:
+ logging.debug("skipping extracting links for %s:"%response.url)
+
return links
- def save_url(self,output_dir, url, data):
+ def write(self,response):
+ url = response.url
+ data = response.content
try:
- filename = get_file_name(output_dir, url)
+ filename = get_file_name(self.output, url)
create_necessary_dirs(filename)
logging.debug("Creating file: %s"%filename)
with open(filename,"wb") as foo:
foo.write(data)
except StandardError, e:
logging.warn(e)
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
self.unread_set = set()
self.unread_queue = deque()
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
self.enqueue(Link(u, 0) for u in urls)
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
return bool(self.unread_queue)
def enqueue(self, links):
"""Updates the queue with the new links at a given depth"""
with self.update_lock:
for url,depth in links:
if self.will_follow(url) and (self.limit is None or depth < self.limit):
self.unread_set.add(url)
self.unread_queue.append((depth,url))
else:
self.excluded.add(url)
logging.debug("Excluding %s" %url)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
out=None
with self.update_lock:
if self.unread_queue:
self.active_consumers+=1
out =self.unread_queue.popleft()
yield out
# error handling
if out:
with self.update_lock:
url = out[1]
self.visited.add(url)
self.unread_set.remove(url)
self.active_consumers-=1
self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
# todo strip this out in lieu of warcs
re_strip = re.compile(r"[^\w\d\-_]")
def clean_query(arg):
if arg:
return re.sub(re_strip,"_", arg)
else:
return ""
def get_file_name(output_dir, url):
data = urlparse(url)
path = data.path[1:] if data.path.startswith("/") else path
if path.endswith("/"):
path = path+"index.html";
path = path + "."+clean_query(data.query) if data.query else path
filename = os.path.join(output_dir+"/", data.netloc, path)
return filename
def create_necessary_dirs(filename):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
|
tef/crawler
|
fcd2b96cd8d9541758432dfcb34551fd1926c10e
|
moving
|
diff --git a/crawler.py b/crawler.py
index 72fc59b..ea545df 100644
--- a/crawler.py
+++ b/crawler.py
@@ -1,62 +1,62 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has one third party dependency (requests), and
is written for Python 2.5. MIT License"""
import sys
import os.path
import logging
from optparse import OptionParser
-from lib.harvester import scrape, Scraper, ScraperQueue
+from scraper import scrape, Scraper, ScraperQueue
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.add_option("-L", "--log-level", dest="log_level")
parser.add_option("-P", "--prefix", dest="roots", action="append",
help="download urls if they match this prefix, can be given multiple times")
parser.add_option("--pool", dest="pool_size")
parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info", roots = [])
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
queue = ScraperQueue(
urls,
roots = options.roots if options.roots else [os.path.split(url)[0] for url in urls],
limit=max(0,int(options.recursion_limit)) if options.recursion_limit else None,
)
def scraper(**args):
return Scraper(
output_directory=options.output_directory,
**args
)
scrape(
queue = queue,
scraper=scraper,
pool_size=max(1,int(options.pool_size)),
)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/lib/htmlparser.py b/htmlparser.py
similarity index 100%
rename from lib/htmlparser.py
rename to htmlparser.py
diff --git a/lib/__init__.py b/lib/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/lib/store.py b/lib/store.py
deleted file mode 100644
index b34b059..0000000
--- a/lib/store.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from __future__ import with_statement
-
-import logging
-import os
-import re
-
-import os.path
-
-from urlparse import urlparse
-
-
-def save_url(output_dir, url, data):
- try:
- filename = get_file_name(output_dir, url)
- create_necessary_dirs(filename)
- logging.debug("Creating file: %s"%filename)
- with open(filename,"wb") as foo:
- foo.write(data)
- except StandardError, e:
- logging.warn(e)
-
-re_strip = re.compile(r"[^\w\d\-_]")
-
-def clean_query(arg):
- if arg:
- return re.sub(re_strip,"_", arg)
- else:
- return ""
-
-
-def get_file_name(output_dir, url):
- data = urlparse(url)
- path = data.path[1:] if data.path.startswith("/") else path
- if path.endswith("/"):
- path = path+"index.html";
-
- path = path + "."+clean_query(data.query) if data.query else path
-
- filename = os.path.join(output_dir+"/", data.netloc, path)
-
- return filename
-
-def create_necessary_dirs(filename):
- dir = os.path.dirname(filename)
- if not os.path.exists(dir):
- os.makedirs(dir)
diff --git a/lib/harvester.py b/scraper.py
similarity index 100%
rename from lib/harvester.py
rename to scraper.py
|
tef/crawler
|
e60c27e6eaebe356e36b09c32bc03105f26941df
|
moving shit around
|
diff --git a/crawler.py b/crawler.py
index d22f535..72fc59b 100644
--- a/crawler.py
+++ b/crawler.py
@@ -1,57 +1,62 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has one third party dependency (requests), and
is written for Python 2.5. MIT License"""
import sys
import os.path
import logging
from optparse import OptionParser
-from lib import Harvester
+from lib.harvester import scrape, Scraper, ScraperQueue
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.add_option("-L", "--log-level", dest="log_level")
parser.add_option("-P", "--prefix", dest="roots", action="append",
help="download urls if they match this prefix, can be given multiple times")
parser.add_option("--pool", dest="pool_size")
parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info", roots = [])
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
- s = Harvester(
+ queue = ScraperQueue(
urls,
roots = options.roots if options.roots else [os.path.split(url)[0] for url in urls],
- output_directory=options.output_directory,
limit=max(0,int(options.recursion_limit)) if options.recursion_limit else None,
+ )
+
+ def scraper(**args):
+ return Scraper(
+ output_directory=options.output_directory,
+ **args
+ )
+
+ scrape(
+ queue = queue,
+ scraper=scraper,
pool_size=max(1,int(options.pool_size)),
)
- s.start()
-
- s.join()
-
-
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/lib/__init__.py b/lib/__init__.py
index efa0708..e69de29 100644
--- a/lib/__init__.py
+++ b/lib/__init__.py
@@ -1,2 +0,0 @@
-from harvester import Harvester
-__all__ = ["Harvester"]
\ No newline at end of file
diff --git a/lib/harvester.py b/lib/harvester.py
index 7d10b86..8c02ec6 100644
--- a/lib/harvester.py
+++ b/lib/harvester.py
@@ -1,173 +1,234 @@
"""A bulk downloader"""
from __future__ import with_statement
-import os.path
import logging
import threading
+import os
+import re
+import os.path
+from urlparse import urlparse
from threading import Thread,Condition,Lock
-from collections import deque
+from collections import deque, namedtuple
from contextlib import contextmanager
-from http import fetch
-from store import save_url
+from .htmlparser import LinkParser, HTMLParseError
-class Harvester(Thread, object):
- """A harvester thread. Initialized with a base set of urls, a list of root-prefixes
- and an output directory,
- will start scraping with start()
+import requests
- It creates a queue for the urls, and spawns a number of sub-threads
- to consume from the queue, and update it with found links
+Link = namedtuple('Link','url depth ')
- All sub-tasks exit when the queue is empty and all sub-tasks are waiting
+def scrape(scraper, queue, pool_size):
+ pool = [scraper(queue=queue, name="scraper-%d"%name) for name in range(pool_size)]
+ for p in pool:
+ p.start()
- """
+ for p in pool:
+ p.join()
+
+ read, excluded = queue.visited, queue.excluded
- def __init__(self, urls, roots, output_directory=None, limit=None, pool_size=4):
- Thread.__init__(self)
- self.queue = ScraperQueue(urls, roots, limit)
+ logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
+class Scraper(Thread):
+ def __init__(self, queue, output_directory, **args):
+ self.queue = queue
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
-
- self.pool_size = pool_size
+ Thread.__init__(self, **args)
def run(self):
- class Scraper(Thread):
- def run(thread):
- while self.queue.active():
- with self.queue.consume_top() as top:
- if top:
- (depth, url) = top
- logging.info(thread.getName()+" getting "+url)
- (data, links) = fetch(url)
+ while self.queue.active():
+ with self.queue.consume_top() as top:
+ if top:
+ (depth, url) = top
+ self.scrape(url, depth)
+ logging.info(self.getName()+" exiting")
+
+ def scrape(self, url, depth):
+ logging.info(self.getName()+" getting "+url)
+ (data, links) = self.fetch(url)
+
+ if data:
+ self.save_url(self.output,url, data)
+ if links:
+ self.queue.enqueue(Link(lnk, depth+1) for lnk in links)
+
+
+ def fetch(self, url):
+ """Returns a tuple of ("data", [links])"""
+ logging.debug("fetching %s"%url)
+ try:
+ response = requests.get(url)
+ content_type = response.headers['Content-Type']
+ data = response.text
+
+ if content_type.find("html") >= 0:
+ links = self.extract_links(url, data)
+ else:
+ logging.debug("skipping extracting links for %s:"%url)
+ links = ()
- if data:
- save_url(self.output,url, data)
- if links:
- self.queue.enqueue(links, depth+1)
- logging.info(thread.getName()+" exiting")
- pool = [Scraper(name="scraper-%d"%name) for name in range(self.pool_size)]
- for p in pool:
- p.start()
+ return (data, links)
+ except requests.exceptions.RequestException as ex:
+ logging.warn("Can't fetch url: %s error:%s"%(url,ex))
+ return (None, ())
- for p in pool:
- p.join()
+ def extract_links(self,url, data):
+ links = ()
+ try:
+ html = LinkParser()
+ html.feed(data)
+ html.close()
+ links = html.get_abs_links(url)
- read, excluded = self.queue.visited, self.queue.excluded
+ except HTMLParseError,ex:
+ logging.warning("failed to extract links for %s, %s"%(url,ex))
- logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
+ return links
+ def save_url(self,output_dir, url, data):
+ try:
+ filename = get_file_name(output_dir, url)
+ create_necessary_dirs(filename)
+ logging.debug("Creating file: %s"%filename)
+ with open(filename,"wb") as foo:
+ foo.write(data)
+ except StandardError, e:
+ logging.warn(e)
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
self.unread_set = set()
self.unread_queue = deque()
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
- self.enqueue(urls, 0)
+ self.enqueue(Link(u, 0) for u in urls)
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
return bool(self.unread_queue)
- def enqueue(self, links, depth):
+ def enqueue(self, links):
"""Updates the queue with the new links at a given depth"""
- if self.limit is None or depth < self.limit:
- with self.update_lock:
- for url in links:
- if self.will_follow(url):
- self.unread_set.add(url)
- self.unread_queue.append((depth,url))
+ with self.update_lock:
+ for url,depth in links:
+ if self.will_follow(url) and (self.limit is None or depth < self.limit):
+ self.unread_set.add(url)
+ self.unread_queue.append((depth,url))
- else:
- self.excluded.add(url)
- logging.debug("Excluding %s" %url)
- else:
- self.excluded.update(links)
+ else:
+ self.excluded.add(url)
+ logging.debug("Excluding %s" %url)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
out=None
with self.update_lock:
if self.unread_queue:
self.active_consumers+=1
out =self.unread_queue.popleft()
yield out
+ # error handling
if out:
with self.update_lock:
url = out[1]
self.visited.add(url)
self.unread_set.remove(url)
self.active_consumers-=1
self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
+
+# todo strip this out in lieu of warcs
+re_strip = re.compile(r"[^\w\d\-_]")
+
+def clean_query(arg):
+ if arg:
+ return re.sub(re_strip,"_", arg)
+ else:
+ return ""
+def get_file_name(output_dir, url):
+ data = urlparse(url)
+ path = data.path[1:] if data.path.startswith("/") else path
+ if path.endswith("/"):
+ path = path+"index.html";
+
+ path = path + "."+clean_query(data.query) if data.query else path
+
+ filename = os.path.join(output_dir+"/", data.netloc, path)
+
+ return filename
+
+def create_necessary_dirs(filename):
+ dir = os.path.dirname(filename)
+ if not os.path.exists(dir):
+ os.makedirs(dir)
+
diff --git a/lib/http.py b/lib/http.py
deleted file mode 100644
index 81f7be3..0000000
--- a/lib/http.py
+++ /dev/null
@@ -1,37 +0,0 @@
-import logging
-
-import requests
-from htmlparser import LinkParser, HTMLParseError
-
-
-def fetch(url):
- """Returns a tuple of ("data", [links])"""
- logging.debug("fetching %s"%url)
- try:
- response = requests.get(url)
- content_type = response.headers['Content-Type']
- data = response.text
-
- if content_type.find("html") >= 0:
- links = extract_links(url, data)
- else:
- logging.debug("skipping extracting links for %s:"%url)
- links = ()
-
- return (data, links)
- except requests.exceptions.RequestException as ex:
- logging.warn("Can't fetch url: %s error:%s"%(url,ex))
- return (None, ())
-
-def extract_links(url, data):
- links = ()
- try:
- html = LinkParser()
- html.feed(data)
- html.close()
- links = html.get_abs_links(url)
-
- except HTMLParseError,ex:
- logging.warning("failed to extract links for %s, %s"%(url,ex))
-
- return links
|
tef/crawler
|
d16782c634453af61ef3b73cdfaada61fa82f7be
|
extending tag extractor
|
diff --git a/crawler.py b/crawler.py
index 8002e8c..d22f535 100644
--- a/crawler.py
+++ b/crawler.py
@@ -1,57 +1,57 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
-a primitive wget. It has no third party dependencies, and
-is written for Python 2.5"""
+a primitive wget. It has one third party dependency (requests), and
+is written for Python 2.5. MIT License"""
import sys
import os.path
import logging
from optparse import OptionParser
from lib import Harvester
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.add_option("-L", "--log-level", dest="log_level")
parser.add_option("-P", "--prefix", dest="roots", action="append",
help="download urls if they match this prefix, can be given multiple times")
parser.add_option("--pool", dest="pool_size")
parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info", roots = [])
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
s = Harvester(
urls,
roots = options.roots if options.roots else [os.path.split(url)[0] for url in urls],
output_directory=options.output_directory,
limit=max(0,int(options.recursion_limit)) if options.recursion_limit else None,
pool_size=max(1,int(options.pool_size)),
)
s.start()
s.join()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/lib/htmlparser.py b/lib/htmlparser.py
index d4f80f6..8f7e547 100644
--- a/lib/htmlparser.py
+++ b/lib/htmlparser.py
@@ -1,70 +1,103 @@
"""Simplified html parser that extracts urls from a document"""
import logging
import os.path
from urlparse import urlparse, urlunparse
from HTMLParser import HTMLParser, HTMLParseError
__all__ = ["LinkParser", "HTMLParseError"]
-def attr_extractor(name):
+def attr_extractor(*names):
def _extractor(attrs):
- return [value for key,value in attrs if key == name and value]
+ return [value for key,value in attrs if key in names and value]
return _extractor
+def meta_extractor(attrs):
+ content = [value for key,value in attrs if key =="content" and value]
+ urls = []
+ for value in content:
+ for pair in value.split(";"):
+ bits = pair.split("=",2)
+ if len(bits)>1 and bits[0].lower()=="url":
+ urls.append(bits[1].strip())
+ return urls
+
+
class LinkParser(HTMLParser):
def __init__(self):
- self.links = []
- HTMLParser.__init__(self)
-
+ self.links = []
+ HTMLParser.__init__(self)
+ self.base = None
- tag_extractor = {
- "a": attr_extractor("href"),
- "link": attr_extractor("href"),
- "img": attr_extractor("src"),
- "script": attr_extractor("src"),
- "iframe": attr_extractor("src"),
- "frame": attr_extractor("src"),
- "embed": attr_extractor("src"),
- }
+ self.tag_extractor = {
+ "a": attr_extractor("href"),
+ "applet": attr_extractor("code"),
+ "area": attr_extractor("href"),
+ "bgsound": attr_extractor("src"),
+ "body": attr_extractor("background"),
+ "embed": attr_extractor("href","src"),
+ "fig": attr_extractor("src"),
+ "form": attr_extractor("action"),
+ "frame": attr_extractor("src"),
+ "iframe": attr_extractor("src"),
+ "img": attr_extractor("href","src","lowsrc"),
+ "input": attr_extractor("src"),
+ "link": attr_extractor("href"),
+ "layer": attr_extractor("src"),
+ "object": attr_extractor("data"),
+ "overlay": attr_extractor("src"),
+ "script": attr_extractor("src"),
+ "table": attr_extractor("background"),
+ "td": attr_extractor("background"),
+ "th": attr_extractor("background"),
+ "meta": meta_extractor,
+ "base": self.base_extractor,
+ }
+ def base_extractor(self, attrs):
+ base = [value for key,value in attrs if key == "href" and value]
+ if base:
+ self.base = base[-1]
+ return ()
def handle_starttag(self, tag, attrs):
extractor = self.tag_extractor.get(tag, None)
if extractor:
self.links.extend(extractor(attrs))
def get_abs_links(self, url):
+ if self.base:
+ url = self.base
full_urls = []
root = urlparse(url)
root_dir = os.path.split(root.path)[0]
for link in self.links:
parsed = urlparse(link)
if not parsed.netloc: # does it have no protocol or host, i.e relative
if parsed.path.startswith("/"):
parsed = root[0:2] + parsed[2:5] + (None,)
else:
dir = root_dir
path = parsed.path
while True:
if path.startswith("../"):
path=path[3:]
dir=os.path.split(dir)[0]
elif path.startswith("./"):
path=path[2:]
else:
break
parsed = root[0:2] + (os.path.join(dir, path),) + parsed[3:5] + (None,)
new_link = urlunparse(parsed)
logging.debug("relative %s -> %s"%(link, new_link))
link=new_link
else:
logging.debug("absolute %s"%link)
full_urls.append(link)
return full_urls
|
tef/crawler
|
846fbc3ab4e172fd51ccc6418d7558825986d076
|
using requests
|
diff --git a/pyget/lib/http.py b/pyget/lib/http.py
index 0758e48..81f7be3 100644
--- a/pyget/lib/http.py
+++ b/pyget/lib/http.py
@@ -1,38 +1,37 @@
import logging
-from urllib2 import urlopen, URLError
-from urlparse import urlparse
+import requests
from htmlparser import LinkParser, HTMLParseError
def fetch(url):
"""Returns a tuple of ("data", [links])"""
logging.debug("fetching %s"%url)
try:
- response = urlopen(url)
- content_type = response.info()['Content-Type']
- data = response.read()
+ response = requests.get(url)
+ content_type = response.headers['Content-Type']
+ data = response.text
if content_type.find("html") >= 0:
links = extract_links(url, data)
else:
logging.debug("skipping extracting links for %s:"%url)
links = ()
return (data, links)
- except URLError, ex:
+ except requests.exceptions.RequestException as ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return (None, ())
def extract_links(url, data):
links = ()
try:
html = LinkParser()
html.feed(data)
html.close()
links = html.get_abs_links(url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
return links
|
tef/crawler
|
55d87b7c7c9312f8042795815e8c391b72e1d785
|
null bug
|
diff --git a/pyget/lib/harvester.py b/pyget/lib/harvester.py
index 5bd4acb..7d10b86 100644
--- a/pyget/lib/harvester.py
+++ b/pyget/lib/harvester.py
@@ -1,173 +1,173 @@
"""A bulk downloader"""
from __future__ import with_statement
import os.path
import logging
import threading
from threading import Thread,Condition,Lock
from collections import deque
from contextlib import contextmanager
from http import fetch
from store import save_url
class Harvester(Thread, object):
"""A harvester thread. Initialized with a base set of urls, a list of root-prefixes
and an output directory,
will start scraping with start()
It creates a queue for the urls, and spawns a number of sub-threads
to consume from the queue, and update it with found links
All sub-tasks exit when the queue is empty and all sub-tasks are waiting
"""
def __init__(self, urls, roots, output_directory=None, limit=None, pool_size=4):
Thread.__init__(self)
self.queue = ScraperQueue(urls, roots, limit)
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
self.pool_size = pool_size
def run(self):
class Scraper(Thread):
def run(thread):
while self.queue.active():
with self.queue.consume_top() as top:
if top:
(depth, url) = top
logging.info(thread.getName()+" getting "+url)
(data, links) = fetch(url)
if data:
save_url(self.output,url, data)
if links:
self.queue.enqueue(links, depth+1)
logging.info(thread.getName()+" exiting")
pool = [Scraper(name="scraper-%d"%name) for name in range(self.pool_size)]
for p in pool:
p.start()
for p in pool:
p.join()
read, excluded = self.queue.visited, self.queue.excluded
logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
self.unread_set = set()
self.unread_queue = deque()
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
self.enqueue(urls, 0)
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
return bool(self.unread_queue)
def enqueue(self, links, depth):
"""Updates the queue with the new links at a given depth"""
if self.limit is None or depth < self.limit:
with self.update_lock:
for url in links:
if self.will_follow(url):
self.unread_set.add(url)
self.unread_queue.append((depth,url))
else:
self.excluded.add(url)
logging.debug("Excluding %s" %url)
else:
self.excluded.update(links)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
out=None
with self.update_lock:
if self.unread_queue:
self.active_consumers+=1
out =self.unread_queue.popleft()
yield out
-
- with self.update_lock:
- url = out[1]
- self.visited.add(url)
- self.unread_set.remove(url)
- self.active_consumers-=1
- self.wake_up_consumers()
+ if out:
+ with self.update_lock:
+ url = out[1]
+ self.visited.add(url)
+ self.unread_set.remove(url)
+ self.active_consumers-=1
+ self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
- logging.debug("Waking up consumers because" +("unread" if self.unread_queue else "finished"))
+ logging.debug("Waking up consumers because " +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
|
tef/crawler
|
f718c4799f42dc0ecceb8466f2ec592aed38a75d
|
added root-set option, fixed thread bug
|
diff --git a/pyget/lib/harvester.py b/pyget/lib/harvester.py
index 202d6c3..5bd4acb 100644
--- a/pyget/lib/harvester.py
+++ b/pyget/lib/harvester.py
@@ -1,169 +1,173 @@
"""A bulk downloader"""
from __future__ import with_statement
import os.path
import logging
import threading
from threading import Thread,Condition,Lock
from collections import deque
from contextlib import contextmanager
from http import fetch
from store import save_url
class Harvester(Thread, object):
- """A harvester thread. Initialized with a base set of urls and an output directory,
+ """A harvester thread. Initialized with a base set of urls, a list of root-prefixes
+ and an output directory,
will start scraping with start()
It creates a queue for the urls, and spawns a number of sub-threads
to consume from the queue, and update it with found links
All sub-tasks exit when the queue is empty and all sub-tasks are waiting
"""
- def __init__(self, urls, output_directory=None, limit=None, pool_size=4):
+ def __init__(self, urls, roots, output_directory=None, limit=None, pool_size=4):
Thread.__init__(self)
-
- roots = [os.path.split(url)[0] for url in urls]
self.queue = ScraperQueue(urls, roots, limit)
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
self.pool_size = pool_size
def run(self):
class Scraper(Thread):
def run(thread):
while self.queue.active():
with self.queue.consume_top() as top:
if top:
(depth, url) = top
logging.info(thread.getName()+" getting "+url)
(data, links) = fetch(url)
if data:
save_url(self.output,url, data)
if links:
self.queue.enqueue(links, depth+1)
logging.info(thread.getName()+" exiting")
pool = [Scraper(name="scraper-%d"%name) for name in range(self.pool_size)]
for p in pool:
p.start()
for p in pool:
p.join()
read, excluded = self.queue.visited, self.queue.excluded
logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
- self.unread_set = set(urls)
- self.unread_queue = deque(((0,url) for url in self.unread_set))
+ self.unread_set = set()
+ self.unread_queue = deque()
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
+ self.enqueue(urls, 0)
+
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
return bool(self.unread_queue)
def enqueue(self, links, depth):
"""Updates the queue with the new links at a given depth"""
if self.limit is None or depth < self.limit:
with self.update_lock:
for url in links:
if self.will_follow(url):
self.unread_set.add(url)
self.unread_queue.append((depth,url))
else:
self.excluded.add(url)
logging.debug("Excluding %s" %url)
else:
self.excluded.update(links)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
+ out=None
with self.update_lock:
- self.active_consumers+=1
- (depth, url) =self.unread_queue.popleft()
- yield (depth, url)
+ if self.unread_queue:
+ self.active_consumers+=1
+ out =self.unread_queue.popleft()
+ yield out
with self.update_lock:
+ url = out[1]
self.visited.add(url)
self.unread_set.remove(url)
self.active_consumers-=1
self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
logging.debug("Waking up consumers because" +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
diff --git a/pyget/pyget.py b/pyget/pyget.py
index df1d794..8002e8c 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,53 +1,57 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has no third party dependencies, and
is written for Python 2.5"""
import sys
+import os.path
import logging
from optparse import OptionParser
from lib import Harvester
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.add_option("-L", "--log-level", dest="log_level")
+parser.add_option("-P", "--prefix", dest="roots", action="append",
+ help="download urls if they match this prefix, can be given multiple times")
parser.add_option("--pool", dest="pool_size")
-parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info")
+parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info", roots = [])
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
s = Harvester(
urls,
+ roots = options.roots if options.roots else [os.path.split(url)[0] for url in urls],
output_directory=options.output_directory,
limit=max(0,int(options.recursion_limit)) if options.recursion_limit else None,
pool_size=max(1,int(options.pool_size)),
)
s.start()
s.join()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
tef/crawler
|
36abfd5c2c9903eb56991ad6497514363c9e2ae7
|
whoops
|
diff --git a/pyget/pyget.py b/pyget/pyget.py
index 441b52b..df1d794 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,53 +1,53 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has no third party dependencies, and
is written for Python 2.5"""
import sys
import logging
from optparse import OptionParser
from lib import Harvester
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.add_option("-L", "--log-level", dest="log_level")
parser.add_option("--pool", dest="pool_size")
parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info")
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
s = Harvester(
urls,
output_directory=options.output_directory,
- limit=min(0,int(options.recursion_limit)) if options.recursion_limit else None,
- pool_size=min(1,int(options.pool_size)),
+ limit=max(0,int(options.recursion_limit)) if options.recursion_limit else None,
+ pool_size=max(1,int(options.pool_size)),
)
s.start()
s.join()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
tef/crawler
|
2fe9bc5bcafd86566999de32a4f92a9b52107f44
|
minor tidy - time to stop
|
diff --git a/pyget/lib/harvester.py b/pyget/lib/harvester.py
index 9a8e82f..202d6c3 100644
--- a/pyget/lib/harvester.py
+++ b/pyget/lib/harvester.py
@@ -1,166 +1,169 @@
"""A bulk downloader"""
from __future__ import with_statement
import os.path
import logging
import threading
from threading import Thread,Condition,Lock
from collections import deque
from contextlib import contextmanager
from http import fetch
from store import save_url
class Harvester(Thread, object):
"""A harvester thread. Initialized with a base set of urls and an output directory,
will start scraping with start()
It creates a queue for the urls, and spawns a number of sub-threads
to consume from the queue, and update it with found links
All sub-tasks exit when the queue is empty and all sub-tasks are waiting
"""
def __init__(self, urls, output_directory=None, limit=None, pool_size=4):
Thread.__init__(self)
roots = [os.path.split(url)[0] for url in urls]
self.queue = ScraperQueue(urls, roots, limit)
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
self.pool_size = pool_size
def run(self):
class Scraper(Thread):
def run(thread):
while self.queue.active():
with self.queue.consume_top() as top:
if top:
(depth, url) = top
logging.info(thread.getName()+" getting "+url)
(data, links) = fetch(url)
if data:
save_url(self.output,url, data)
if links:
self.queue.enqueue(links, depth+1)
logging.info(thread.getName()+" exiting")
pool = [Scraper(name="scraper-%d"%name) for name in range(self.pool_size)]
for p in pool:
p.start()
for p in pool:
p.join()
+ read, excluded = self.queue.visited, self.queue.excluded
+
+ logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
class ScraperQueue(object):
"""
Created with an initial set of urls to read, a set of roots to constrain
all links by, and a recursion limit, this is a queue of yet to be read urls.
There are three basic methods consume_top, active and enqueue
"""
def __init__(self, urls, roots, limit):
self.unread_set = set(urls)
self.unread_queue = deque(((0,url) for url in self.unread_set))
self.visited = set()
self.roots=roots
self.limit=limit
self.excluded = set()
self.active_consumers=0
self.update_lock = Lock()
self.waiting_consumers = Condition()
def active(self):
"""Returns True if there are items waiting to be read,
or False if the queue is empty, and no-one is currently processing an item
If someone is processing an item, then it blocks until it can return True or False
as above
"""
if self.unread_queue:
return True
elif self.active_consumers == 0:
return False
else:
self.waiting_consumers.acquire()
while (not self.unread_queue) and self.active_consumers > 0:
logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
self.waiting_consumers.wait()
logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
self.waiting_consumers.release()
- return bool(self.unread_queue) or self.active_consumers > 0
+ return bool(self.unread_queue)
def enqueue(self, links, depth):
"""Updates the queue with the new links at a given depth"""
if self.limit is None or depth < self.limit:
with self.update_lock:
for url in links:
if self.will_follow(url):
- self.unread_set.add(url)
- self.unread_queue.append((depth,url))
+ self.unread_set.add(url)
+ self.unread_queue.append((depth,url))
else:
self.excluded.add(url)
logging.debug("Excluding %s" %url)
else:
self.excluded.update(links)
def consume_top(self):
"""Because we need to track when consumers are active (and potentially
adding things to the queue), we use a contextmanager to take
the top of the queue:
i.e with queue.consume_top() as top: ...
Will return None if the queue is currently empty
"""
@contextmanager
def manager():
if not self.unread_queue:
yield None
else:
with self.update_lock:
self.active_consumers+=1
(depth, url) =self.unread_queue.popleft()
yield (depth, url)
with self.update_lock:
self.visited.add(url)
self.unread_set.remove(url)
self.active_consumers-=1
self.wake_up_consumers()
return manager()
def will_follow(self, url):
if url not in self.unread_set and url not in self.visited:
return any(url.startswith(root) for root in self.roots)
return False
def wake_up_consumers(self):
# if there is data to be processed or nothing happening
if self.unread_queue or self.active_consumers == 0:
logging.debug("Waking up consumers because" +("unread" if self.unread_queue else "finished"))
self.waiting_consumers.acquire()
self.waiting_consumers.notifyAll()
self.waiting_consumers.release()
diff --git a/pyget/lib/http.py b/pyget/lib/http.py
index fac9b72..0758e48 100644
--- a/pyget/lib/http.py
+++ b/pyget/lib/http.py
@@ -1,38 +1,38 @@
import logging
from urllib2 import urlopen, URLError
from urlparse import urlparse
from htmlparser import LinkParser, HTMLParseError
def fetch(url):
"""Returns a tuple of ("data", [links])"""
- logging.info("fetching %s"%url)
+ logging.debug("fetching %s"%url)
try:
response = urlopen(url)
content_type = response.info()['Content-Type']
data = response.read()
if content_type.find("html") >= 0:
links = extract_links(url, data)
else:
logging.debug("skipping extracting links for %s:"%url)
links = ()
return (data, links)
except URLError, ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return (None, ())
def extract_links(url, data):
links = ()
try:
html = LinkParser()
html.feed(data)
html.close()
links = html.get_abs_links(url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
return links
diff --git a/pyget/lib/store.py b/pyget/lib/store.py
index 7bd001c..b34b059 100644
--- a/pyget/lib/store.py
+++ b/pyget/lib/store.py
@@ -1,46 +1,46 @@
from __future__ import with_statement
import logging
import os
import re
import os.path
from urlparse import urlparse
def save_url(output_dir, url, data):
try:
filename = get_file_name(output_dir, url)
create_necessary_dirs(filename)
- logging.info("Creating file: %s"%filename)
+ logging.debug("Creating file: %s"%filename)
with open(filename,"wb") as foo:
foo.write(data)
except StandardError, e:
logging.warn(e)
re_strip = re.compile(r"[^\w\d\-_]")
def clean_query(arg):
if arg:
return re.sub(re_strip,"_", arg)
else:
return ""
def get_file_name(output_dir, url):
data = urlparse(url)
path = data.path[1:] if data.path.startswith("/") else path
if path.endswith("/"):
path = path+"index.html";
path = path + "."+clean_query(data.query) if data.query else path
filename = os.path.join(output_dir+"/", data.netloc, path)
return filename
def create_necessary_dirs(filename):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
diff --git a/pyget/pyget.py b/pyget/pyget.py
index 59592db..441b52b 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,56 +1,53 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has no third party dependencies, and
is written for Python 2.5"""
import sys
import logging
from optparse import OptionParser
from lib import Harvester
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
-parser.add_option("-L", "--log_level", dest="log_level")
+parser.add_option("-L", "--log-level", dest="log_level")
parser.add_option("--pool", dest="pool_size")
parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info")
def main(argv):
(options, urls) = parser.parse_args(args=argv[1:])
logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
s = Harvester(
urls,
output_directory=options.output_directory,
- limit=options.recursion_limit,
- pool_size=options.pool_size,
+ limit=min(0,int(options.recursion_limit)) if options.recursion_limit else None,
+ pool_size=min(1,int(options.pool_size)),
)
s.start()
s.join()
- read, excluded = s.queue.visited, s.queue.excluded
-
- logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
tef/crawler
|
21fafd39b52d9fa5eebef63e91ee816d5178e73a
|
moving stuff around and making it threaded
|
diff --git a/pyget/lib/__init__.py b/pyget/lib/__init__.py
new file mode 100644
index 0000000..efa0708
--- /dev/null
+++ b/pyget/lib/__init__.py
@@ -0,0 +1,2 @@
+from harvester import Harvester
+__all__ = ["Harvester"]
\ No newline at end of file
diff --git a/pyget/lib/harvester.py b/pyget/lib/harvester.py
new file mode 100644
index 0000000..9a8e82f
--- /dev/null
+++ b/pyget/lib/harvester.py
@@ -0,0 +1,166 @@
+"""A bulk downloader"""
+from __future__ import with_statement
+
+
+import os.path
+import logging
+import threading
+
+from threading import Thread,Condition,Lock
+from collections import deque
+from contextlib import contextmanager
+
+from http import fetch
+from store import save_url
+
+class Harvester(Thread, object):
+ """A harvester thread. Initialized with a base set of urls and an output directory,
+ will start scraping with start()
+
+ It creates a queue for the urls, and spawns a number of sub-threads
+ to consume from the queue, and update it with found links
+
+ All sub-tasks exit when the queue is empty and all sub-tasks are waiting
+
+ """
+
+ def __init__(self, urls, output_directory=None, limit=None, pool_size=4):
+ Thread.__init__(self)
+
+ roots = [os.path.split(url)[0] for url in urls]
+ self.queue = ScraperQueue(urls, roots, limit)
+
+ if not output_directory:
+ output_directory = os.getcwd()
+ self.output = output_directory
+
+ self.pool_size = pool_size
+
+ def run(self):
+ class Scraper(Thread):
+ def run(thread):
+ while self.queue.active():
+ with self.queue.consume_top() as top:
+ if top:
+ (depth, url) = top
+ logging.info(thread.getName()+" getting "+url)
+ (data, links) = fetch(url)
+
+ if data:
+ save_url(self.output,url, data)
+ if links:
+ self.queue.enqueue(links, depth+1)
+ logging.info(thread.getName()+" exiting")
+ pool = [Scraper(name="scraper-%d"%name) for name in range(self.pool_size)]
+ for p in pool:
+ p.start()
+
+ for p in pool:
+ p.join()
+
+
+
+
+
+
+class ScraperQueue(object):
+ """
+ Created with an initial set of urls to read, a set of roots to constrain
+ all links by, and a recursion limit, this is a queue of yet to be read urls.
+
+ There are three basic methods consume_top, active and enqueue
+
+ """
+ def __init__(self, urls, roots, limit):
+ self.unread_set = set(urls)
+ self.unread_queue = deque(((0,url) for url in self.unread_set))
+ self.visited = set()
+
+ self.roots=roots
+ self.limit=limit
+ self.excluded = set()
+ self.active_consumers=0
+
+ self.update_lock = Lock()
+ self.waiting_consumers = Condition()
+
+ def active(self):
+ """Returns True if there are items waiting to be read,
+ or False if the queue is empty, and no-one is currently processing an item
+
+ If someone is processing an item, then it blocks until it can return True or False
+ as above
+ """
+ if self.unread_queue:
+ return True
+ elif self.active_consumers == 0:
+ return False
+ else:
+ self.waiting_consumers.acquire()
+ while (not self.unread_queue) and self.active_consumers > 0:
+ logging.debug(threading.currentThread().getName()+" .... waiting on" + str(self.active_consumers) + str(self.unread_queue));
+ self.waiting_consumers.wait()
+ logging.debug(threading.currentThread().getName()+"awake" + str(self.unread_queue) +" " + str(self.active_consumers))
+ self.waiting_consumers.release()
+ return bool(self.unread_queue) or self.active_consumers > 0
+
+
+ def enqueue(self, links, depth):
+ """Updates the queue with the new links at a given depth"""
+ if self.limit is None or depth < self.limit:
+ with self.update_lock:
+ for url in links:
+ if self.will_follow(url):
+ self.unread_set.add(url)
+ self.unread_queue.append((depth,url))
+
+ else:
+ self.excluded.add(url)
+ logging.debug("Excluding %s" %url)
+ else:
+ self.excluded.update(links)
+
+
+ def consume_top(self):
+ """Because we need to track when consumers are active (and potentially
+ adding things to the queue), we use a contextmanager to take
+ the top of the queue:
+
+ i.e with queue.consume_top() as top: ...
+
+ Will return None if the queue is currently empty
+ """
+ @contextmanager
+ def manager():
+ if not self.unread_queue:
+ yield None
+ else:
+ with self.update_lock:
+ self.active_consumers+=1
+ (depth, url) =self.unread_queue.popleft()
+ yield (depth, url)
+
+ with self.update_lock:
+ self.visited.add(url)
+ self.unread_set.remove(url)
+ self.active_consumers-=1
+ self.wake_up_consumers()
+
+ return manager()
+
+
+
+ def will_follow(self, url):
+ if url not in self.unread_set and url not in self.visited:
+ return any(url.startswith(root) for root in self.roots)
+ return False
+
+
+
+ def wake_up_consumers(self):
+ # if there is data to be processed or nothing happening
+ if self.unread_queue or self.active_consumers == 0:
+ logging.debug("Waking up consumers because" +("unread" if self.unread_queue else "finished"))
+ self.waiting_consumers.acquire()
+ self.waiting_consumers.notifyAll()
+ self.waiting_consumers.release()
diff --git a/pyget/htmlparser.py b/pyget/lib/htmlparser.py
similarity index 100%
rename from pyget/htmlparser.py
rename to pyget/lib/htmlparser.py
diff --git a/pyget/lib/http.py b/pyget/lib/http.py
new file mode 100644
index 0000000..fac9b72
--- /dev/null
+++ b/pyget/lib/http.py
@@ -0,0 +1,38 @@
+import logging
+
+from urllib2 import urlopen, URLError
+from urlparse import urlparse
+from htmlparser import LinkParser, HTMLParseError
+
+
+def fetch(url):
+ """Returns a tuple of ("data", [links])"""
+ logging.info("fetching %s"%url)
+ try:
+ response = urlopen(url)
+ content_type = response.info()['Content-Type']
+ data = response.read()
+
+ if content_type.find("html") >= 0:
+ links = extract_links(url, data)
+ else:
+ logging.debug("skipping extracting links for %s:"%url)
+ links = ()
+
+ return (data, links)
+ except URLError, ex:
+ logging.warn("Can't fetch url: %s error:%s"%(url,ex))
+ return (None, ())
+
+def extract_links(url, data):
+ links = ()
+ try:
+ html = LinkParser()
+ html.feed(data)
+ html.close()
+ links = html.get_abs_links(url)
+
+ except HTMLParseError,ex:
+ logging.warning("failed to extract links for %s, %s"%(url,ex))
+
+ return links
diff --git a/pyget/lib/store.py b/pyget/lib/store.py
new file mode 100644
index 0000000..7bd001c
--- /dev/null
+++ b/pyget/lib/store.py
@@ -0,0 +1,46 @@
+from __future__ import with_statement
+
+import logging
+import os
+import re
+
+import os.path
+
+from urlparse import urlparse
+
+
+def save_url(output_dir, url, data):
+ try:
+ filename = get_file_name(output_dir, url)
+ create_necessary_dirs(filename)
+ logging.info("Creating file: %s"%filename)
+ with open(filename,"wb") as foo:
+ foo.write(data)
+ except StandardError, e:
+ logging.warn(e)
+
+re_strip = re.compile(r"[^\w\d\-_]")
+
+def clean_query(arg):
+ if arg:
+ return re.sub(re_strip,"_", arg)
+ else:
+ return ""
+
+
+def get_file_name(output_dir, url):
+ data = urlparse(url)
+ path = data.path[1:] if data.path.startswith("/") else path
+ if path.endswith("/"):
+ path = path+"index.html";
+
+ path = path + "."+clean_query(data.query) if data.query else path
+
+ filename = os.path.join(output_dir+"/", data.netloc, path)
+
+ return filename
+
+def create_necessary_dirs(filename):
+ dir = os.path.dirname(filename)
+ if not os.path.exists(dir):
+ os.makedirs(dir)
diff --git a/pyget/pyget.py b/pyget/pyget.py
index 2bd7498..59592db 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,46 +1,56 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has no third party dependencies, and
is written for Python 2.5"""
import sys
import logging
from optparse import OptionParser
-from scraper import Scraper
+from lib import Harvester
+
+LEVELS = {'debug': logging.DEBUG,
+ 'info': logging.INFO,
+ 'warning': logging.WARNING,
+ 'error': logging.ERROR,
+ 'critical': logging.CRITICAL}
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
+parser.add_option("-L", "--log_level", dest="log_level")
+
+parser.add_option("--pool", dest="pool_size")
-parser.set_defaults(output_directory=None, recursion_limit=None)
+parser.set_defaults(output_directory=None, recursion_limit=None, pool_size=4, log_level="info")
def main(argv):
- logging.basicConfig(level=logging.INFO)
(options, urls) = parser.parse_args(args=argv[1:])
+ logging.basicConfig(level=LEVELS[options.log_level])
if len(urls) < 1:
parser.error("missing url(s)")
- s = Scraper(
+ s = Harvester(
urls,
output_directory=options.output_directory,
limit=options.recursion_limit,
+ pool_size=options.pool_size,
)
s.start()
s.join()
- read, excluded = s.read, s.excluded
+ read, excluded = s.queue.visited, s.queue.excluded
- print "completed read: %d, excluded %d urls"%(len(read), len(excluded))
+ logging.info("completed read: %d, excluded %d urls"%(len(read), len(excluded)))
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/pyget/scraper.py b/pyget/scraper.py
deleted file mode 100644
index 0c4434e..0000000
--- a/pyget/scraper.py
+++ /dev/null
@@ -1,120 +0,0 @@
-"""A bulk downloader"""
-
-from __future__ import with_statement
-
-import os
-import os.path
-import logging
-
-from threading import Thread
-from collections import deque
-from urllib2 import urlopen, URLError
-from urlparse import urlparse
-from htmlparser import LinkParser, HTMLParseError
-
-class Scraper(Thread, object):
- """A scraper thread. Initialized with a base set of urls and an output directory,
- will start scraping with start()"""
-
- def __init__(self, urls, output_directory=None, limit=None):
- Thread.__init__(self)
- self.unread_queue = deque(((0,url) for url in urls))
- self.unread_set = set(urls)
-
- self.roots = [os.path.split(url)[0] for url in urls]
-
- self.read = {}
- self.excluded = []
-
- self.limit = limit
-
- if not output_directory:
- output_directory = os.getcwd()
- self.output = output_directory
-
-
- def run(self):
- while self.unread_queue:
- (depth, first) = self.unread_queue.popleft()
-
- (data, links) = self.fetch(first)
- self.read[first] = data
- self.unread_set.remove(first)
-
- if data:
- self.write_file(first, data)
-
- depth+=1
- if self.limit is None or depth > self.limit:
- for url in links:
- if self.will_follow(url):
- if url not in self.read and url not in self.unread_set:
- logging.debug("Will visit %s" %url)
- self.unread_queue.append((depth,url))
- self.unread_set.add(url)
- else:
- logging.debug("Have visited %s" %url)
- else:
- self.excluded.append(url)
- logging.debug("Excluding %s" %url)
- else:
- self.excluded.extend(links)
-
- def will_follow(self, url):
- return any(url.startswith(root) for root in self.roots)
-
-
- def fetch(self, url):
- logging.info("fetching %s"%url)
- try:
- response = urlopen(url)
- content_type = response.info()['Content-Type']
- data = response.read()
-
- if content_type.find("html") >= 0:
- links = self.extract_links(url, data)
- else:
- logging.debug("skipping extracting links for %s:"%url)
- links = ()
-
-
- return (data, links)
- except URLError, ex:
- logging.warn("Can't fetch url: %s error:%s"%(url,ex))
- return (None, ())
-
- def extract_links(self, url, data):
- links = ()
- try:
- html = LinkParser()
- html.feed(data)
- html.close()
- links = html.get_abs_links(url)
-
- except HTMLParseError,ex:
- logging.warning("failed to extract links for %s, %s"%(url,ex))
-
- return links
-
- def get_file_name(self, url):
- data = urlparse(url)
- path = data.path[1:] if data.path.startswith("/") else path
- filename = os.path.join(self.output+"/", data.netloc, path)
- if filename.endswith("/"):
- filename = filename+"index.html";
-
- return filename
-
- def write_file(self, url, data):
- filename = self.get_file_name(url)
- create_necessary_dirs(filename)
- logging.debug("Creating file: %s"%filename)
- with open(filename,"wb") as foo:
- foo.write(data)
- pass
-
-
-def create_necessary_dirs(filename):
- dir = os.path.dirname(filename)
- if not os.path.exists(dir):
- os.makedirs(dir)
|
tef/crawler
|
04415a16a102e823902b3b1453317cff586e3cc0
|
make scraper behave like a thread - first pass of threading scraper
|
diff --git a/pyget/pyget.py b/pyget/pyget.py
index e3e7d15..2bd7498 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,46 +1,46 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget. It has no third party dependencies, and
is written for Python 2.5"""
import sys
import logging
from optparse import OptionParser
from scraper import Scraper
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.set_defaults(output_directory=None, recursion_limit=None)
def main(argv):
logging.basicConfig(level=logging.INFO)
(options, urls) = parser.parse_args(args=argv[1:])
if len(urls) < 1:
parser.error("missing url(s)")
s = Scraper(
urls,
output_directory=options.output_directory,
limit=options.recursion_limit,
)
s.start()
- s.wait()
+ s.join()
read, excluded = s.read, s.excluded
- print "completed read %d, excluded %d urls"%(len(read), len(excluded))
+ print "completed read: %d, excluded %d urls"%(len(read), len(excluded))
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/pyget/scraper.py b/pyget/scraper.py
index 5aa0348..0c4434e 100644
--- a/pyget/scraper.py
+++ b/pyget/scraper.py
@@ -1,117 +1,120 @@
"""A bulk downloader"""
from __future__ import with_statement
import os
import os.path
import logging
+from threading import Thread
from collections import deque
from urllib2 import urlopen, URLError
from urlparse import urlparse
from htmlparser import LinkParser, HTMLParseError
-class Scraper(object):
+class Scraper(Thread, object):
+ """A scraper thread. Initialized with a base set of urls and an output directory,
+ will start scraping with start()"""
+
def __init__(self, urls, output_directory=None, limit=None):
+ Thread.__init__(self)
self.unread_queue = deque(((0,url) for url in urls))
self.unread_set = set(urls)
self.roots = [os.path.split(url)[0] for url in urls]
+
self.read = {}
- self.limit = limit
self.excluded = []
+ self.limit = limit
+
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
- def start(self):
+ def run(self):
while self.unread_queue:
(depth, first) = self.unread_queue.popleft()
(data, links) = self.fetch(first)
self.read[first] = data
self.unread_set.remove(first)
if data:
self.write_file(first, data)
depth+=1
if self.limit is None or depth > self.limit:
for url in links:
if self.will_follow(url):
if url not in self.read and url not in self.unread_set:
- logging.info("Will visit %s" %url)
+ logging.debug("Will visit %s" %url)
self.unread_queue.append((depth,url))
self.unread_set.add(url)
else:
logging.debug("Have visited %s" %url)
else:
self.excluded.append(url)
logging.debug("Excluding %s" %url)
else:
self.excluded.extend(links)
def will_follow(self, url):
return any(url.startswith(root) for root in self.roots)
def fetch(self, url):
logging.info("fetching %s"%url)
try:
response = urlopen(url)
content_type = response.info()['Content-Type']
data = response.read()
if content_type.find("html") >= 0:
links = self.extract_links(url, data)
else:
logging.debug("skipping extracting links for %s:"%url)
links = ()
return (data, links)
except URLError, ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return (None, ())
def extract_links(self, url, data):
links = ()
try:
html = LinkParser()
html.feed(data)
html.close()
links = html.get_abs_links(url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
return links
def get_file_name(self, url):
data = urlparse(url)
path = data.path[1:] if data.path.startswith("/") else path
filename = os.path.join(self.output+"/", data.netloc, path)
if filename.endswith("/"):
filename = filename+"index.html";
return filename
def write_file(self, url, data):
filename = self.get_file_name(url)
create_necessary_dirs(filename)
logging.debug("Creating file: %s"%filename)
with open(filename,"wb") as foo:
foo.write(data)
pass
-
- def wait(self):
- pass
-
def create_necessary_dirs(filename):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
|
tef/crawler
|
75df9b3c8d200bd3b392326b8244b914378cfe6f
|
better ./, ../ handling in relative links, also fixed scraper loop as it should tread unread urls as a set *and* a queue
|
diff --git a/pyget/htmlparser.py b/pyget/htmlparser.py
index a3cc605..d4f80f6 100644
--- a/pyget/htmlparser.py
+++ b/pyget/htmlparser.py
@@ -1,58 +1,70 @@
"""Simplified html parser that extracts urls from a document"""
import logging
import os.path
from urlparse import urlparse, urlunparse
from HTMLParser import HTMLParser, HTMLParseError
__all__ = ["LinkParser", "HTMLParseError"]
def attr_extractor(name):
def _extractor(attrs):
return [value for key,value in attrs if key == name and value]
return _extractor
class LinkParser(HTMLParser):
def __init__(self):
self.links = []
HTMLParser.__init__(self)
tag_extractor = {
"a": attr_extractor("href"),
"link": attr_extractor("href"),
"img": attr_extractor("src"),
"script": attr_extractor("src"),
"iframe": attr_extractor("src"),
"frame": attr_extractor("src"),
"embed": attr_extractor("src"),
}
def handle_starttag(self, tag, attrs):
extractor = self.tag_extractor.get(tag, None)
if extractor:
self.links.extend(extractor(attrs))
def get_abs_links(self, url):
full_urls = []
root = urlparse(url)
+ root_dir = os.path.split(root.path)[0]
for link in self.links:
parsed = urlparse(link)
if not parsed.netloc: # does it have no protocol or host, i.e relative
if parsed.path.startswith("/"):
- parsed = root[0:2] + parsed[2:]
+ parsed = root[0:2] + parsed[2:5] + (None,)
else:
- parsed = root[0:2] + (os.path.join(root.path, parsed.path),) + parsed[3:]
+ dir = root_dir
+ path = parsed.path
+ while True:
+ if path.startswith("../"):
+ path=path[3:]
+ dir=os.path.split(dir)[0]
+ elif path.startswith("./"):
+ path=path[2:]
+ else:
+ break
+
+ parsed = root[0:2] + (os.path.join(dir, path),) + parsed[3:5] + (None,)
new_link = urlunparse(parsed)
logging.debug("relative %s -> %s"%(link, new_link))
link=new_link
else:
logging.debug("absolute %s"%link)
full_urls.append(link)
return full_urls
diff --git a/pyget/pyget.py b/pyget/pyget.py
index 1f7d828..e3e7d15 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,52 +1,46 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
-a primitive wget"""
+a primitive wget. It has no third party dependencies, and
+is written for Python 2.5"""
import sys
import logging
from optparse import OptionParser
from scraper import Scraper
+parser = OptionParser(usage="%prog [options] url (url ...)")
+parser.add_option("-o", "--output-directory", dest="output_directory",
+ help="write downloaded files to this directory")
+parser.add_option("-l", "--limit", dest="recursion_limit")
-parser= None # created later
+parser.set_defaults(output_directory=None, recursion_limit=None)
def main(argv):
- logging.basicConfig(level=logging.DEBUG)
+ logging.basicConfig(level=logging.INFO)
(options, urls) = parser.parse_args(args=argv[1:])
if len(urls) < 1:
parser.error("missing url(s)")
- s = Scraper(urls, output_directory=options.output_directory)
+ s = Scraper(
+ urls,
+ output_directory=options.output_directory,
+ limit=options.recursion_limit,
+ )
s.start()
s.wait()
read, excluded = s.read, s.excluded
print "completed read %d, excluded %d urls"%(len(read), len(excluded))
return 0
-
-def create_parser():
- parser = OptionParser(usage="%prog [options] url (url ...)")
-
- parser.add_option("-o", "--output-directory", dest="output_directory",
- help="write downloaded files to this directory")
- parser.add_option("-l", "--limit", dest="recursion_limit")
-
- parser.set_defaults(output_directory=None, recursion_limit=None)
-
- return parser
-
-
-parser = create_parser()
-
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/pyget/scraper.py b/pyget/scraper.py
index 44fb61a..5aa0348 100644
--- a/pyget/scraper.py
+++ b/pyget/scraper.py
@@ -1,113 +1,117 @@
"""A bulk downloader"""
from __future__ import with_statement
import os
import os.path
import logging
from collections import deque
from urllib2 import urlopen, URLError
from urlparse import urlparse
from htmlparser import LinkParser, HTMLParseError
class Scraper(object):
- def __init__(self, urls, output_directory=None):
- self.unread = deque(urls)
- self.roots = urls
+ def __init__(self, urls, output_directory=None, limit=None):
+ self.unread_queue = deque(((0,url) for url in urls))
+ self.unread_set = set(urls)
+
+ self.roots = [os.path.split(url)[0] for url in urls]
self.read = {}
+ self.limit = limit
self.excluded = []
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
def start(self):
- while self.unread:
- first = self.unread.popleft()
+ while self.unread_queue:
+ (depth, first) = self.unread_queue.popleft()
(data, links) = self.fetch(first)
+ self.read[first] = data
+ self.unread_set.remove(first)
+
if data:
self.write_file(first, data)
- self.read[first] = data
- for url in links:
- if self.will_follow(url):
- if url not in self.read:
- logging.info("Will visit %s" %url)
- self.unread.append(url)
- else:
- logging.info("Have visited %s" %url)
- else:
- self.excluded.append(url)
- logging.info("Excluding %s" %url)
-
+ depth+=1
+ if self.limit is None or depth > self.limit:
+ for url in links:
+ if self.will_follow(url):
+ if url not in self.read and url not in self.unread_set:
+ logging.info("Will visit %s" %url)
+ self.unread_queue.append((depth,url))
+ self.unread_set.add(url)
+ else:
+ logging.debug("Have visited %s" %url)
+ else:
+ self.excluded.append(url)
+ logging.debug("Excluding %s" %url)
+ else:
+ self.excluded.extend(links)
def will_follow(self, url):
- return False
+ return any(url.startswith(root) for root in self.roots)
def fetch(self, url):
- logging.debug("fetching %s"%url)
+ logging.info("fetching %s"%url)
try:
response = urlopen(url)
content_type = response.info()['Content-Type']
data = response.read()
if content_type.find("html") >= 0:
links = self.extract_links(url, data)
else:
logging.debug("skipping extracting links for %s:"%url)
- links = None
+ links = ()
return (data, links)
except URLError, ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return (None, ())
def extract_links(self, url, data):
links = ()
try:
html = LinkParser()
html.feed(data)
html.close()
links = html.get_abs_links(url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
return links
def get_file_name(self, url):
data = urlparse(url)
path = data.path[1:] if data.path.startswith("/") else path
filename = os.path.join(self.output+"/", data.netloc, path)
if filename.endswith("/"):
filename = filename+"index.html";
return filename
def write_file(self, url, data):
filename = self.get_file_name(url)
create_necessary_dirs(filename)
logging.debug("Creating file: %s"%filename)
with open(filename,"wb") as foo:
foo.write(data)
pass
def wait(self):
pass
-
-
-
-
-
def create_necessary_dirs(filename):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
|
tef/crawler
|
41c776c1d41e127e7b9eb5ad7d9b5247c7234653
|
working on relative links from document
|
diff --git a/pyget/htmlparser.py b/pyget/htmlparser.py
index 7adad0d..a3cc605 100644
--- a/pyget/htmlparser.py
+++ b/pyget/htmlparser.py
@@ -1,37 +1,58 @@
"""Simplified html parser that extracts urls from a document"""
+import logging
+import os.path
+
+from urlparse import urlparse, urlunparse
from HTMLParser import HTMLParser, HTMLParseError
+__all__ = ["LinkParser", "HTMLParseError"]
def attr_extractor(name):
def _extractor(attrs):
return [value for key,value in attrs if key == name and value]
return _extractor
class LinkParser(HTMLParser):
def __init__(self):
self.links = []
HTMLParser.__init__(self)
tag_extractor = {
"a": attr_extractor("href"),
"link": attr_extractor("href"),
"img": attr_extractor("src"),
"script": attr_extractor("src"),
"iframe": attr_extractor("src"),
"frame": attr_extractor("src"),
"embed": attr_extractor("src"),
}
def handle_starttag(self, tag, attrs):
extractor = self.tag_extractor.get(tag, None)
if extractor:
- self.links.extend(extractor(attrs))
+ self.links.extend(extractor(attrs))
def get_abs_links(self, url):
- return self.links
+ full_urls = []
+ root = urlparse(url)
+ for link in self.links:
+ parsed = urlparse(link)
+ if not parsed.netloc: # does it have no protocol or host, i.e relative
+ if parsed.path.startswith("/"):
+ parsed = root[0:2] + parsed[2:]
+ else:
+ parsed = root[0:2] + (os.path.join(root.path, parsed.path),) + parsed[3:]
+ new_link = urlunparse(parsed)
+ logging.debug("relative %s -> %s"%(link, new_link))
+ link=new_link
+
+ else:
+ logging.debug("absolute %s"%link)
+ full_urls.append(link)
+ return full_urls
diff --git a/pyget/scraper.py b/pyget/scraper.py
index 28b4819..44fb61a 100644
--- a/pyget/scraper.py
+++ b/pyget/scraper.py
@@ -1,114 +1,113 @@
"""A bulk downloader"""
from __future__ import with_statement
import os
import os.path
import logging
from collections import deque
from urllib2 import urlopen, URLError
from urlparse import urlparse
-from htmlparser import LinkParser
+from htmlparser import LinkParser, HTMLParseError
class Scraper(object):
def __init__(self, urls, output_directory=None):
self.unread = deque(urls)
self.roots = urls
self.read = {}
self.excluded = []
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
def start(self):
while self.unread:
first = self.unread.popleft()
(data, links) = self.fetch(first)
if data:
self.write_file(first, data)
self.read[first] = data
for url in links:
if self.will_follow(url):
if url not in self.read:
logging.info("Will visit %s" %url)
self.unread.append(url)
else:
logging.info("Have visited %s" %url)
else:
self.excluded.append(url)
logging.info("Excluding %s" %url)
def will_follow(self, url):
return False
def fetch(self, url):
logging.debug("fetching %s"%url)
try:
response = urlopen(url)
content_type = response.info()['Content-Type']
data = response.read()
-
if content_type.find("html") >= 0:
links = self.extract_links(url, data)
else:
logging.debug("skipping extracting links for %s:"%url)
links = None
return (data, links)
except URLError, ex:
logging.warn("Can't fetch url: %s error:%s"%(url,ex))
return (None, ())
def extract_links(self, url, data):
links = ()
try:
html = LinkParser()
html.feed(data)
html.close()
links = html.get_abs_links(url)
except HTMLParseError,ex:
logging.warning("failed to extract links for %s, %s"%(url,ex))
return links
def get_file_name(self, url):
data = urlparse(url)
path = data.path[1:] if data.path.startswith("/") else path
filename = os.path.join(self.output+"/", data.netloc, path)
if filename.endswith("/"):
filename = filename+"index.html";
return filename
- def write_file(self, url, data):
+ def write_file(self, url, data):
filename = self.get_file_name(url)
create_necessary_dirs(filename)
logging.debug("Creating file: %s"%filename)
with open(filename,"wb") as foo:
foo.write(data)
pass
def wait(self):
pass
def create_necessary_dirs(filename):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
|
tef/crawler
|
75c450fc05aa6102871fe904c14acd46fc8450fd
|
adding link parser
|
diff --git a/pyget/htmlparser.py b/pyget/htmlparser.py
new file mode 100644
index 0000000..7adad0d
--- /dev/null
+++ b/pyget/htmlparser.py
@@ -0,0 +1,37 @@
+"""Simplified html parser that extracts urls from a document"""
+
+from HTMLParser import HTMLParser, HTMLParseError
+
+
+def attr_extractor(name):
+ def _extractor(attrs):
+ return [value for key,value in attrs if key == name and value]
+ return _extractor
+
+
+class LinkParser(HTMLParser):
+ def __init__(self):
+ self.links = []
+ HTMLParser.__init__(self)
+
+
+ tag_extractor = {
+ "a": attr_extractor("href"),
+ "link": attr_extractor("href"),
+ "img": attr_extractor("src"),
+ "script": attr_extractor("src"),
+ "iframe": attr_extractor("src"),
+ "frame": attr_extractor("src"),
+ "embed": attr_extractor("src"),
+ }
+
+
+
+ def handle_starttag(self, tag, attrs):
+ extractor = self.tag_extractor.get(tag, None)
+ if extractor:
+ self.links.extend(extractor(attrs))
+
+
+ def get_abs_links(self, url):
+ return self.links
diff --git a/pyget/pyget.py b/pyget/pyget.py
index 5ad44aa..1f7d828 100644
--- a/pyget/pyget.py
+++ b/pyget/pyget.py
@@ -1,48 +1,52 @@
#!/usr/bin/env python2.5
"""An example website downloader, similar in functionality to
a primitive wget"""
import sys
import logging
from optparse import OptionParser
from scraper import Scraper
parser= None # created later
def main(argv):
logging.basicConfig(level=logging.DEBUG)
(options, urls) = parser.parse_args(args=argv[1:])
if len(urls) < 1:
parser.error("missing url(s)")
s = Scraper(urls, output_directory=options.output_directory)
s.start()
s.wait()
+ read, excluded = s.read, s.excluded
+
+ print "completed read %d, excluded %d urls"%(len(read), len(excluded))
+
return 0
def create_parser():
parser = OptionParser(usage="%prog [options] url (url ...)")
parser.add_option("-o", "--output-directory", dest="output_directory",
help="write downloaded files to this directory")
parser.add_option("-l", "--limit", dest="recursion_limit")
parser.set_defaults(output_directory=None, recursion_limit=None)
return parser
parser = create_parser()
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/pyget/scraper.py b/pyget/scraper.py
index ddfb130..28b4819 100644
--- a/pyget/scraper.py
+++ b/pyget/scraper.py
@@ -1,86 +1,114 @@
"""A bulk downloader"""
from __future__ import with_statement
import os
import os.path
import logging
from collections import deque
from urllib2 import urlopen, URLError
from urlparse import urlparse
-
+from htmlparser import LinkParser
class Scraper(object):
def __init__(self, urls, output_directory=None):
self.unread = deque(urls)
+ self.roots = urls
self.read = {}
+ self.excluded = []
+
if not output_directory:
output_directory = os.getcwd()
self.output = output_directory
def start(self):
while self.unread:
first = self.unread.popleft()
(data, links) = self.fetch(first)
if data:
self.write_file(first, data)
self.read[first] = data
for url in links:
- if url not in self.read:
- self.unread.append()
+ if self.will_follow(url):
+ if url not in self.read:
+ logging.info("Will visit %s" %url)
+ self.unread.append(url)
+ else:
+ logging.info("Have visited %s" %url)
+ else:
+ self.excluded.append(url)
+ logging.info("Excluding %s" %url)
+ def will_follow(self, url):
+ return False
def fetch(self, url):
logging.debug("fetching %s"%url)
try:
- data = urlopen(url)
- links = self.extract_links(url, data)
- return (data, links)
- except URLError, ex:
- logging.warn("Can't fetch url: %s error:%s"%(url,ex))
- return (None, ())
+ response = urlopen(url)
+ content_type = response.info()['Content-Type']
+ data = response.read()
+ if content_type.find("html") >= 0:
+ links = self.extract_links(url, data)
+ else:
+ logging.debug("skipping extracting links for %s:"%url)
+ links = None
- def write_file(self, url, data):
- filename = self.get_file_name(url)
- create_necessary_dirs(filename)
- logging.debug("Creating file: %s"%filename)
- with open(filename,"w") as foo:
- foo.writelines(data.readlines())
- pass
+ return (data, links)
+ except URLError, ex:
+ logging.warn("Can't fetch url: %s error:%s"%(url,ex))
+ return (None, ())
def extract_links(self, url, data):
- return ()
+ links = ()
+ try:
+ html = LinkParser()
+ html.feed(data)
+ html.close()
+ links = html.get_abs_links(url)
+
+ except HTMLParseError,ex:
+ logging.warning("failed to extract links for %s, %s"%(url,ex))
+ return links
def get_file_name(self, url):
data = urlparse(url)
path = data.path[1:] if data.path.startswith("/") else path
filename = os.path.join(self.output+"/", data.netloc, path)
if filename.endswith("/"):
filename = filename+"index.html";
return filename
+ def write_file(self, url, data):
+ filename = self.get_file_name(url)
+ create_necessary_dirs(filename)
+ logging.debug("Creating file: %s"%filename)
+ with open(filename,"wb") as foo:
+ foo.write(data)
+ pass
+
+
+
def wait(self):
pass
+
def create_necessary_dirs(filename):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
-
-
-
|
tef/crawler
|
4d87ace202ae124b76515d9e60ad71fe87ada211
|
inital boilerplate for parsing arguments, fetching a file and writing it to disk
|
diff --git a/pyget/pyget.py b/pyget/pyget.py
new file mode 100644
index 0000000..5ad44aa
--- /dev/null
+++ b/pyget/pyget.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python2.5
+"""An example website downloader, similar in functionality to
+a primitive wget"""
+
+import sys
+import logging
+
+from optparse import OptionParser
+
+from scraper import Scraper
+
+
+
+parser= None # created later
+
+def main(argv):
+ logging.basicConfig(level=logging.DEBUG)
+ (options, urls) = parser.parse_args(args=argv[1:])
+
+ if len(urls) < 1:
+ parser.error("missing url(s)")
+
+ s = Scraper(urls, output_directory=options.output_directory)
+
+ s.start()
+
+ s.wait()
+
+ return 0
+
+
+def create_parser():
+ parser = OptionParser(usage="%prog [options] url (url ...)")
+
+ parser.add_option("-o", "--output-directory", dest="output_directory",
+ help="write downloaded files to this directory")
+ parser.add_option("-l", "--limit", dest="recursion_limit")
+
+ parser.set_defaults(output_directory=None, recursion_limit=None)
+
+ return parser
+
+
+parser = create_parser()
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
+
|
tef/crawler
|
4cb4e88dc38a3ab5b58cc3998c6e44b03aeedeac
|
inital boilerplate for parsing arguments, fetching a file and writing it to disk
|
diff --git a/pyget/scraper.py b/pyget/scraper.py
new file mode 100644
index 0000000..ddfb130
--- /dev/null
+++ b/pyget/scraper.py
@@ -0,0 +1,86 @@
+"""A bulk downloader"""
+
+from __future__ import with_statement
+
+import os
+import os.path
+import logging
+
+from collections import deque
+from urllib2 import urlopen, URLError
+from urlparse import urlparse
+
+
+class Scraper(object):
+ def __init__(self, urls, output_directory=None):
+ self.unread = deque(urls)
+ self.read = {}
+ if not output_directory:
+ output_directory = os.getcwd()
+ self.output = output_directory
+
+
+ def start(self):
+ while self.unread:
+ first = self.unread.popleft()
+
+ (data, links) = self.fetch(first)
+ if data:
+ self.write_file(first, data)
+
+ self.read[first] = data
+ for url in links:
+ if url not in self.read:
+ self.unread.append()
+
+
+
+
+ def fetch(self, url):
+ logging.debug("fetching %s"%url)
+ try:
+ data = urlopen(url)
+ links = self.extract_links(url, data)
+ return (data, links)
+ except URLError, ex:
+ logging.warn("Can't fetch url: %s error:%s"%(url,ex))
+ return (None, ())
+
+
+
+ def write_file(self, url, data):
+ filename = self.get_file_name(url)
+ create_necessary_dirs(filename)
+ logging.debug("Creating file: %s"%filename)
+ with open(filename,"w") as foo:
+ foo.writelines(data.readlines())
+ pass
+
+
+ def extract_links(self, url, data):
+ return ()
+
+
+ def get_file_name(self, url):
+ data = urlparse(url)
+ path = data.path[1:] if data.path.startswith("/") else path
+ filename = os.path.join(self.output+"/", data.netloc, path)
+ if filename.endswith("/"):
+ filename = filename+"index.html";
+
+ return filename
+
+ def wait(self):
+ pass
+
+
+
+
+
+def create_necessary_dirs(filename):
+ dir = os.path.dirname(filename)
+ if not os.path.exists(dir):
+ os.makedirs(dir)
+
+
+
|
valaravena/Glo
|
465f2a62d423c76d1aee7768e16ed21f8ae24df5
|
Adding Update
|
diff --git a/app/config/database.php b/app/config/database.php
index 50103c9..b41b4d8 100644
--- a/app/config/database.php
+++ b/app/config/database.php
@@ -1,96 +1,99 @@
<?php
/**
* This is core configuration file.
*
* Use it to configure core behaviour ofCake.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* In this file you set up your database connection details.
*
* @package cake
* @subpackage cake.config
*/
/**
* Database configuration class.
* You can specify multiple configurations for production, development and testing.
*
* driver => The name of a supported driver; valid options are as follows:
* mysql - MySQL 4 & 5,
* mysqli - MySQL 4 & 5 Improved Interface (PHP5 only),
* sqlite - SQLite (PHP5 only),
* postgres - PostgreSQL 7 and higher,
* mssql - Microsoft SQL Server 2000 and higher,
* db2 - IBM DB2, Cloudscape, and Apache Derby (http://php.net/ibm-db2)
* oracle - Oracle 8 and higher
* firebird - Firebird/Interbase
* sybase - Sybase ASE
* adodb-[drivername] - ADOdb interface wrapper (see below),
* odbc - ODBC DBO driver
*
* You can add custom database drivers (or override existing drivers) by adding the
* appropriate file to app/models/datasources/dbo. Drivers should be named 'dbo_x.php',
* where 'x' is the name of the database.
*
* persistent => true / false
* Determines whether or not the database should use a persistent connection
*
* connect =>
* ADOdb set the connect to one of these
* (http://phplens.com/adodb/supported.databases.html) and
* append it '|p' for persistent connection. (mssql|p for example, or just mssql for not persistent)
* For all other databases, this setting is deprecated.
*
* host =>
* the host you connect to the database. To add a socket or port number, use 'port' => #
*
* prefix =>
* Uses the given prefix for all the tables in this database. This setting can be overridden
* on a per-table basis with the Model::$tablePrefix property.
*
* schema =>
* For Postgres and DB2, specifies which schema you would like to use the tables in. Postgres defaults to
* 'public', DB2 defaults to empty.
*
* encoding =>
* For MySQL, MySQLi, Postgres and DB2, specifies the character encoding to use when connecting to the
* database. Uses database default.
*
*/
class DATABASE_CONFIG {
var $default = array(
- 'driver' => 'sqlite',
+ 'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
- 'password' => '',
- 'database' => '/Users/jmashburn/Documents/Projects/Glow/app/config/schema/glow.sqlite',
+ 'password' => 'root',
+ 'database' => 'glow',
+ #'database' => '/Users/jmashburn/Documents/Projects/Glow/app/config/schema/glow.sqlite',
'prefix' => '',
+ 'port' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'encoding' => 'UTF8'
);
+
var $test = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'test_database_name',
'prefix' => '',
);
}
diff --git a/app/config/routes.php b/app/config/routes.php
index f05e76e..80df076 100644
--- a/app/config/routes.php
+++ b/app/config/routes.php
@@ -1,31 +1,32 @@
<?php
#App::import('Lib', 'super_router');
require_once APP.'libs'.DS.'super_router.php';
#SuperRouter::plugins();
#if (!isInstalled()) {
# SuperRouter::connect('/', array('plugin' => 'install', 'controller' => 'wizard'));
#}
// Basic
SuperRouter::connect('/admin', array('admin' => true, 'controller' => 'dashboard'));
// Pages
SuperRouter::connect('/', array('controller' => 'pages', 'action' => 'home', 'home'));
#SuperRouter::connect('/pages/*', array('controller' => 'pages', 'action' => 'view'));
SuperRouter::connect('/contact', array('controller' => 'pages', 'action' => 'contact'));
// Users
SuperRouter::connect('/register', array('controller' => 'users', 'action' => 'register'));
- SuperRouter::connect('/login', array('controller' => 'users', 'action' => 'login'));
+ SuperRouter::connect('/login', array('controller' => 'users', 'action' => 'login'));
+ SuperRouter::connect('/logout', array('controller' => 'users', 'action' => 'logout'));
SuperRouter::connect('/recover', array('controller' => 'users', 'action' => 'recover'));
Router::parseExtensions('xml','json', 'csv');
diff --git a/app/config/schema/schema.php b/app/config/schema/schema.php
index 011401d..5bf282b 100644
--- a/app/config/schema/schema.php
+++ b/app/config/schema/schema.php
@@ -1,133 +1,133 @@
<?php
/* SVN FILE: $Id$ */
/* App schema generated on: 2010-09-15 16:09:38 : 1284583118*/
class AppSchema extends CakeSchema {
var $name = 'App';
function before($event = array()) {
return true;
}
function after($event = array()) {
}
var $account_types = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => false, 'default' => NULL),
'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
'indexes' => array(),
'tableParameters' => array()
);
var $accounts = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'account_type_id' => array('type' => 'text', 'null' => false, 'default' => NULL, 'length' => 11),
'user_id' => array('type' => 'text', 'null' => false, 'default' => NULL, 'length' => 11),
'first_name' => array('type' => 'string', 'null' => false, 'default' => NULL),
'last_name' => array('type' => 'string', 'null' => false, 'default' => NULL),
'bio' => array('type' => 'text', 'null' => true, 'default' => NULL),
'location' => array('type' => 'string', 'null' => true, 'default' => NULL),
'date_of_birth' => array('type' => 'date', 'null' => true, 'default' => NULL),
'gender_id' => array('type' => 'text', 'null' => true, 'default' => NULL, 'length' => 11),
'image' => array('type' => 'string', 'null' => true, 'default' => NULL),
'newsletter' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 1),
'active' => array('type' => 'text', 'null' => true, 'default' => NULL, 'length' => 1),
'key' => array('type' => 'string', 'null' => true, 'default' => NULL),
'source_id' => array('type' => 'text', 'null' => true, 'default' => NULL, 'length' => 11),
'source_extra' => array('type' => 'string', 'null' => true, 'default' => NULL),
'ip' => array('type' => 'string', 'null' => true, 'default' => NULL),
'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
'indexes' => array(),
'tableParameters' => array()
);
var $acos = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'parent_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'model' => array('type' => 'string', 'null' => true, 'default' => NULL),
'foreign_key' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'alias' => array('type' => 'string', 'null' => true, 'default' => NULL),
'lft' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'rght' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'indexes' => array(),
'tableParameters' => array()
);
var $aros = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'parent_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'model' => array('type' => 'string', 'null' => true, 'default' => NULL),
'foreign_key' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'alias' => array('type' => 'string', 'null' => true, 'default' => NULL),
'lft' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'rght' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'indexes' => array(),
'tableParameters' => array()
);
var $aros_acos = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'aro_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10),
'aco_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10),
'_create' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
'_read' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
'_update' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
'_delete' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
'indexes' => array(),
'tableParameters' => array()
);
var $core_resources = array(
'code' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'key' => 'primary'),
'version' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50),
'indexes' => array(),
'tableParameters' => array()
);
var $genders = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => false, 'default' => NULL),
'indexes' => array(),
'tableParameters' => array()
);
var $groups = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => true, 'default' => NULL),
'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
'indexes' => array(),
'tableParameters' => array()
);
var $pages = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => true, 'default' => NULL),
'title' => array('type' => 'string', 'null' => true, 'default' => NULL),
'meta_description' => array('type' => 'text', 'null' => true, 'default' => NULL),
'meta_keywords' => array('type' => 'text', 'null' => true, 'default' => NULL),
'slug' => array('type' => 'string', 'null' => true, 'default' => NULL),
'content' => array('type' => 'text', 'null' => true, 'default' => NULL),
'top_show' => array('type' => 'boolean', 'null' => false, 'default' => '0'),
'bottom_show' => array('type' => 'boolean', 'null' => false, 'default' => '0'),
- 'top_order' => array('type' => 'text', 'null' => true, 'default' => '0', 'length' => 3),
- 'bottom_order' => array('type' => 'text', 'null' => true, 'default' => '0', 'length' => 3),
+ 'top_order' => array('type' => 'text', 'null' => true, 'default' => NULL, 'length' => 3),
+ 'bottom_order' => array('type' => 'text', 'null' => true, 'default' => NULL, 'length' => 3),
'indexes' => array(),
'tableParameters' => array()
);
var $sources = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => true, 'default' => NULL),
'indexes' => array(),
'tableParameters' => array()
);
var $users = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'group_id' => array('type' => 'integer', 'null' => false, 'default' => NULL),
'username' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100),
'password' => array('type' => 'string', 'null' => false, 'default' => NULL),
'email' => array('type' => 'string', 'null' => true, 'default' => NULL),
'active' => array('type' => 'boolean', 'null' => false, 'default' => NULL),
'key' => array('type' => 'string', 'null' => false, 'default' => NULL),
'ip' => array('type' => 'string', 'null' => false, 'default' => NULL),
'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'indexes' => array(),
'tableParameters' => array()
);
}
-?>
\ No newline at end of file
+?>
diff --git a/app/controllers/users_controller.php b/app/controllers/users_controller.php
index f821a8c..a630527 100644
--- a/app/controllers/users_controller.php
+++ b/app/controllers/users_controller.php
@@ -1,307 +1,316 @@
<?php
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Recaptcha');
var $helpers = array('Recaptcha', 'SimpleGeo.GoogleMap');
- var $uses = array('SimpleGeo.SimpleGeo');
+ var $uses = array('SimpleGeo.SimpleGeo','Group');
function beforeFilter() {
parent::beforeFilter();
$this->Security->requireLogin('authenticate');
if (!empty($this->Auth)) {
$this->Auth->allow('activate', 'register', 'reset', 'recover', 'resend', 'login', 'logout');
$this->Auth->allow('*');
}
}
- function index() {
+ function index() {
+
$this->set('title_for_layout', __('Account', true));
if ($this->Session->check('Auth.User')) {
$simpleGeoLayer = 'iWobbleTestLayer';
$points = array();
if (!empty($simpleGeoLayer)) {
if (!empty($this->params['url']['hash'])) {
$result = $this->SimpleGeo->getNearby($simpleGeoLayer, $this->params['url']['hash'], array('limit' => 50, 'radius' => 200));
if (!empty($result->features)) {
foreach ($result->features as $feature) {
$point['Point']['id'] = $feature->id;
$point['Point']['name'] = $feature->id;
$point['Point']['longitude'] = $feature->geometry->coordinates[0];
$point['Point']['latitude'] = $feature->geometry->coordinates[1];
$point['Point']['created'] = $feature->created;
$points[] = $point;
}
} else {
if (!empty($result->message)) {
#die($result->message);
}
}
}
$this->set('points', $points);
}
} else {
$this->redirect('/login');
}
}
- function login() {
+ function login() {
$this->set('title_for_layout', __('Login', true));
- if (!empty($this->data)) {
+ if (!empty($this->data)) {
if (!empty($this->data['User']['remember_me']) &&
$this->data['User']['remember_me'] == 1) {
$this->Cookie->write('User.id', $this->Auth->user('id'));
}
}
if ($this->Session->check('Auth.User')) {
$this->redirect($this->Auth->redirect());
}
}
function logout() {
if ($this->Cookie->read('User.id')) {
$this->Cookie->delete('User.id');
}
$this->redirect($this->Auth->logout());
- }
+ }
+
function register($status = '') {
$this->set('title_for_layout', __('Register with Gridglo', true));
if (!$this->Session->check('Auth.User')) {
if (!empty($this->data)) {
$this->data['User']['group_id'] = 3;
$this->data['User']['active'] = 1;
if ($user = $this->User->register($this->data)) {
$this->_sendEmail($user);
$this->Session->write('Registration.email', $user['to']);
$this->redirect(array('action' => 'register', 'success'));
} else {
$this->Session->setFlash(__('We were unable to register your account!', true), 'error');
}
} elseif ($status) {
if ($this->Session->check('Registration.email')) {
$this->set('email', $this->Session->read('Registration.email'));
$this->render($this->action.'_'.$status);
} else {
$this->redirect(array('action' => 'register'));
}
}
} else {
$this->redirect('/');
}
}
function activate($key = null) {
if (!$this->Session->check('Auth.User')) {
if (!is_null($key)) {
if ($user = $this->User->activate($key)) {
$this->Auth->login($user);
$this->_sendEmail($user);
$this->Session->setFlash(__('Your account is verified!', true), 'success');
$this->redirect(array('action' => 'done'));
} else {
$this->Session->setFlash(__('We were unable to verify you account! Account may already be active.', true), 'error');
$this->redirect(array('action' => 'login'));
}
} else {
$this->redirect(array('action' => 'login'));
}
} else {
$this->redirect('/');
}
}
function done() {
if ($this->Session->check('Auth.User')) {
if (!empty($this->data)) {
if ($this->Auth->user('id')) {
$user = $this->User->read(null, $this->Auth->user('id'));
$this->User->save($this->data);
$this->Auth->login($user);
$this->redirect($this->Auth->redirect('/'));
} else {
$this->redirect(array('action' => 'login'));
}
} else {
$this->data = $this->Auth->user();
}
} else {
$this->redirect('/');
}
}
function skip() {
$this->redirect($this->Auth->redirect('/'));
// Track User/Insert History
// Send to Home Page
}
function recover() {
$this->set('title_for_layout', __('Reset your Password', true));
if (!empty($this->data)) {
if ($user = $this->User->recover($this->data)) {
$this->_sendEmail($user);
$this->Session->setFlash(__('Password Change Email has been sent!', true), 'success');
$this->redirect(array('action' => 'login'));
} else {
$this->Session->setFlash(__('No user found with that email', true), 'error');
}
}
}
function reset($key = null) {
if (!is_null($key)) {
if ($user = $this->User->resetKey($key)) {
$this->Session->write('Reset.User', $user);
}
}
if ($user = $this->Session->read('Reset.User')) {
$this->set('user', $user);
if (!empty($this->data)) {
if ($this->User->reset($this->data, $user['User']['id'])) {
$this->Session->delete('Reset');
$this->redirect('/');
}
}
} else {
$this->redirect('/');
}
}
function resend($email = null) {
if (!is_null($email)) {
if ($user = $this->User->resend($email)) {
$this->_sendEmail($user);
} else {
$this->Session->setFlash(__('Unable to send activation email. It may be that the account is already active or the email doesn\'t exisit.', true), 'error');
}
}
$this->redirect(array('action' => 'login'));
}
function changepassword() {
$this->layout = 'account';
$this->set('title_for_layout', __('Change Password', true));
if (!empty($this->data)) {
if ($user = $this->User->reset($this->data)) {
$this->Session->setFlash(__('Password Change Email has been sent!', true), 'success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to change your password. Please try again.', true), 'error');
$this->redirect(array('action' => 'changepassword'));
}
}
+ }
+
+ function asdfasdf() {
+ $users = $this->User->find('all');
+
+ $this->set('test', $users);
+
}
function admin_login() {
$this->set('title_for_layout', __('Administration Login', true));
$this->layout = "admin_login";
if (!empty($this->data)) {
if ($this->data['User']['remember_me'] == 1) {
$this->Cookie->write('User.id', $this->Auth->user('id'));
}
}
if ($this->Session->check('Auth.User')) {
$this->redirect($this->Auth->redirect());
}
}
function admin_logout() {
if ($this->Cookie->read('User.id')) {
$this->Cookie->delete('User.id');
}
$this->redirect($this->Auth->logout());
}
function admin_index() {
$this->set('title_for_layout', __('Users', true));
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
function admin_view($id = null) {
if (!$id) {
$this->Session->setFlash(sprintf(__('Invalid %s', true), 'user'), 'attention');
$this->redirect(array('action' => 'index'));
}
$this->set('user', $this->User->read(null, $id));
}
function admin_add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->register($this->data)) {
$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'user'), 'success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'user'), 'error');
}
}
$this->set('title_for_layout', sprintf(__('Add %s', true), 'User'));
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
function admin_edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(sprintf(__('Invalid %s', true), 'user'), 'attention');
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->User->register($this->data, $id)) {
$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'user'), 'success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'user'), 'error');
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $id);
}
$this->set('title_for_layout', sprintf(__('Edit "%s"', true), $this->data['User']['username']));
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
function admin_delete($id = null) {
if (!$id) {
$this->Session->setFlash(sprintf(__('Invalid id for %s', true), 'User'));
$this->redirect(array('action' => 'index'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash(sprintf(__('%s deleted', true), 'User'));
$this->redirect(array('action' => 'index'));
}
}
/* API STUFF */
function authenticate() {
$user = array();
if ($this->Auth->user('id')) {
$this->log('Logged in as '. $this->Auth->user('username'));
$user = $this->User->Account->getAccountByIdOrUsername($this->Auth->user('id'));
}
$this->set(compact('user'));
}
}
diff --git a/app/models/account.php b/app/models/account.php
index 0852fae..791e303 100644
--- a/app/models/account.php
+++ b/app/models/account.php
@@ -1,82 +1,98 @@
<?php
class Account extends AppModel {
var $name = 'Account';
var $displayField = 'account_type_id';
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $actsAs = array(
'FileUpload' => array(
'image' => array(
'required' => array('add' => true, 'edit' => false),
'directory' => 'img/profile',
- 'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png'),
+ 'allowed_mime' => array('image/jpeg', 'image/jpg', 'image/gif', 'image/png'),
'allowed_extensions' => array('.jpg', '.jpeg', '.png', '.gif'),
'allowed_size' => 2097152,
'random_filename' => true,
'resize' => array(
'70' => array(
'directory' => 'img/profile/140',
'width' => 140,
'phpThumb' => array(
'far' => 1,
'bg' => 'FFFFFF'
)
- )
+ ),
+ 'thumb' => array(
+ 'directory' => 'img/profile/140',
+ 'width' => 234234,
+ 'phpThumb' => array(
+ 'far' => 1,
+ 'bg' => 'FFFFFF'
+ )
+ ),
+ 'grande' => array(
+ 'directory' => 'img/profile/140',
+ 'width' => 23,
+ 'phpThumb' => array(
+ 'far' => 1,
+ 'bg' => 'FFFFFF'
+ )
+ )
)
)
)
);
var $belongsTo = array(
'AccountType' => array(
'className' => 'AccountType',
'foreignKey' => 'account_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Gender' => array(
'className' => 'Gender',
'foreignKey' => 'gender_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Source' => array(
'className' => 'Source',
'foreignKey' => 'source_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
function getAccountByIdOrUsername($id = null) {
if (!empty($id)) {
$account = $this->find('first',
array(
'conditions' => array(
'OR' => array(
array('User.id' => $id),
array('User.username' => $id)
),
),
)
);
if (!empty($account)) {
return $account;
}
}
return false;
}
}
?>
\ No newline at end of file
diff --git a/app/models/user.php b/app/models/user.php
index 41ddf74..0deaab6 100644
--- a/app/models/user.php
+++ b/app/models/user.php
@@ -1,332 +1,328 @@
<?php
class User extends AppModel {
var $name = 'User';
var $order = 'name ASC';
var $actsAs = array('Containable', 'Acl.Acl' => 'requester');
var $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasMany = array(
'Account' => array(
'className' => 'Account',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->validate = array(
'username' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => __('Username must not be empty.', true),
),
'isUnique' => array(
'rule' => array('isUnique' , 'username'),
'message' => __('Username is already taken. Please choose a different username', true)
),
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'message' => __('The username can contain letters and numbers only.', true)
),
'between' => array(
'rule' => array('between', 3, 16),
'message' => __('Username must be between 3 and 16 characters long.', true),
),
- 'minLength' => array(
- 'rule' => array('minLength', 1),
- 'message' => __('Username is a required field', true)
- )
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => __('A valid password is required.', true)
)
),
'old_password' => array(
'old_password' => array(
'rule' => array('minLength', 1),
'message' => __('Please enter your current password.', true)
),
),
'password_before' => array(
'between' => array(
'rule' => array('between', 6, 20),
'message' => __('Password must be between 6 and 20 characters long.', true)
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => __('A valid password is required.', true)
),
),
'password_confirmation' => array(
'matchFields' => array(
'rule' => array('matchFields', 'password_before'),
'message' => __('Password and Retype Password do not match.', true)
),
'minLength' => array(
'rule' => array('minLength', 1),
'message' => __('A valid retype password is required.', true)
),
),
'email' => array(
# 'isUnique' => array(
# 'rule' => array('isUnique', 'email'),
# 'message' => __('The email was already used by another user.', true)
# ),
'email' => array(
'rule' => 'email',
'message' => __('The email you provided does not appear to be valid.', true)
),
'minlength' => array(
'rule' => array('minLength', 1),
'message' => __('A valid email is required.', true)
),
),
// Change Password
'ip' => array(
'userIp' => array(
'rule' => 'ip',
'message' => __('Please specify a valid ip address', true),
'allowEmpty' => true,
),
),
);
}
function parentNode($type='Aro') {
if ($type == 'Aro') {
if (!$this->id && empty($this->data)) {
return null;
}
$data = $this->data;
if (empty($this->data)) {
$data = $this->read();
}
if (empty($data['User']['group_id'])) {
return null;
} else {
return array('model' => 'Group', 'foreign_key' => $data['User']['group_id']);
}
}
return false;
}
function afterSave($created) {
if (!$created) {
$parent = $this->parentNode();
$parent = $this->node($parent);
$node = $this->node();
$aro = $node[0];
$aro['Aro']['parent_id'] = $parent[0]['Aro']['id'];
$this->Aro->save($aro);
}
}
function register($data, $id = null) {
if (is_array($data)) {
if (!empty($data['User'])) {
if (empty($id) || !empty($data['User']['reset_key'])) {
$data['User']['key'] = Security::hash(uniqid(rand(), true).Configure::read('Security.salt'));
}
if (!empty($data['User']['before_password'])) {
$data['User']['password'] = Security::hash(Configure::read('Security.salt').$data['User']['before_password']);
}
if (!empty($id)) {
$data['User']['id'] = $id;
} else {
$data['User']['ip'] = $_SERVER['REMOTE_ADDR'];
$this->create();
}
if ($this->save($data)) {
$user = $this->read(null, $this->getLastInsertId());
$user['User']['username'] = $data['User']['username'];
$user['User']['password'] = $data['User']['before_password'];
$user['User']['activate_link'] = $this->appConfigurations['url'].'/users/activate/'. $data['User']['key'];
$user['to'] = $data['User']['email'];
# if ($admin == true) {
# } else {
$user['subject'] = sprintf(__('Registration Verification - %s', true), $this->appConfigurations['name']);
# }
$user['template'] = 'users/activate';
return $user;
} else {
return false;
}
} else {
return false;
}
}
}
function recover($data, $newPasswordLength = 8) {
$conditions = array();
if (is_array($data)) {
if (!empty($data['User'])) {
foreach ($data['User'] as $key => $datum) {
if ($this->hasField($key)) {
$conditions[$key] = $datum;
}
}
$user = $this->find('first', array('conditions' => $conditions));
if (!empty($user)) {
$user['User']['key'] = Security::hash(uniqid(rand(), true));
$user['User']['before_password'] = substr(sha1(uniqid(rand(), true)), 0, $newPasswordLength);
$user['to'] = $user['User']['email'];
$user['subject'] = sprintf(__('Account Reset - %s', true), $this->appConfigurations['name']);
$user['template'] = 'users/reset';
$user['User']['password'] = Security::hash(Configure::read('Security.salt').$user['User']['before_password']);
$user['User']['reset_link'] = $this->appConfigurations['url'].'/users/reset/'. $user['User']['key'];
$this->save($user, false);
return $user;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
function reset($data, $id = null) {
if (is_array($data)) {
if (!empty($data['User'])) {
if (!empty($data['User']['before_password'])) {
$data['User']['password'] = Security::hash(Configure::read('Security.salt').$data['User']['before_password']);
}
if (!empty($id)) {
$data['User']['id'] = $id;
if ($this->save($data)) {
return true;
}
}
}
}
return false;
}
function resetKey($key) {
if (isset($key)) {
$user = $this->find('first', array('conditions' => array('User.key' => $key)));
if (!empty($user)) {
$user['User']['key'] = '';
$this->save($user);
return $user;
} else {
return false;
}
}
return false;
}
function resend($email) {
if (!is_null($email)) {
$user = $this->find('first', array('contitions' => array('User.email' => $email, 'User.active' => 0)));
if (!empty($user)) {
$data['User']['key'] = Security::hash(uniqid(rand(), true));
$this->read(null, $user['User']['id']);
$this->save($data);
$user['User']['activate_link'] = $this->appConfigurations['url'].'/users/activate/'. $data['User']['key'];
$user['to'] = $user['User']['email'];
$user['subject'] = sprintf(__('Resent Verification - %s', true), $this->appConfigurations['name']);
$user['template'] = 'users/activate';
return $user;
}
}
return false;
}
function activate($key) {
$user = $this->find('first', array('conditions' => array('User.key' => $key, 'User.active' => 0)));
if (!empty($user)) {
$user['User']['active'] = 1;
$user['User']['key'] = '';
$this->save($user);
$user['to'] = $user['User']['email'];
$user['subject'] = sprintf(__('Welcome to %s, %s', true), $this->appConfigurations['name'], $user['User']['username']);
$user['template'] = 'users/welcome';
return $user;
} else {
return false;
}
}
function getUserByIdOrUsername($id = null) {
if (!empty($id)) {
$user = $this->find('first',
array(
'conditions' => array(
'OR' => array(
array('User.id' => $id),
array('User.username' => $id)
),
),
/* 'fields' => array(
'User.id',
'User.first_name',
'User.last_name',
'User.username',
'User.email',
)*/
)
);
if (!empty($user)) {
return $user;
}
}
return false;
}
}
diff --git a/app/plugins/acl/config/schema/schema.php b/app/plugins/acl/config/schema/schema.php
new file mode 100644
index 0000000..569fb52
--- /dev/null
+++ b/app/plugins/acl/config/schema/schema.php
@@ -0,0 +1,48 @@
+<?php
+/* SVN FILE: $Id$ */
+/* App schema generated on: 2010-09-15 16:09:19 : 1284583159*/
+class AppSchema extends CakeSchema {
+ var $name = 'App';
+
+ function before($event = array()) {
+ return true;
+ }
+
+ function after($event = array()) {
+ }
+
+ var $acos = array(
+ 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
+ 'parent_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'model' => array('type' => 'string', 'null' => true, 'default' => NULL),
+ 'foreign_key' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'alias' => array('type' => 'string', 'null' => true, 'default' => NULL),
+ 'lft' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'rght' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'indexes' => array(),
+ 'tableParameters' => array()
+ );
+ var $aros = array(
+ 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
+ 'parent_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'model' => array('type' => 'string', 'null' => true, 'default' => NULL),
+ 'foreign_key' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'alias' => array('type' => 'string', 'null' => true, 'default' => NULL),
+ 'lft' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'rght' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
+ 'indexes' => array(),
+ 'tableParameters' => array()
+ );
+ var $aros_acos = array(
+ 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
+ 'aro_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10),
+ 'aco_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10),
+ '_create' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
+ '_read' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
+ '_update' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
+ '_delete' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 2),
+ 'indexes' => array(),
+ 'tableParameters' => array()
+ );
+}
+?>
\ No newline at end of file
diff --git a/app/views/layouts/default.ctp b/app/views/layouts/default.ctp
index 1a6294f..e3630d4 100644
--- a/app/views/layouts/default.ctp
+++ b/app/views/layouts/default.ctp
@@ -1,56 +1,57 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $html->charset(); ?>
<title>
<?php echo $title_for_layout; ?> ::
<?php echo $appConfigurations['name']; ?>
</title>
<?php
if(!empty($meta_description)) :
echo $html->meta('description', $meta_description);
endif;
if(!empty($meta_keywords)) :
echo $html->meta('keywords', $meta_keywords);
endif;
echo $html->css('reset');
echo $html->css('style');
echo $html->css('clear');
echo $javascript->link('http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js');
echo $javascript->link('jquery/jquery.inlineedit');
echo $javascript->link('common');
echo $scripts_for_layout;
?>
</head>
<body>
<div id="message">
<?php
if($session->check('Message.flash')){
echo $session->flash();
}
if($session->check('Message.auth')){
echo $session->flash('auth');
}
?>
</div>
<div id="container">
+ <?php $this->log('Test');?>
<div id="header">
<div id="logo">
<?php echo $html->link($html->image('logo.gif', array('alt' => $appConfigurations['name'], 'title' => $appConfigurations['name'])), '/', array('escape' => false)); ?>
</div>
<div id="top-menu">
<?php echo $this->element('menu_top');?>
</div>
</div>
<div id="content" class="clearfix">
<?php echo $content_for_layout; ?>
<span class="clearFix"></span>
</div>
<?php echo $this->element('footer');?>
</div>
<div id="mask"><div id="modal" class="modal-container"><div id="modal-content"></div><div id="modal-close"> </div></div></div>
<?php echo $this->element('sql_dump'); ?>
</body>
</html>
diff --git a/app/views/users/index.ctp b/app/views/users/index.ctp
index 74d2045..57ca88e 100644
--- a/app/views/users/index.ctp
+++ b/app/views/users/index.ctp
@@ -1,144 +1,144 @@
<?php
echo $javascript->link("http://www.google.com/jsapi");
echo $javascript->codeBlock("google.load('maps', '3', {other_params:'sensor=false'});");
echo $javascript->codeBlock("geocoder = new google.maps.Geocoder();");
echo $javascript->codeBlock();
?>
var infowindow;
$(document).ready(function() {
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var mapDrag = function(event) {updateLayer(map.getCenter());}
google.maps.event.addListener(map, 'dragend', mapDrag, true);
var mapZoom = function(event) {updateLayer(map.getCenter());}
google.maps.event.addListener(map, 'zoom_changed', mapZoom, true);
if (geocoder) {
geocoder.geocode({'address': "<?php echo $account['Account']['location'];?>"},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
updateLayer(results[0].geometry.location);
} else {
}
}
);
}
function updateLayer(latlng) {
var epm_data = [
{"epm":56,"ame":2300,"ami":"Yes","renew":"CNG","ev":"No","leed":"NOT CERTIFIED"},
{"epm":67,"ame":1800,"ami":"Yes","renew":"NOT CERTIFIED","ev":"No","leed":"NOT CERTIFIED"},
{"epm":45,"ame":2546,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":88,"ame":3050,"ami":"No","renew":"CNG","ev":"No","leed":"CERTIFIED"},
{"epm":44,"ame":1457,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":87,"ame":2199,"ami":"Yes","renew":"CNG","ev":"No","leed":"SILVER"},
{"epm":77,"ame":2892,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":35,"ame":1913,"ami":"Yes","renew":"SOLAR","0":"CNG","ev":"No","leed":"NOT CERTIFIED"},
{"epm":96,"ame":3520,"ami":"Yes","renew":"SOLAR","ev":"Yes","leed":"PLATINUM"},
{"epm":58,"ame":4200,"ami":"No","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":67,"ame":2765,"ami":"No","renew":"NONE","ev":"No","leed":"GOLD"},
{"epm":59,"ame":1965,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":68,"ame":3275,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":37,"ame":2134,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":52,"ame":2755,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":85,"ame":3877,"ami":"Yes","renew":"NONE","ev":"Yes","leed":"CERTIFIED"},
{"epm":34,"ame":2433,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":66,"ame":1933,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":87,"ame":1456,"ami":"No","renew":"SOLAR","ev":"No","leed":"CERTIFIED"},
{"epm":84,"ame":2345,"ami":"Yes","renew":"NONE","ev":"No","leed":"SILVER"},
{"epm":76,"ame":2756,"ami":"Yes","renew":"NONE","ev":"No","leed":"CERTIFIED"},
{"epm":56,"ame":4234,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":74,"ame":3244,"ami":"No","renew":"SOLAR","0":"CNG","ev":"Yes","leed":"NOT CERTIFIED"},
{"epm":73,"ame":1655,"ami":"Yes","renew":"SOLAR","ev":"No","leed":"NOT CERTIFIED"},
{"epm":62,"ame":4266,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":45,"ame":2311,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":52,"ame":1966,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":60,"ame":1077,"ami":"Yes","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":28,"ame":2234,"ami":"No","renew":"NONE","ev":"No","leed":"NOT CERTIFIED"},
{"epm":65,"ame":3200,"ami":"Yes","renew":"NONE","ev":"No","leed":"CERTIFIED"}
];
$.ajax({
url: "/simple_geo/simple_geo/nearby/?hash="+latlng.toUrlValue(),
dataType: 'json',
success: function(result) {
$.each(result, function(i, data) {
var latlng = new google.maps.LatLng(data.Point.latitude,data.Point.longitude);
- var recordNum = i % epm_data.length;
- var imgNum = ((epm_data[recordNum].epm%10)*10);
+ var recordNum = i % epm_data.length;
+ var imgNum = ((Math.floor(epm_data[recordNum].epm/10)%10)*10);
var content = '<div class="map_popup" style="padding:0;margin:0;width:250px;">'+
'<h2 class="title" style="border-bottom: 1px solid #000">'+data.Point.name+'</h2>'+
'<div style="padding:5px 0; margin:5px 0;border-bottom:1px solid #000;overflow:hidden"><strong>EPM-Premise Rating:</strong> '+epm_data[recordNum].epm+'<br /><img src="/img/meter/b_'+imgNum+'.png" alt="'+imgNum+'"></div>'+
'<p><strong>Avg. Monthly Usage:</strong> '+epm_data[recordNum].ame+' kWh</p>'+
'<p><strong>AMI Ready:</strong> '+epm_data[recordNum].ami+'<br />'+
'<p><strong>Renewable Sources:</strong> '+epm_data[recordNum].renew+'</p>'+
'<p><strong>EV Charging Station:</strong> '+epm_data[recordNum].ev+'</p>'+
'<p><strong>LEED Certification:</strong> '+epm_data[recordNum].leed+'</p>'+
'</div>';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: "/img/SGBluePin.png"
});
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: content});
infowindow.open(map,marker);
$('.map_popup').parent().parent().css('overflow','hidden');
$('.map_popup').parent().css('overflow','hidden');
});
});
}
});
}
});
<?php echo $javascript->blockEnd();?>
<div class="clearfix"></div>
<div id="left-col">
<div class="box" style="width:99%">
<div class="topleft">
<div class="topright">
<div>
<div id="map"style="width:100%; height: 500px;" ></div>
</div>
</div>
</div>
<div class="bottomleft">
<div class="bottomright"> </div>
</div>
</div>
</div>
<div id="right-col">
<?php echo $this->element('account_menu')?>
</div>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.