├── .gitignore ├── Boost.python └── minimal │ ├── Makefile │ ├── hello_ext.C │ └── test_hello.py ├── FORTRAN ├── BilinearInterpolation │ ├── interpolated.pdf │ ├── interpolation.f90 │ ├── original.pdf │ ├── rect_surface_data.xdr │ └── test_interpolation.py ├── FindElementInArray │ ├── Makefile │ └── find_element_in_array.f90 ├── INI_Parsing │ ├── Makefile │ ├── ini.f90 │ ├── test.ini │ └── test_ini.f90 ├── LinearEquationSolver │ ├── Makefile │ ├── lu_solver.f90 │ ├── test_lu_solver.f90 │ └── test_lu_solver.py └── TridiagonalSolver │ ├── Makefile │ ├── README │ ├── test_tridiag.f90 │ ├── test_tridiag.py │ └── tridiag.f90 ├── Fundamentals └── zip.py ├── GoogleCloudPlatform └── driveAPIexample.py ├── LICENSE ├── Linear_Systems ├── LTI_Simulation_with_Python.py ├── first_order_LTI_step_response.png └── linear_filters.py ├── PairCorrelation ├── README ├── example_2D.py ├── example_3D.py ├── paircorrelation.py └── utilities.py ├── Plotting └── matplotlib │ ├── AxesGrid_example.py │ └── plot_without_axes.py ├── README ├── Visualization └── vtktools.py ├── XML └── write_wxGlade_XML.py ├── f2py └── simple_example │ ├── Makefile │ ├── simple_f2py_example.f90 │ └── test_f2py_example.py └── scipy └── interpolation.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.o 4 | *.so 5 | *.png 6 | -------------------------------------------------------------------------------- /Boost.python/minimal/Makefile: -------------------------------------------------------------------------------- 1 | # location of the Python header files 2 | 3 | PYTHON_VERSION = 2.7 4 | PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION) 5 | 6 | # location of the Boost Python include files and library 7 | 8 | BOOST_INC = /usr/include 9 | BOOST_LIB = /usr/lib 10 | 11 | # compile mesh classes 12 | TARGET = hello_ext 13 | 14 | $(TARGET).so: $(TARGET).o 15 | g++ -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python-$(PYTHON_VERSION) -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so 16 | 17 | $(TARGET).o: $(TARGET).C 18 | g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).C 19 | -------------------------------------------------------------------------------- /Boost.python/minimal/hello_ext.C: -------------------------------------------------------------------------------- 1 | char const* greet() 2 | { 3 | return "hello, world"; 4 | } 5 | 6 | #include 7 | 8 | BOOST_PYTHON_MODULE(hello_ext) 9 | { 10 | using namespace boost::python; 11 | def("greet", greet); 12 | } 13 | -------------------------------------------------------------------------------- /Boost.python/minimal/test_hello.py: -------------------------------------------------------------------------------- 1 | import hello_ext 2 | print hello_ext.greet() 3 | -------------------------------------------------------------------------------- /FORTRAN/BilinearInterpolation/interpolated.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cfinch/Shocksolution_Examples/d61b096eccab63cb2d847f70c250f6fba9dddc88/FORTRAN/BilinearInterpolation/interpolated.pdf -------------------------------------------------------------------------------- /FORTRAN/BilinearInterpolation/interpolation.f90: -------------------------------------------------------------------------------- 1 | module interpolation 2 | 3 | contains 4 | 5 | function binarysearch(length, array, value, delta) 6 | ! Given an array and a value, returns the index of the element that 7 | ! is closest to, but less than, the given value. 8 | ! Uses a binary search algorithm. 9 | ! "delta" is the tolerance used to determine if two values are equal 10 | ! if ( abs(x1 - x2) <= delta) then 11 | ! assume x1 = x2 12 | ! endif 13 | 14 | implicit none 15 | integer, intent(in) :: length 16 | real, dimension(length), intent(in) :: array 17 | !f2py depend(length) array 18 | real, intent(in) :: value 19 | real, intent(in), optional :: delta 20 | 21 | integer :: binarysearch 22 | 23 | integer :: left, middle, right 24 | real :: d 25 | 26 | if (present(delta) .eqv. .true.) then 27 | d = delta 28 | else 29 | d = 1e-9 30 | endif 31 | 32 | left = 1 33 | right = length 34 | do 35 | if (left > right) then 36 | exit 37 | endif 38 | middle = nint((left+right) / 2.0) 39 | if ( abs(array(middle) - value) <= d) then 40 | binarySearch = middle 41 | return 42 | else if (array(middle) > value) then 43 | right = middle - 1 44 | else 45 | left = middle + 1 46 | end if 47 | end do 48 | binarysearch = right 49 | 50 | end function binarysearch 51 | 52 | real function interpolate(x_len, x_array, y_len, y_array, f, x, y, delta) 53 | ! This function uses bilinear interpolation to estimate the value 54 | ! of a function f at point (x,y) 55 | ! f is assumed to be sampled on a regular grid, with the grid x values specified 56 | ! by x_array and the grid y values specified by y_array 57 | ! Reference: http://en.wikipedia.org/wiki/Bilinear_interpolation 58 | implicit none 59 | integer, intent(in) :: x_len, y_len 60 | real, dimension(x_len), intent(in) :: x_array 61 | real, dimension(y_len), intent(in) :: y_array 62 | real, dimension(x_len, y_len), intent(in) :: f 63 | real, intent(in) :: x,y 64 | real, intent(in), optional :: delta 65 | !f2py depend(x_len) x_array, f 66 | !f2py depend(y_len) y_array, f 67 | 68 | real :: denom, x1, x2, y1, y2 69 | integer :: i,j 70 | 71 | i = binarysearch(x_len, x_array, x) 72 | j = binarysearch(y_len, y_array, y) 73 | 74 | x1 = x_array(i) 75 | x2 = x_array(i+1) 76 | 77 | y1 = y_array(j) 78 | y2 = y_array(j+1) 79 | 80 | denom = (x2 - x1)*(y2 - y1) 81 | 82 | interpolate = (f(i,j)*(x2-x)*(y2-y) + f(i+1,j)*(x-x1)*(y2-y) + & 83 | f(i,j+1)*(x2-x)*(y-y1) + f(i+1, j+1)*(x-x1)*(y-y1))/denom 84 | 85 | end function interpolate 86 | 87 | end module interpolation 88 | -------------------------------------------------------------------------------- /FORTRAN/BilinearInterpolation/original.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cfinch/Shocksolution_Examples/d61b096eccab63cb2d847f70c250f6fba9dddc88/FORTRAN/BilinearInterpolation/original.pdf -------------------------------------------------------------------------------- /FORTRAN/BilinearInterpolation/rect_surface_data.xdr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cfinch/Shocksolution_Examples/d61b096eccab63cb2d847f70c250f6fba9dddc88/FORTRAN/BilinearInterpolation/rect_surface_data.xdr -------------------------------------------------------------------------------- /FORTRAN/BilinearInterpolation/test_interpolation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from numpy import * 3 | import interp 4 | from PlotUtils.PlotUtils3D import rect_surface_plot 5 | 6 | x_array = arange(-2.0, 2.1, 0.2) 7 | y_array = x_array.copy() 8 | z_array = empty([len(x_array), len(y_array)]) 9 | 10 | for i in range(len(x_array)): 11 | for j in range(len(y_array)): 12 | z_array[i,j] = x_array[i]*y_array[j]*exp(-x_array[i]**2 - y_array[j]**2) 13 | 14 | rect_surface_plot(x_array, y_array, z_array, "original") 15 | 16 | x_interpolated = arange(-2.0, 2.1, 0.1) 17 | y_interpolated = x_interpolated.copy() 18 | z_interpolated = empty([len(x_interpolated), len(y_interpolated)]) 19 | 20 | for i in range(len(x_interpolated)): 21 | for j in range(len(y_interpolated)): 22 | x = x_interpolated[i] 23 | y = y_interpolated[j] 24 | z_interpolated[i,j] = interp.interpolation.interpolate(len(x_array), 25 | x_array, len(y_array), y_array, z_array, x, y, delta=1e-5) 26 | 27 | rect_surface_plot(x_interpolated, y_interpolated, z_interpolated, "interpolated") 28 | -------------------------------------------------------------------------------- /FORTRAN/FindElementInArray/Makefile: -------------------------------------------------------------------------------- 1 | find_element : find_element_in_array.f90 2 | gfortran -o find_element find_element_in_array.f90 3 | -------------------------------------------------------------------------------- /FORTRAN/FindElementInArray/find_element_in_array.f90: -------------------------------------------------------------------------------- 1 | program find_element_in_array 2 | implicit none 3 | 4 | integer :: i, num_elements = 10000000, target_value = 9000000 5 | integer, dimension(:), allocatable :: array1, array2 6 | real :: t1, t2 7 | integer :: loc 8 | 9 | allocate(array1(num_elements), array2(num_elements)) 10 | 11 | ! Create array 12 | do i = 1, num_elements 13 | array1(i) = i 14 | end do 15 | 16 | ! Search array, method 1 17 | call cpu_time(t1) 18 | do i = 1, num_elements 19 | if (array1(i) .eq. target_value) then 20 | loc = i 21 | exit 22 | endif 23 | end do 24 | call cpu_time(t2) 25 | write(*,*) "Value ", target_value, " found at ", loc 26 | write(*,*) "CPU time: ", t2-t1 27 | 28 | ! Search array, method 2 29 | call cpu_time(t1) 30 | forall (i=1:num_elements) array2(i) = abs(array1(i) - target_value) 31 | loc = minloc(array2, 1) 32 | call cpu_time(t2) 33 | write(*,*) "Value ", target_value, " found at ", loc 34 | write(*,*) "CPU time: ", t2-t1 35 | 36 | ! Search array, method 3 37 | call cpu_time(t1) 38 | loc = minloc(abs(array1 - target_value), 1) 39 | call cpu_time(t2) 40 | write(*,*) "Value ", target_value, " found at ", loc 41 | write(*,*) "CPU time: ", t2-t1 42 | 43 | end program find_element_in_array 44 | -------------------------------------------------------------------------------- /FORTRAN/INI_Parsing/Makefile: -------------------------------------------------------------------------------- 1 | test_ini : ini.f90 test_ini.f90 2 | gfortran ini.f90 test_ini.f90 -o test_ini 3 | 4 | clean: 5 | rm ini.o test_ini.o test_ini 6 | -------------------------------------------------------------------------------- /FORTRAN/INI_Parsing/ini.f90: -------------------------------------------------------------------------------- 1 | ! PARSER - parse an ini file 2 | ! V1.0 6 AUG 03 3 | ! Written by Douglas S. Elder elderdo@yahoo.com 4 | 5 | !** common block that will contain the iniFile 6 | BLOCK DATA iniFile 7 | LOGICAL initialized 8 | INTEGER num_lines 9 | CHARACTER LINES(100)*256 10 | CHARACTER iniFilename*256 11 | COMMON /Options/ num_lines, LINES, initialized, iniFilename 12 | DATA initialized, num_lines, iniFilename / .FALSE., 0, 'Options.ini' / 13 | END 14 | 15 | !** allow you to use a different iniFile or to switch to another 16 | SUBROUTINE setIniFilename(value) 17 | CHARACTER value*(*) 18 | LOGICAL initialized 19 | INTEGER num_lines 20 | CHARACTER LINES(100)*256 21 | CHARACTER iniFilename*256 22 | COMMON /Options/ num_lines, LINES, initialized, iniFilename 23 | if (initialized .EQV. .TRUE.) then 24 | if (value .NE. iniFilename) then 25 | ! switching to a different ini file 26 | iniFilename = value 27 | call loadOptions 28 | end if 29 | else 30 | ! overriding the default ini file 31 | iniFilename = value 32 | end if 33 | END 34 | 35 | !**** read in the iniFile into the common Options block 36 | SUBROUTINE loadOptions 37 | IMPLICIT NONE 38 | INTEGER num_lines 39 | LOGICAL initialized 40 | CHARACTER LINES(100)*256 41 | CHARACTER iniFilename*256 42 | COMMON /Options/ num_lines, LINES, initialized, iniFilename 43 | CHARACTER LINE*256 44 | ! WRITE(*,*) 'loadOptions' 45 | num_lines = 0 46 | OPEN(UNIT=33, FILE=iniFilename) 47 | 1 READ(33,'(A)', END=10) LINE 48 | num_lines = num_lines + 1 49 | if (num_lines .GT. 100) then 50 | WRITE(0,*) 'Options.ini file > 100 lines.' 51 | STOP 16 52 | else 53 | LINES(num_lines) = LINE 54 | end if 55 | GOTO 1 56 | 57 | 10 CONTINUE 58 | ! WRITE(*,*) 'num_lines = ',num_lines 59 | CLOSE (UNIT=33) 60 | initialized = .TRUE. 61 | END 62 | 63 | !*** try to find the Section and keyword, if found return its value 64 | !*** otherwise return an empty string and an error 65 | SUBROUTINE getValue(section, kwd, value, error) 66 | IMPLICIT NONE 67 | logical, intent(out) :: error 68 | CHARACTER section*(*) 69 | CHARACTER kwd*(*) 70 | CHARACTER value*(*) 71 | INTEGER I, STARTVAL 72 | INTEGER num_lines 73 | LOGICAL initialized 74 | CHARACTER LINES(100)*256 75 | CHARACTER iniFilename*256 76 | COMMON /Options/ num_lines, LINES, initialized, iniFilename 77 | INTEGER MAXLINE 78 | PARAMETER (MAXLINE = 256) 79 | CHARACTER LINE*256 80 | LOGICAL foundSection, foundKwd 81 | 82 | error = .false. 83 | 84 | if (initialized .EQV. .FALSE.) then 85 | call loadOptions 86 | end if 87 | foundSection = .FALSE. 88 | foundKwd = .FALSE. 89 | value = '' 90 | !WRITE(*,*) 'Looking for ',section 91 | DO I=1, num_lines 92 | if (LINES(I)(1:1) .EQ. '[') then 93 | startval = index(lines(i), '[' // trim(section) // ']', .true.) 94 | if (startval > 0) then 95 | foundSection = .true. 96 | endif 97 | else 98 | if ((foundSection .EQV. .TRUE.) .AND. (lines(i)(1:1) .NE. ';')) then 99 | startval = index(lines(i), kwd, .true.) 100 | if (startval > 0) then 101 | startval = index(lines(i), '=') 102 | value = LINES(I)(STARTVAL+1:) 103 | end if 104 | end if 105 | end if 106 | ENDDO 107 | if (value .eq. '') then 108 | error = .true. 109 | endif 110 | END 111 | 112 | -------------------------------------------------------------------------------- /FORTRAN/INI_Parsing/test.ini: -------------------------------------------------------------------------------- 1 | ; A sample INI file 2 | 3 | [setup] 4 | simulate=true 5 | num_iterations=100 6 | 7 | [constants] 8 | pi=3.14159 9 | e=2.1718281828 10 | ;Make sure commented lines are ignored! 11 | ;pi=0.00000 12 | -------------------------------------------------------------------------------- /FORTRAN/INI_Parsing/test_ini.f90: -------------------------------------------------------------------------------- 1 | ! PARSER - parse an ini file 2 | ! V1.0 6 AUG 03 3 | PROGRAM MAIN 4 | IMPLICIT NONE 5 | CHARACTER str*256 6 | external setIniFilename, getValue 7 | logical error, simulate 8 | real pi 9 | 10 | call setIniFilename('test.ini') 11 | 12 | call getValue('constants', 'pi', str, error) 13 | if (error .eqv. .false.) then 14 | write(*,'(a,a)') 'str = ', trim(str) 15 | read(str, '(f7.5)') pi 16 | write(*,'(a,f7.5)') 'pi = ', pi 17 | endif 18 | 19 | call getValue('setup', 'simulate', str, error) 20 | if (error .eqv. .false.) then 21 | write(*,'(a,a)') 'str = ', trim(str) 22 | read(str, '(L7)') simulate 23 | write(*,'(a,L1)') 'simulate = ', simulate 24 | 25 | endif 26 | 27 | ! Test error handling. This SHOULD print the error message. 28 | call getValue('doesnotexist', 'dummy', str, error) 29 | if (error .eqv. .false.) then 30 | write(*,'(a,a)') 'dummy = ', trim(str) 31 | else 32 | write(*,'(a)') 'Error: section or keyword not found' 33 | endif 34 | 35 | end program 36 | 37 | -------------------------------------------------------------------------------- /FORTRAN/LinearEquationSolver/Makefile: -------------------------------------------------------------------------------- 1 | lu_solver.so : lu_solver.f90 2 | f2py2.6 -c -m lu_solver lu_solver.f90 3 | 4 | test_lu_solver : test_lu_solver.o lu_solver.o 5 | gfortran -o test_lu_solver test_lu_solver.o lu_solver.o 6 | 7 | test_lu_solver.o : test_lu_solver.f90 8 | gfortran -c test_lu_solver.f90 9 | 10 | lu_solver.o : lu_solver.f90 11 | gfortran -c lu_solver.f90 12 | 13 | clean : 14 | rm test_lu_solver.o lu_solver.o lu_solver.so 15 | -------------------------------------------------------------------------------- /FORTRAN/LinearEquationSolver/lu_solver.f90: -------------------------------------------------------------------------------- 1 | !******************************************************* 2 | !* LU decomposition routines used by test_lu.f90 * 3 | !* * 4 | !* F90 version by J-P Moreau, Paris * 5 | !* --------------------------------------------------- * 6 | !* Reference: * 7 | !* * 8 | !* "Numerical Recipes By W.H. Press, B. P. Flannery, * 9 | !* S.A. Teukolsky and W.T. Vetterling, Cambridge * 10 | !* University Press, 1986" [BIBLI 08]. * 11 | !* * 12 | !******************************************************* 13 | MODULE LU 14 | CONTAINS 15 | 16 | ! *************************************************************** 17 | ! * Given an N x N matrix A, this routine replaces it by the LU * 18 | ! * decomposition of a rowwise permutation of itself. A and N * 19 | ! * are input. INDX is an output vector which records the row * 20 | ! * permutation effected by the partial pivoting; D is output * 21 | ! * as -1 or 1, depending on whether the number of row inter- * 22 | ! * changes was even or odd, respectively. This routine is used * 23 | ! * in combination with LUBKSB to solve linear equations or to * 24 | ! * invert a matrix. Return code is 1, if matrix is singular. * 25 | ! *************************************************************** 26 | Subroutine LUDCMP(A,N,INDX,D,CODE) 27 | IMPLICIT NONE 28 | integer, parameter :: nmax = 100 29 | real, parameter :: tiny = 1.5D-16 30 | 31 | real*8, intent(inout), dimension(N,N) :: A 32 | integer, intent(in) :: N 33 | integer, intent(out) :: D, CODE 34 | integer, intent(out), dimension(N) :: INDX 35 | !f2py depend(N) A, indx 36 | 37 | REAL*8 :: AMAX, DUM, SUMM, VV(NMAX) 38 | INTEGER :: i, j, k, imax 39 | 40 | D=1; CODE=0 41 | 42 | DO I=1,N 43 | AMAX=0.d0 44 | DO J=1,N 45 | IF (DABS(A(I,J)).GT.AMAX) AMAX=DABS(A(I,J)) 46 | END DO ! j loop 47 | IF(AMAX.LT.TINY) THEN 48 | CODE = 1 49 | RETURN 50 | END IF 51 | VV(I) = 1.d0 / AMAX 52 | END DO ! i loop 53 | 54 | DO J=1,N 55 | DO I=1,J-1 56 | SUMM = A(I,J) 57 | DO K=1,I-1 58 | SUMM = SUMM - A(I,K)*A(K,J) 59 | END DO ! k loop 60 | A(I,J) = SUMM 61 | END DO ! i loop 62 | AMAX = 0.d0 63 | DO I=J,N 64 | SUMM = A(I,J) 65 | DO K=1,J-1 66 | SUMM = SUMM - A(I,K)*A(K,J) 67 | END DO ! k loop 68 | A(I,J) = SUMM 69 | DUM = VV(I)*DABS(SUMM) 70 | IF(DUM.GE.AMAX) THEN 71 | IMAX = I 72 | AMAX = DUM 73 | END IF 74 | END DO ! i loop 75 | 76 | IF(J.NE.IMAX) THEN 77 | DO K=1,N 78 | DUM = A(IMAX,K) 79 | A(IMAX,K) = A(J,K) 80 | A(J,K) = DUM 81 | END DO ! k loop 82 | D = -D 83 | VV(IMAX) = VV(J) 84 | END IF 85 | 86 | INDX(J) = IMAX 87 | IF(DABS(A(J,J)) < TINY) A(J,J) = TINY 88 | 89 | IF(J.NE.N) THEN 90 | DUM = 1.d0 / A(J,J) 91 | DO I=J+1,N 92 | A(I,J) = A(I,J)*DUM 93 | END DO ! i loop 94 | END IF 95 | END DO ! j loop 96 | 97 | RETURN 98 | END subroutine LUDCMP 99 | 100 | 101 | ! ****************************************************************** 102 | ! * Solves the set of N linear equations A . X = B. Here A is * 103 | ! * input, not as the matrix A but rather as its LU decomposition, * 104 | ! * determined by the routine LUDCMP. INDX is input as the permuta-* 105 | ! * tion vector returned by LUDCMP. B is input as the right-hand * 106 | ! * side vector B, and returns with the solution vector X. A, N and* 107 | ! * INDX are not modified by this routine and can be used for suc- * 108 | ! * cessive calls with different right-hand sides. This routine is * 109 | ! * also efficient for plain matrix inversion. * 110 | ! ****************************************************************** 111 | Subroutine LUBKSB(A, N, INDX, B) 112 | integer, intent(in) :: N 113 | real*8, intent(in), dimension(N,N) :: A 114 | integer, intent(in), dimension(N) :: INDX 115 | real*8, intent(inout), dimension(N) :: B 116 | !f2py depend(N) A, INDX, B 117 | 118 | REAL*8 SUMM 119 | 120 | II = 0 121 | 122 | DO I=1,N 123 | LL = INDX(I) 124 | SUMM = B(LL) 125 | B(LL) = B(I) 126 | IF(II.NE.0) THEN 127 | DO J=II,I-1 128 | SUMM = SUMM - A(I,J)*B(J) 129 | END DO ! j loop 130 | ELSE IF(SUMM.NE.0.d0) THEN 131 | II = I 132 | END IF 133 | B(I) = SUMM 134 | END DO ! i loop 135 | 136 | DO I=N,1,-1 137 | SUMM = B(I) 138 | IF(I < N) THEN 139 | DO J=I+1,N 140 | SUMM = SUMM - A(I,J)*B(J) 141 | END DO ! j loop 142 | END IF 143 | B(I) = SUMM / A(I,I) 144 | END DO ! i loop 145 | 146 | RETURN 147 | END subroutine LUBKSB 148 | 149 | END MODULE LU 150 | -------------------------------------------------------------------------------- /FORTRAN/LinearEquationSolver/test_lu_solver.f90: -------------------------------------------------------------------------------- 1 | !******************************************************* 2 | !* Solving a linear system AX = B by LU decomposition * 3 | !* with dynamic allocations * 4 | !* * 5 | !* F90 version by J-P Moreau, Paris * 6 | !* --------------------------------------------------- * 7 | !* SAMPLE RUN: * 8 | !* * 9 | !* Input file (test_lu.dat): * 10 | !* * 11 | !* 4 * 12 | !* 8 2 3 12 25.0 * 13 | !* 2 4 7 0.25 13.25 * 14 | !* 3 7 3 5 18.0 * 15 | !* 12 0.25 5 2 19.25 * 16 | !* * 17 | !* Output file (test_lu.lst): * 18 | !* * 19 | !* --------------------------------------------------- * 20 | !* LINEAR SYSTEM TO BE SOLVED: * 21 | !* --------------------------------------------------- * 22 | !* N=4 * 23 | !* * 24 | !* 8.000000 2.000000 3.000000 12.00000 25.00000 * 25 | !* 2.000000 4.000000 7.000000 0.250000 13.25000 * 26 | !* 3.000000 7.000000 3.000000 5.000000 18.00000 * 27 | !* 12.00000 0.250000 5.000000 2.000000 19.25000 * 28 | !* * 29 | !* System solution: * 30 | !* * 31 | !* X1= 1.000000 * 32 | !* X2= 1.000000 * 33 | !* X3= 1.000000 * 34 | !* X4= 1.000000 * 35 | !* --------------------------------------------------- * 36 | !* * 37 | !* Uses: module LU * 38 | !******************************************************* 39 | Program test_lu_solver 40 | USE LU 41 | implicit none 42 | 43 | real*8, pointer :: A(:,:) !real matrix (n x n) 44 | real*8, pointer :: B(:) !real vector (n) 45 | real*8, pointer :: temp(:) !real temporary vector (n+1) 46 | integer,pointer :: INDX(:) !integer vector (n) 47 | 48 | integer :: i, d, rc, n = 4 49 | 50 | !dynamic allocations 51 | allocate(A(n,n)) 52 | allocate(B(n)) 53 | allocate(temp(n+1)) 54 | allocate(INDX(n)) 55 | 56 | ! Fill matrix A 57 | ! 8 2 3 12 25.0 58 | ! 2 4 7 0.25 13.25 59 | ! 3 7 3 5 18.0 60 | ! 12 0.25 5 2 19.25 61 | 62 | A(1,1) = 8; A(1,2) = 2; A(1,3) = 3; A(1,4) = 12 63 | A(2,1) = 2; A(2,2) = 4; A(2,3) = 7; A(2,4) = 0.25 64 | A(3,1) = 3; A(3,2) = 7; A(3,3) = 3; A(3,4) = 5 65 | A(4,1) = 12; A(4,2) = 0.25; A(4,3) = 5; A(4,4) = 2 66 | 67 | ! Vector B 68 | B(1) = 25 69 | B(2) = 13.25 70 | B(3) = 18.0 71 | B(4) = 19.25 72 | 73 | !call LU decomposition routine 74 | call LUDCMP(A,n,INDX,D,rc) 75 | 76 | !call appropriate solver if previous return code is ok 77 | if (rc.eq.0) then 78 | call LUBKSB(A,n,INDX,B) 79 | endif 80 | 81 | !print results or error message 82 | if (rc.eq.1) then 83 | write(*,*) ' The system matrix is singular, no solution !' 84 | else 85 | write(*,*) ' System solution:' 86 | do i=1, n 87 | write(*,*) i,B(i) 88 | end do 89 | end if 90 | 91 | end program test_lu_solver 92 | -------------------------------------------------------------------------------- /FORTRAN/LinearEquationSolver/test_lu_solver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from numpy import * 3 | from matplotlib import pyplot as plt 4 | import lu_solver 5 | 6 | # Setup 7 | num_layers = 4 8 | 9 | D = ones(num_layers) 10 | delta_h = ones(num_layers) 11 | 12 | D[1] = 0.5 13 | D[3] = 2.0 14 | D[2] = 0.1 15 | 16 | delta_h[0] = 0.25 17 | delta_h[1] = 1.0 18 | delta_h[2] = 1.75 19 | delta_h[3] = 0.25 20 | 21 | C_0 = 0 22 | C_N = 1.0 23 | 24 | # Set up matrices and arrays 25 | A = array([[8, 2, 3, 12], [2, 4, 7, 0.25], [3, 7, 3, 5], [12, 0.25, 5, 2]], 26 | dtype='double', order='f') 27 | print(A) 28 | b = array([25, 13.25, 18, 19.25], dtype=float64, order='f') 29 | print(b) 30 | 31 | indx, d, code = lu_solver.lu.ludcmp(A, num_layers) 32 | 33 | print("LU Decomposition:") 34 | print A 35 | print indx 36 | print d 37 | print code 38 | 39 | if code == 0: 40 | lu_solver.lu.lubksb(A, num_layers, indx, b) 41 | 42 | print("Solution:") 43 | print b 44 | -------------------------------------------------------------------------------- /FORTRAN/TridiagonalSolver/Makefile: -------------------------------------------------------------------------------- 1 | tridiag.so : tridiag.f90 2 | f2py2.6 -c -m tridiag tridiag.f90 3 | 4 | test_tridiag : tridiag.o test_tridiag.o 5 | gfortran -o test_tridiag test_tridiag.o tridiag.o 6 | 7 | test_tridiag.o : test_tridiag.f90 8 | gfortran -c test_tridiag.f90 9 | 10 | tridiag.o : tridiag.f90 11 | gfortran -c tridiag.f90 12 | 13 | clean : 14 | rm test_tridiag.o tridiag.o tridiag.so tri.mod test_tridiag 15 | -------------------------------------------------------------------------------- /FORTRAN/TridiagonalSolver/README: -------------------------------------------------------------------------------- 1 | To build a library that can be imported into Python, type: 2 | $ make 3 | $ python test_tridiag.py 4 | 5 | To build the Fortran library and the Fortran test program: 6 | $ make test_tridiag 7 | $ ./test_tridiag 8 | -------------------------------------------------------------------------------- /FORTRAN/TridiagonalSolver/test_tridiag.f90: -------------------------------------------------------------------------------- 1 | program fortran_linear_solver 2 | use tri 3 | implicit none 4 | 5 | integer , parameter :: N = 5 6 | real, dimension(N) :: A,B,C,R,U 7 | integer :: CODE 8 | 9 | A = (/10.0, 10.0, 10.0, 10.0, 0.0/) 10 | B = (/-40.0, -30.0, -30.0, -30.0, 40.0/) 11 | C = (/10.0, 10.0, 10.0, 10.0, 0.0/) 12 | R = (/-10.0, -10.0, -10.0, -10.0, -30.0/) 13 | 14 | CALL TRIDIAG(A,B,C,R,N,U,CODE) 15 | 16 | print *, U 17 | print *, CODE 18 | 19 | end program fortran_linear_solver 20 | -------------------------------------------------------------------------------- /FORTRAN/TridiagonalSolver/test_tridiag.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from numpy import * 3 | from scipy.linalg import solve 4 | import tridiag 5 | 6 | upper = array([10.0, 10.0, 10.0, 10.0, 0.0]) 7 | middle = array([-40.0, -30.0, -30.0, -30.0, 40.0]) 8 | lower = upper.copy() 9 | b = array([-10.0, -10.0, -10.0, -10.0, -30.0]) 10 | m = len(middle) 11 | n = m 12 | 13 | (solution, exit_code) = tridiag.tri.tridiag(lower, middle, upper, b, n) 14 | 15 | print "Fortran solution:" 16 | print solution 17 | print exit_code 18 | 19 | # Create matrix from diagonals 20 | coeffs = zeros([m,n]) 21 | 22 | coeffs[0,0] = middle[0] 23 | coeffs[0,1] = upper[0] 24 | 25 | for i in range(1,m-1): 26 | coeffs[i,i-1] = lower[i] 27 | coeffs[i,i] = middle[i] 28 | coeffs[i,i+1] = upper[i] 29 | 30 | coeffs[m-1,m-2] = lower[m-1] 31 | coeffs[m-1,m-1] = middle[m-1] 32 | 33 | print "Python input:" 34 | print coeffs 35 | print b 36 | Python_solution = solve(coeffs, b) 37 | 38 | print "Python solution:" 39 | print Python_solution 40 | 41 | 42 | -------------------------------------------------------------------------------- /FORTRAN/TridiagonalSolver/tridiag.f90: -------------------------------------------------------------------------------- 1 | MODULE TRI 2 | CONTAINS 3 | SUBROUTINE TRIDIAG(A,B,C,R,N,U,CODE) 4 | !***************************************************************** 5 | ! Solves for a vector U of length N the tridiagonal linear set 6 | ! M U = R, where A, B and C are the three main diagonals of matrix 7 | ! M(N,N), the other terms are 0. R is the right side vector. 8 | !***************************************************************** 9 | implicit none 10 | ! integer, parameter :: NMAX=100 11 | 12 | real, dimension(N), intent(in) :: A,B,C,R 13 | !f2py depend(N) A,B,C,R 14 | 15 | real, dimension(N), intent(out) :: U 16 | integer, intent(in) :: N 17 | integer, intent(out) :: CODE 18 | 19 | REAL BET,GAM(N) 20 | integer J 21 | 22 | IF(B(1).EQ.0.D0) THEN 23 | CODE=1 24 | RETURN 25 | END IF 26 | 27 | BET=B(1) 28 | U(1)=R(1)/BET 29 | DO J=2,N !Decomposition and forward substitution 30 | GAM(J)=C(J-1)/BET 31 | BET=B(J)-A(J)*GAM(J) 32 | IF(BET.EQ.0.D0) THEN !Algorithm fails 33 | CODE=2 34 | RETURN 35 | END IF 36 | U(J)=(R(J)-A(J)*U(J-1))/BET 37 | END DO 38 | 39 | DO J=N-1,1,-1 !Back substitution 40 | U(J)=U(J)-GAM(J+1)*U(J+1) 41 | END DO 42 | 43 | CODE=0 44 | RETURN 45 | end subroutine tridiag 46 | 47 | END MODULE TRI 48 | -------------------------------------------------------------------------------- /Fundamentals/zip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # From sequences to a sequence of tuples 4 | a = range(0, 5) 5 | b = range(5, 10) 6 | c = range(10, 15) 7 | 8 | sequence_of_tuples = zip(a, b, c) 9 | print("Sequence of tuples:") 10 | print(sequence_of_tuples) 11 | 12 | # From a sequence of tuples to multiple sequences 13 | a1, b1, c1 = zip(*sequence_of_tuples) 14 | print("Separate sequences:") 15 | print(a1) 16 | print(b1) 17 | print(c1) 18 | 19 | # How it works 20 | def test_fn(*args): 21 | """Number of arguments is not known in advance""" 22 | print("Arguments passed to function:") 23 | for a in args: 24 | print a 25 | 26 | test_fn(*sequence_of_tuples) 27 | 28 | # Convert tuples to lists (optional) 29 | a1 = list(a1) 30 | print(type(a1)) 31 | -------------------------------------------------------------------------------- /GoogleCloudPlatform/driveAPIexample.py: -------------------------------------------------------------------------------- 1 | """Demonstrate basic usage of the Python client for Google Drive API v3 2 | 3 | Created by Craig Finch (cfinch@ieee.org) 4 | https://www.shocksolution.com 5 | GPLv3 License 6 | """ 7 | 8 | import tempfile 9 | 10 | from apiclient import discovery 11 | from apiclient.http import MediaFileUpload 12 | 13 | def credentials_from_file(): 14 | """Load credentials from a service account file 15 | Args: 16 | None 17 | Returns: service account credential object 18 | 19 | https://developers.google.com/identity/protocols/OAuth2ServiceAccount 20 | """ 21 | 22 | from google.oauth2 import service_account 23 | import googleapiclient.discovery 24 | 25 | # https://developers.google.com/identity/protocols/googlescopes#drivev3 26 | SCOPES = [ 27 | 'https://www.googleapis.com/auth/drive' 28 | ] 29 | SERVICE_ACCOUNT_FILE = './name-of-service-account-key.json' 30 | 31 | credentials = service_account.Credentials.from_service_account_file( 32 | SERVICE_ACCOUNT_FILE, scopes=SCOPES) 33 | 34 | return credentials 35 | 36 | # Set your Google email address here 37 | userEmail = 'craig@example.com' 38 | 39 | credentials = credentials_from_file() 40 | service = discovery.build('drive', 'v3', credentials=credentials) 41 | 42 | # Create a folder 43 | # https://developers.google.com/drive/v3/web/folder 44 | 45 | folder_metadata = { 46 | 'name': 'My Test Folder', 47 | 'mimeType': 'application/vnd.google-apps.folder' 48 | } 49 | cloudFolder = service.files().create(body=folder_metadata).execute() 50 | 51 | # Upload a file in the folder 52 | # https://developers.google.com/api-client-library/python/guide/media_upload 53 | # https://developers.google.com/drive/v3/reference/files/create 54 | 55 | file_metadata = { 56 | 'name': 'A Test File', 57 | 'parents': [cloudFolder['id']] 58 | } 59 | 60 | with tempfile.NamedTemporaryFile(mode='w') as tf: 61 | tf.write("This is some test data") 62 | 63 | # https://developers.google.com/api-client-library/python/guide/media_upload 64 | media = MediaFileUpload(tf.name, mimetype='text/plain') 65 | # https://developers.google.com/drive/v3/web/manage-uploads 66 | cloudFile = service.files().create(body=file_metadata).execute() 67 | 68 | # Share file with a human user 69 | # https://developers.google.com/drive/v3/web/manage-sharing 70 | # https://developers.google.com/drive/v3/reference/permissions/create 71 | 72 | cloudPermissions = service.permissions().create(fileId=cloudFile['id'], 73 | body={'type': 'user', 'role': 'reader', 'emailAddress': userEmail}).execute() 74 | 75 | cp = service.permissions().list(fileId=cloudFile['id']).execute() 76 | print(cp) 77 | 78 | # List files in our folder 79 | # https://developers.google.com/drive/v3/web/search-parameters 80 | # https://developers.google.com/drive/v3/reference/files/list 81 | 82 | query = "'{}' in parents".format(cloudFolder['id']) 83 | filesInFolder = service.files().list(q=query, orderBy='folder', pageSize=10).execute() 84 | items = filesInFolder.get('files', []) 85 | 86 | # Print the paged results 87 | if not items: 88 | print('No files found.') 89 | else: 90 | print('Files:') 91 | for item in items: 92 | print('{0} ({1})'.format(item['name'], item['id'])) 93 | # service.files().delete(fileId=item['id']).execute() # Optional cleanup -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Linear_Systems/LTI_Simulation_with_Python.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from numpy import * 3 | from matplotlib import pyplot as plt 4 | from scipy import signal 5 | 6 | # Setup 7 | tau = 5.0 * 60 # 5 minutes 8 | t_max = 60 * 30.0 # 30 minute experiment 9 | dt = 10.0 10 | 11 | ### Using the lti class from scipy.signal ### 12 | # Define a first-order LTI system 13 | sys = signal.lti(1, [1, 1.0 / tau]) 14 | 15 | # Plot its step response with step method 16 | h_times = arange(0, t_max, dt) 17 | 18 | step_response = sys.step(T=h_times)[1] 19 | plt.plot(h_times, step_response / step_response.max()) # normalize 20 | plt.axhline(0.63, color='red') # mark time constant 21 | plt.axvline(tau, color='red') 22 | plt.xlabel('t') 23 | plt.ylabel('h(t)') 24 | plt.title('Step response') 25 | 26 | # Plot its impulse response with impulse method 27 | plt.figure() 28 | plt.plot(h_times, sys.impulse(T=h_times)[1], label='Using step method') 29 | plt.xlabel('t') 30 | plt.ylabel('h(t)') 31 | plt.title('Impulse response') 32 | 33 | ### Defining our own 1st order LTI system ### 34 | def h(t, tau): 35 | """Impulse response of first-order LTI system. 36 | Args: 37 | h array of time values 38 | tau time constant 39 | """ 40 | h = exp(-t / tau) 41 | h[t < 0] = 0.0 42 | return h 43 | 44 | plt.plot(h_times, h(h_times,tau), color='green', marker='.', ls='', 45 | label='Using h(t)') 46 | plt.xlabel('t') 47 | plt.ylabel('h(t)') 48 | plt.title('Impulse response') 49 | plt.legend(loc='best') 50 | 51 | # Define a sampled step function 52 | x_times = arange(-t_max, t_max, dt) 53 | step = zeros(len(x_times)) 54 | step[len(step)/2:] = 1.0 55 | 56 | plt.figure() 57 | plt.plot(x_times, step, color='black', label='step fn') 58 | 59 | # Convolve step function with impulse response 60 | step_response = convolve(h(h_times, tau), step, mode='valid') 61 | plt.plot(h_times, step_response[:-1]/step_response.max(), color='green', 62 | marker='.', label='step response') 63 | plt.xlabel('t') 64 | plt.ylabel('h(t)') 65 | plt.title('Step response') 66 | 67 | # Deconvolve to recover original signal 68 | h_array = h(h_times, tau) 69 | 70 | # Pad step_response(t) to be longer than h(t) 71 | step_response = concatenate([zeros(len(h_times)), step_response, 72 | ones(len(h_times))]) 73 | 74 | x_reconstructed = signal.deconvolve(step_response, h_array) 75 | 76 | x_len = len(step_response) - len(h_times) + 1 77 | x_reconstructed_times = arange(-dt*x_len/2, dt*(x_len/2-1), dt) 78 | 79 | plt.plot(x_reconstructed_times, x_reconstructed[0][:-1], color='blue', ls='', 80 | marker='s', label='recovered step fn') 81 | plt.legend(loc='best') 82 | plt.show() 83 | -------------------------------------------------------------------------------- /Linear_Systems/first_order_LTI_step_response.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cfinch/Shocksolution_Examples/d61b096eccab63cb2d847f70c250f6fba9dddc88/Linear_Systems/first_order_LTI_step_response.png -------------------------------------------------------------------------------- /Linear_Systems/linear_filters.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import scipy.signal 5 | 6 | # Filter parameters 7 | cutoff = 0.2 8 | numtaps = 100 9 | order = 4 # IIR 10 | 11 | # Input signal 12 | x = np.concatenate([np.ones(100), np.ones(100) * 10.0]) # nonzero step function 13 | 14 | # FIR LPF 15 | lpf = scipy.signal.firwin(numtaps, cutoff, window=('hamming')) 16 | 17 | # Compute and plot frequency response 18 | lpf_freq, lpf_response = scipy.signal.freqz(lpf) 19 | 20 | plt.figure() 21 | plt.suptitle('FIR filter frequency response') 22 | plt.subplot(2,1,1) 23 | plt.plot(lpf_freq, np.abs(lpf_response), marker='.') 24 | plt.xlabel('f/f0') 25 | plt.ylabel('Abs') 26 | 27 | plt.subplot(2,1,2) 28 | plt.plot(lpf_freq, np.unwrap(np.angle(lpf_response)), marker='.') 29 | plt.xlabel('f/f0') 30 | plt.ylabel('Angle') 31 | 32 | # Filter signal, no initial conditions 33 | y1 = scipy.signal.lfilter(lpf, [1.0], x) 34 | 35 | plt.figure() 36 | plt.title('Signal, filtered with FIR') 37 | plt.plot(y1) 38 | plt.xlabel('t') 39 | plt.ylabel('y(t)') 40 | 41 | # Filter signal, using initial conditions 42 | zi = scipy.signal.lfiltic(lpf, [1.0], [1.0], np.ones(len(lpf)-1)) 43 | y, zf = scipy.signal.lfilter(lpf, [1.0], x, zi=zi) 44 | plt.plot(y) 45 | 46 | # IIR LPF 47 | butterworth = scipy.signal.butter(order, cutoff, btype='lowpass') 48 | butterworth_freq, butterworth_response = scipy.signal.freqz(butterworth[0], butterworth[1]) 49 | 50 | plt.figure() 51 | plt.suptitle('IIR filter frequency response') 52 | plt.subplot(2,1,1) 53 | plt.plot(butterworth_freq, scipy.signal.abs(butterworth_response), marker='.', label='abs') 54 | plt.xlabel('f/f0') 55 | plt.ylabel('Abs') 56 | 57 | plt.subplot(2,1,2) 58 | plt.plot(butterworth_freq, np.unwrap(np.angle(butterworth_response)), marker='.', label='arg') 59 | plt.xlabel('f/f0') 60 | plt.ylabel('Angle') 61 | 62 | # Filter signal, no initial conditions 63 | y = scipy.signal.lfilter(butterworth[0], butterworth[1], x) 64 | 65 | plt.figure() 66 | plt.title('Signal, filtered with IIR filter') 67 | plt.plot(y) 68 | 69 | # Filter signal, using initial conditions 70 | zi = scipy.signal.lfilter_zi(butterworth[0], butterworth[1]) 71 | y, zf = scipy.signal.lfilter(butterworth[0], butterworth[1], x, zi=zi) 72 | plt.plot(y) 73 | 74 | plt.show() 75 | -------------------------------------------------------------------------------- /PairCorrelation/README: -------------------------------------------------------------------------------- 1 | Python code to compute the pair correlation function (also known as the radial 2 | distribution function, or RDF) for a distribution of particles. 3 | -------------------------------------------------------------------------------- /PairCorrelation/example_2D.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from utilities import * 4 | from paircorrelation import pairCorrelationFunction_2D 5 | 6 | # Particle setup 7 | domain_size = 20.0 8 | num_particles = 2000 9 | 10 | # Calculation setup 11 | dr = 0.1 12 | 13 | ### Random arrangement of particles ### 14 | particle_radius = 0.1 15 | rMax = domain_size / 4 16 | x = np.random.uniform(low=0, high=domain_size, size=num_particles) 17 | y = np.random.uniform(low=0, high=domain_size, size=num_particles) 18 | 19 | # Compute pair correlation 20 | g_r, r, reference_indices = pairCorrelationFunction_2D(x, y, domain_size, rMax, dr) 21 | 22 | # Visualize 23 | plt.figure() 24 | plt.plot(r, g_r, color='black') 25 | plt.xlabel('r') 26 | plt.ylabel('g(r)') 27 | plt.xlim( (0, rMax) ) 28 | plt.ylim( (0, 1.05 * g_r.max()) ) 29 | 30 | plot_adsorbed_circles(x, y, particle_radius, domain_size, reference_indices=reference_indices) 31 | 32 | ### Hexagonal circle packing ### 33 | particle_radius = 1.0 34 | domain_size = 50.0 35 | rMax = domain_size / 3 36 | 37 | x, y, domain_width, domain_height = generate_hex_circle_packing(particle_radius, domain_size) 38 | 39 | # Compute pair correlation 40 | g_r, r, reference_indices = pairCorrelationFunction_2D(x, y, domain_size, 41 | rMax, dr) 42 | 43 | # Visualize 44 | plt.figure() 45 | plt.plot(r, g_r, color='black') 46 | plt.xlabel('r') 47 | plt.ylabel('g(r)') 48 | plt.xlim( (0, rMax) ) 49 | plt.ylim( (0, 1.05 * g_r.max()) ) 50 | 51 | plot_adsorbed_circles(x, y, particle_radius, domain_size, reference_indices=reference_indices) 52 | 53 | plt.show() 54 | -------------------------------------------------------------------------------- /PairCorrelation/example_3D.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from utilities import * 4 | from paircorrelation import pairCorrelationFunction_3D 5 | 6 | # Particle setup 7 | domain_size = 20.0 8 | num_particles = 10000 9 | 10 | # Calculation setup 11 | dr = 0.1 12 | 13 | ### Random arrangement of particles ### 14 | particle_radius = 0.1 15 | rMax = domain_size / 4 16 | x = np.random.uniform(low=0, high=domain_size, size=num_particles) 17 | y = np.random.uniform(low=0, high=domain_size, size=num_particles) 18 | z = np.random.uniform(low=0, high=domain_size, size=num_particles) 19 | 20 | # Compute pair correlation 21 | g_r, r, reference_indices = pairCorrelationFunction_3D(x, y, z, domain_size, rMax, dr) 22 | 23 | # Visualize 24 | plt.figure() 25 | plt.plot(r, g_r, color='black') 26 | plt.xlabel('r') 27 | plt.ylabel('g(r)') 28 | plt.xlim( (0, rMax) ) 29 | plt.ylim( (0, 1.05 * g_r.max()) ) 30 | plt.show() 31 | -------------------------------------------------------------------------------- /PairCorrelation/paircorrelation.py: -------------------------------------------------------------------------------- 1 | def pairCorrelationFunction_2D(x, y, S, rMax, dr): 2 | """Compute the two-dimensional pair correlation function, also known 3 | as the radial distribution function, for a set of circular particles 4 | contained in a square region of a plane. This simple function finds 5 | reference particles such that a circle of radius rMax drawn around the 6 | particle will fit entirely within the square, eliminating the need to 7 | compensate for edge effects. If no such particles exist, an error is 8 | returned. Try a smaller rMax...or write some code to handle edge effects! ;) 9 | 10 | Arguments: 11 | x an array of x positions of centers of particles 12 | y an array of y positions of centers of particles 13 | S length of each side of the square region of the plane 14 | rMax outer diameter of largest annulus 15 | dr increment for increasing radius of annulus 16 | 17 | Returns a tuple: (g, radii, interior_indices) 18 | g(r) a numpy array containing the correlation function g(r) 19 | radii a numpy array containing the radii of the 20 | annuli used to compute g(r) 21 | reference_indices indices of reference particles 22 | """ 23 | from numpy import zeros, sqrt, where, pi, mean, arange, histogram 24 | # Number of particles in ring/area of ring/number of reference particles/number density 25 | # area of ring = pi*(r_outer**2 - r_inner**2) 26 | 27 | # Find particles which are close enough to the box center that a circle of radius 28 | # rMax will not cross any edge of the box 29 | bools1 = x > rMax 30 | bools2 = x < (S - rMax) 31 | bools3 = y > rMax 32 | bools4 = y < (S - rMax) 33 | interior_indices, = where(bools1 * bools2 * bools3 * bools4) 34 | num_interior_particles = len(interior_indices) 35 | 36 | if num_interior_particles < 1: 37 | raise RuntimeError ("No particles found for which a circle of radius rMax\ 38 | will lie entirely within a square of side length S. Decrease rMax\ 39 | or increase the size of the square.") 40 | 41 | edges = arange(0., rMax + 1.1 * dr, dr) 42 | num_increments = len(edges) - 1 43 | g = zeros([num_interior_particles, num_increments]) 44 | radii = zeros(num_increments) 45 | numberDensity = len(x) / S**2 46 | 47 | # Compute pairwise correlation for each interior particle 48 | for p in range(num_interior_particles): 49 | index = interior_indices[p] 50 | d = sqrt((x[index] - x)**2 + (y[index] - y)**2) 51 | d[index] = 2 * rMax 52 | 53 | (result, bins) = histogram(d, bins=edges, normed=False) 54 | g[p, :] = result/numberDensity 55 | 56 | # Average g(r) for all interior particles and compute radii 57 | g_average = zeros(num_increments) 58 | for i in range(num_increments): 59 | radii[i] = (edges[i] + edges[i+1]) / 2. 60 | rOuter = edges[i + 1] 61 | rInner = edges[i] 62 | g_average[i] = mean(g[:, i]) / (pi * (rOuter**2 - rInner**2)) 63 | 64 | return (g_average, radii, interior_indices) 65 | #### 66 | 67 | def pairCorrelationFunction_3D(x, y, z, S, rMax, dr): 68 | """Compute the three-dimensional pair correlation function for a set of 69 | spherical particles contained in a cube with side length S. This simple 70 | function finds reference particles such that a sphere of radius rMax drawn 71 | around the particle will fit entirely within the cube, eliminating the need 72 | to compensate for edge effects. If no such particles exist, an error is 73 | returned. Try a smaller rMax...or write some code to handle edge effects! ;) 74 | 75 | Arguments: 76 | x an array of x positions of centers of particles 77 | y an array of y positions of centers of particles 78 | z an array of z positions of centers of particles 79 | S length of each side of the cube in space 80 | rMax outer diameter of largest spherical shell 81 | dr increment for increasing radius of spherical shell 82 | 83 | Returns a tuple: (g, radii, interior_indices) 84 | g(r) a numpy array containing the correlation function g(r) 85 | radii a numpy array containing the radii of the 86 | spherical shells used to compute g(r) 87 | reference_indices indices of reference particles 88 | """ 89 | from numpy import zeros, sqrt, where, pi, mean, arange, histogram 90 | 91 | # Find particles which are close enough to the cube center that a sphere of radius 92 | # rMax will not cross any face of the cube 93 | bools1 = x > rMax 94 | bools2 = x < (S - rMax) 95 | bools3 = y > rMax 96 | bools4 = y < (S - rMax) 97 | bools5 = z > rMax 98 | bools6 = z < (S - rMax) 99 | 100 | interior_indices, = where(bools1 * bools2 * bools3 * bools4 * bools5 * bools6) 101 | num_interior_particles = len(interior_indices) 102 | 103 | if num_interior_particles < 1: 104 | raise RuntimeError ("No particles found for which a sphere of radius rMax\ 105 | will lie entirely within a cube of side length S. Decrease rMax\ 106 | or increase the size of the cube.") 107 | 108 | edges = arange(0., rMax + 1.1 * dr, dr) 109 | num_increments = len(edges) - 1 110 | g = zeros([num_interior_particles, num_increments]) 111 | radii = zeros(num_increments) 112 | numberDensity = len(x) / S**3 113 | 114 | # Compute pairwise correlation for each interior particle 115 | for p in range(num_interior_particles): 116 | index = interior_indices[p] 117 | d = sqrt((x[index] - x)**2 + (y[index] - y)**2 + (z[index] - z)**2) 118 | d[index] = 2 * rMax 119 | 120 | (result, bins) = histogram(d, bins=edges, normed=False) 121 | g[p,:] = result / numberDensity 122 | 123 | # Average g(r) for all interior particles and compute radii 124 | g_average = zeros(num_increments) 125 | for i in range(num_increments): 126 | radii[i] = (edges[i] + edges[i+1]) / 2. 127 | rOuter = edges[i + 1] 128 | rInner = edges[i] 129 | g_average[i] = mean(g[:, i]) / (4.0 / 3.0 * pi * (rOuter**3 - rInner**3)) 130 | 131 | return (g_average, radii, interior_indices) 132 | # Number of particles in shell/total number of particles/volume of shell/number density 133 | # shell volume = 4/3*pi(r_outer**3-r_inner**3) 134 | #### 135 | -------------------------------------------------------------------------------- /PairCorrelation/utilities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from numpy import * 3 | 4 | def generate_hex_circle_packing(a, width): 5 | """Generate a domain of a given width filled with hexagonally packed 6 | circles. The height will be determined so that the vertical 7 | boundary condition is periodic. 8 | 9 | Arguments: 10 | a particle radius 11 | width domain width, in terms of particle radius 12 | 13 | Returns: 14 | x_list list of x coordinates 15 | y_list list of y coordinates 16 | x_size width of domain (equal to argument width) 17 | y_size height of domain 18 | """ 19 | numParticles = 0 20 | 21 | x_list = [] 22 | y_list = [] 23 | y = a 24 | x = a 25 | rowNumber = 0 26 | # Create a row 27 | while y <= width*1.01: 28 | # Create circles in a row 29 | while x < width: 30 | x_list.append(x) 31 | x = x + 2*a 32 | y_list.append(y) 33 | numParticles = numParticles + 1 34 | y = y + a*sqrt(3.) 35 | rowNumber = rowNumber + 1 36 | if rowNumber%2 == 0: 37 | x = a 38 | else: 39 | x = 0 40 | x_size = width 41 | y_size = rowNumber*a*sqrt(3) 42 | 43 | return array(x_list), array(y_list), x_size, y_size 44 | 45 | def plot_adsorbed_circles(adsorbed_x, adsorbed_y, radius, width, reference_indices=[]): 46 | import numpy as np 47 | import matplotlib.pyplot as plt 48 | from matplotlib.patches import Circle 49 | 50 | # Plot each run 51 | fig = plt.figure() 52 | ax = fig.add_subplot(111) 53 | for p in range(len(adsorbed_x)): 54 | if len(np.where(reference_indices == p)[0]) > 0: 55 | ax.add_patch(Circle((adsorbed_x[p], adsorbed_y[p]), radius, 56 | edgecolor='black', facecolor='black')) 57 | else: 58 | ax.add_patch(Circle((adsorbed_x[p], adsorbed_y[p]), radius, 59 | edgecolor='black', facecolor='white')) 60 | 61 | ax.set_aspect(1.0) 62 | plt.axhline(y=0, color='k') 63 | plt.axhline(y=width, color='k') 64 | plt.axvline(x=0, color='k') 65 | plt.axvline(x=width, color='k') 66 | plt.axis([-0.1*width, width*1.1, -0.1*width, width*1.1]) 67 | plt.xlabel("non-dimensional x") 68 | plt.ylabel("non-dimensional y") 69 | 70 | return ax 71 | 72 | -------------------------------------------------------------------------------- /Plotting/matplotlib/AxesGrid_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import matplotlib.pyplot as plt 4 | from mpl_toolkits.axes_grid.axislines import Subplot 5 | 6 | fig1 = plt.figure(1, (3,3), facecolor='white') 7 | 8 | ax1 = Subplot(fig1, 111) 9 | fig1.add_subplot(ax1) 10 | 11 | ax1.axis["right"].set_visible(False) 12 | ax1.axis["top"].set_visible(False) 13 | 14 | plt.show() 15 | 16 | -------------------------------------------------------------------------------- /Plotting/matplotlib/plot_without_axes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import matplotlib.pyplot as plt 4 | from matplotlib.lines import Line2D 5 | from matplotlib.text import Text 6 | 7 | import numpy 8 | 9 | fig1 = plt.figure(facecolor='white') 10 | ax1 = plt.axes(frameon=False) 11 | 12 | #ax1.set_frame_on(False) # Alternate way to turn frame off 13 | 14 | ax1.get_xaxis().tick_bottom() # Turn off ticks at top of plot 15 | 16 | #ax1.axes.get_xaxis().set_visible(False) 17 | ax1.axes.get_yaxis().set_visible(False) # Hide y axis 18 | 19 | # Add a plot 20 | y_offset = 2.0 21 | x = numpy.arange(-5.0, 5.0, 0.1) 22 | for i in range(3): 23 | ax1.plot(x, numpy.sin((i + 1) * x) + i * y_offset, label=str(i+1)) 24 | 25 | plt.legend(loc='lower right') 26 | 27 | # Draw the x axis line 28 | # Note that this must be done after plotting, to get the correct 29 | # view interval 30 | xmin, xmax = ax1.get_xaxis().get_view_interval() 31 | ymin, ymax = ax1.get_yaxis().get_view_interval() 32 | ax1.add_artist(Line2D((xmin, xmax), (ymin, ymin), color='black', linewidth=2)) 33 | 34 | plt.show() 35 | 36 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Examples from my web site at http://www.shocksolution.com 2 | -------------------------------------------------------------------------------- /Visualization/vtktools.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | class VTK_XML_Serial_Unstructured: 3 | """ 4 | USAGE: 5 | vtk_writer = VTK_XML_Serial_Unstructured() 6 | vtk_writer.snapshot("filename.vtu", x, y, z, optional arguments...) 7 | vtk_writer.writePVD("filename.pvd") 8 | """ 9 | def __init__(self): 10 | self.fileNames = [] 11 | 12 | def coords_to_string(self, x,y,z): 13 | string = str() 14 | for i in range(len(x)): 15 | string = string + repr(x[i]) + ' ' + repr(y[i]) \ 16 | + ' ' + repr(z[i]) + ' ' 17 | return string 18 | 19 | def array_to_string(self, a): 20 | string = str() 21 | for i in range(len(a)): 22 | string = string + repr(a[i]) + ' ' 23 | return string 24 | 25 | def snapshot(self, fileName, x,y,z, x_jump=[], y_jump=[], z_jump=[], x_force=[], \ 26 | y_force=[], z_force=[], radii=[], colors=[]): 27 | """ 28 | ARGUMENTS: 29 | fileName file name and/or path/filename 30 | x array of x coordinates of particle centers 31 | y array of y coordinates of particle centers 32 | z array of z coordinates of particle centers 33 | x_jump optional array of x components of particle jump vectors 34 | y_jump optional array of y components of particle jump vectors 35 | z_jump optional array of z components of particle jump vectors 36 | x_force optional array of x components of force vectors 37 | y_force optional array of y components of force vectors 38 | z_force optional array of z components of force vectors 39 | radii optional array of particle radii 40 | colors optional array of scalars to use to set particle colors 41 | The exact colors will depend on the color map you set up in Paraview. 42 | """ 43 | import xml.dom.minidom 44 | #import xml.dom.ext # python 2.5 and later 45 | 46 | # Document and root element 47 | doc = xml.dom.minidom.Document() 48 | root_element = doc.createElementNS("VTK", "VTKFile") 49 | root_element.setAttribute("type", "UnstructuredGrid") 50 | root_element.setAttribute("version", "0.1") 51 | root_element.setAttribute("byte_order", "LittleEndian") 52 | doc.appendChild(root_element) 53 | 54 | # Unstructured grid element 55 | unstructuredGrid = doc.createElementNS("VTK", "UnstructuredGrid") 56 | root_element.appendChild(unstructuredGrid) 57 | 58 | # Piece 0 (only one) 59 | piece = doc.createElementNS("VTK", "Piece") 60 | piece.setAttribute("NumberOfPoints", str(len(x))) 61 | piece.setAttribute("NumberOfCells", "0") 62 | unstructuredGrid.appendChild(piece) 63 | 64 | ### Points #### 65 | points = doc.createElementNS("VTK", "Points") 66 | piece.appendChild(points) 67 | 68 | # Point location data 69 | point_coords = doc.createElementNS("VTK", "DataArray") 70 | point_coords.setAttribute("type", "Float32") 71 | point_coords.setAttribute("format", "ascii") 72 | point_coords.setAttribute("NumberOfComponents", "3") 73 | points.appendChild(point_coords) 74 | 75 | string = self.coords_to_string(x, y, z) 76 | point_coords_data = doc.createTextNode(string) 77 | point_coords.appendChild(point_coords_data) 78 | 79 | #### Cells #### 80 | cells = doc.createElementNS("VTK", "Cells") 81 | piece.appendChild(cells) 82 | 83 | # Cell locations 84 | cell_connectivity = doc.createElementNS("VTK", "DataArray") 85 | cell_connectivity.setAttribute("type", "Int32") 86 | cell_connectivity.setAttribute("Name", "connectivity") 87 | cell_connectivity.setAttribute("format", "ascii") 88 | cells.appendChild(cell_connectivity) 89 | 90 | # Cell location data 91 | connectivity = doc.createTextNode("0") 92 | cell_connectivity.appendChild(connectivity) 93 | 94 | cell_offsets = doc.createElementNS("VTK", "DataArray") 95 | cell_offsets.setAttribute("type", "Int32") 96 | cell_offsets.setAttribute("Name", "offsets") 97 | cell_offsets.setAttribute("format", "ascii") 98 | cells.appendChild(cell_offsets) 99 | offsets = doc.createTextNode("0") 100 | cell_offsets.appendChild(offsets) 101 | 102 | cell_types = doc.createElementNS("VTK", "DataArray") 103 | cell_types.setAttribute("type", "UInt8") 104 | cell_types.setAttribute("Name", "types") 105 | cell_types.setAttribute("format", "ascii") 106 | cells.appendChild(cell_types) 107 | types = doc.createTextNode("1") 108 | cell_types.appendChild(types) 109 | 110 | #### Data at Points #### 111 | point_data = doc.createElementNS("VTK", "PointData") 112 | piece.appendChild(point_data) 113 | 114 | # Points 115 | point_coords_2 = doc.createElementNS("VTK", "DataArray") 116 | point_coords_2.setAttribute("Name", "Points") 117 | point_coords_2.setAttribute("NumberOfComponents", "3") 118 | point_coords_2.setAttribute("type", "Float32") 119 | point_coords_2.setAttribute("format", "ascii") 120 | point_data.appendChild(point_coords_2) 121 | 122 | string = self.coords_to_string(x, y, z) 123 | point_coords_2_Data = doc.createTextNode(string) 124 | point_coords_2.appendChild(point_coords_2_Data) 125 | 126 | # Particle jump vectors 127 | if len(x_jump) > 0: 128 | jumps = doc.createElementNS("VTK", "DataArray") 129 | jumps.setAttribute("Name", "jumps") 130 | jumps.setAttribute("NumberOfComponents", "3") 131 | jumps.setAttribute("type", "Float32") 132 | jumps.setAttribute("format", "ascii") 133 | point_data.appendChild(jumps) 134 | 135 | string = self.coords_to_string(x_jump, y_jump, z_jump) 136 | jumpData = doc.createTextNode(string) 137 | jumps.appendChild(jumpData) 138 | 139 | # Force vectors 140 | if len(x_force) > 0: 141 | forces = doc.createElementNS("VTK", "DataArray") 142 | forces.setAttribute("Name", "forces") 143 | forces.setAttribute("NumberOfComponents", "3") 144 | forces.setAttribute("type", "Float32") 145 | forces.setAttribute("format", "ascii") 146 | point_data.appendChild(forces) 147 | 148 | string = self.coords_to_string(x_force, y_force, z_force) 149 | forceData = doc.createTextNode(string) 150 | forces.appendChild(forceData) 151 | 152 | # Particle radii 153 | if len(radii) > 0: 154 | radiiNode = doc.createElementNS("VTK", "DataArray") 155 | radiiNode.setAttribute("Name", "radii") 156 | radiiNode.setAttribute("type", "Float32") 157 | radiiNode.setAttribute("format", "ascii") 158 | point_data.appendChild(radiiNode) 159 | 160 | string = self.array_to_string(radii) 161 | radiiData = doc.createTextNode(string) 162 | radiiNode.appendChild(radiiData) 163 | 164 | if len(colors) > 0: 165 | # Particle colors 166 | colorNode= doc.createElementNS("VTK", "DataArray") 167 | colorNode.setAttribute("Name", "colors") 168 | colorNode.setAttribute("type", "Float32") 169 | colorNode.setAttribute("format", "ascii") 170 | point_data.appendChild(colorNode) 171 | 172 | string = self.array_to_string(colors) 173 | color_Data = doc.createTextNode(string) 174 | colorNode.appendChild(color_Data) 175 | 176 | #### Cell data (dummy) #### 177 | cell_data = doc.createElementNS("VTK", "CellData") 178 | piece.appendChild(cell_data) 179 | 180 | # Write to file and exit 181 | outFile = open(fileName, 'w') 182 | # xml.dom.ext.PrettyPrint(doc, file) 183 | doc.writexml(outFile, newl='\n') 184 | outFile.close() 185 | self.fileNames.append(fileName) 186 | 187 | def writePVD(self, fileName): 188 | outFile = open(fileName, 'w') 189 | import xml.dom.minidom 190 | 191 | pvd = xml.dom.minidom.Document() 192 | pvd_root = pvd.createElementNS("VTK", "VTKFile") 193 | pvd_root.setAttribute("type", "Collection") 194 | pvd_root.setAttribute("version", "0.1") 195 | pvd_root.setAttribute("byte_order", "LittleEndian") 196 | pvd.appendChild(pvd_root) 197 | 198 | collection = pvd.createElementNS("VTK", "Collection") 199 | pvd_root.appendChild(collection) 200 | 201 | for i in range(len(self.fileNames)): 202 | dataSet = pvd.createElementNS("VTK", "DataSet") 203 | dataSet.setAttribute("timestep", str(i)) 204 | dataSet.setAttribute("group", "") 205 | dataSet.setAttribute("part", "0") 206 | dataSet.setAttribute("file", str(self.fileNames[i])) 207 | collection.appendChild(dataSet) 208 | 209 | outFile = open(fileName, 'w') 210 | pvd.writexml(outFile, newl='\n') 211 | outFile.close() 212 | -------------------------------------------------------------------------------- /XML/write_wxGlade_XML.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import xml.etree.ElementTree as etree 3 | from xml.dom import minidom 4 | 5 | output_file = "test.wgt" # file extension for wxGlade template file 6 | 7 | # Attribute definitions 8 | wxStaticText_attributes = {"class":"wxStaticText", "name":"label_1", 9 | "base":"EditStaticText"} 10 | wxCheckBox_attributes = {"class":"wxCheckBox", "name":"checkbox_1", 11 | "base":"EditCheckBox"} 12 | 13 | # Boilerplate for wxGlade templates 14 | root = etree.Element("application", attrib={"path":"/home/cfinch/Projects/wx/wx/test", 15 | "name":"", "class":"", "option":"0", "language":"C++", "top_window":"grid_sizer_1", 16 | "encoding":"UTF-8", "use_gettext":"0", "overwrite":"0", "use_new_namespace":"1", 17 | "for_version":"2.8", "is_template":"1"}) 18 | 19 | templatedata = etree.SubElement(root, "templatedata") 20 | author = etree.SubElement(templatedata, "author") 21 | author.text = "Craig Finch" 22 | description = etree.SubElement(templatedata, "description") 23 | description.text = "testing" 24 | instructions = etree.SubElement(templatedata, "instructions") 25 | instructions.text = "testing" 26 | 27 | # Dialog 28 | dialog = etree.SubElement(root, "object", attrib={"class":"MyDialog", "name":"dialog", 29 | "base":"EditDialog"}) 30 | dialog_style = etree.SubElement(dialog, "style") 31 | dialog_style.text = "wxDEFAULT_DIALOG_STYLE" 32 | dialog_title = etree.SubElement(dialog, "title") 33 | dialog_title.text = "Dialog" 34 | dialog_size = etree.SubElement(dialog, "size") 35 | dialog_size.text = "200, 200d" 36 | 37 | # Add wxGridSizer to Dialog 38 | sizer = etree.SubElement(dialog, "object", attrib={"class":"wxGridSizer", "name":"grid_sizer_1", 39 | "base":"EditGridSizer"}) 40 | hgap = etree.SubElement(sizer, "hgap") 41 | hgap.text = "0" 42 | rows = etree.SubElement(sizer, "rows") 43 | rows.text = "6" 44 | cols = etree.SubElement(sizer, "cols") 45 | cols.text = "2" 46 | vgap = etree.SubElement(sizer, "vgap") 47 | vgap.text = "0" 48 | 49 | # Add static text to sizer 50 | sizeritem = etree.SubElement(sizer, "object", attrib={"class":"sizeritem"}) 51 | border = etree.SubElement(sizeritem, "border") 52 | border.text = "0" 53 | option = etree.SubElement(sizeritem, "option") 54 | option.text = "0" 55 | 56 | control = etree.SubElement(sizeritem, "object", attrib=wxStaticText_attributes) 57 | att = etree.SubElement(control, "attribute") 58 | att.text = "1" 59 | label = etree.SubElement(control, "label") 60 | label.text = "Label Text" 61 | 62 | # Add check box control to sizer 63 | sizeritem = etree.SubElement(sizer, "object", attrib={"class":"sizeritem"}) 64 | 65 | border = etree.SubElement(sizeritem, "border") 66 | border.text = "0" 67 | option = etree.SubElement(sizeritem, "option") 68 | option.text = "0" 69 | 70 | control = etree.SubElement(sizeritem, "object", attrib=wxCheckBox_attributes) 71 | att = etree.SubElement(control, "attribute") 72 | att.text = "1" 73 | label = etree.SubElement(control, "label") 74 | label.text = "Control Text" 75 | 76 | # Pretty-print 77 | reparsed = minidom.parseString(etree.tostring(root)) 78 | print(reparsed.toprettyxml()) 79 | 80 | # Save to file 81 | f = open(output_file, 'w') 82 | f.write(etree.tostring(root, encoding='utf-8').decode('utf-8')) 83 | f.close() 84 | 85 | -------------------------------------------------------------------------------- /f2py/simple_example/Makefile: -------------------------------------------------------------------------------- 1 | simple_example.so : simple_f2py_example.f90 2 | f2py2.6 -c -m simple_example simple_f2py_example.f90 3 | 4 | clean: 5 | rm simple_example.so 6 | -------------------------------------------------------------------------------- /f2py/simple_example/simple_f2py_example.f90: -------------------------------------------------------------------------------- 1 | ! Build with f2py2.6 -c -m simple_example simple_f2py_example.f90 2 | ! May need to change f2py2.6 to reflect the version of Python you 3 | ! are using (this was built with Python 2.6) 4 | 5 | module test 6 | 7 | contains 8 | 9 | subroutine foo (a) 10 | implicit none 11 | integer, intent(in) :: a 12 | 13 | print*, "Hello from Fortran!" 14 | print*, "a=",a 15 | end subroutine foo 16 | 17 | function bar (len_a, a) 18 | implicit none 19 | integer, intent(in) :: len_a 20 | real, dimension(len_a), intent(in) :: a 21 | 22 | real, dimension(len_a) :: bar 23 | !f2py depend(len_a) a, bar 24 | 25 | integer :: i 26 | real, dimension(len_a) :: b 27 | 28 | do i=1,len_a 29 | b(i) = 2.0*a(i) 30 | end do 31 | 32 | bar = b 33 | end function bar 34 | 35 | subroutine sub (a, len_a, a_out) 36 | implicit none 37 | 38 | real, dimension(len_a), intent(in) :: a 39 | integer, intent(in) :: len_a 40 | real, dimension(len_a), intent(out) :: a_out 41 | 42 | integer :: i 43 | 44 | do i=1,len_a 45 | a_out(i) = 2.0*a(i) 46 | end do 47 | 48 | end subroutine sub 49 | 50 | end module test 51 | -------------------------------------------------------------------------------- /f2py/simple_example/test_f2py_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import simple_example 4 | import numpy as np 5 | 6 | a = np.arange(0.0, 10.0, 1.0) 7 | len_a = len(a) 8 | 9 | print("foo:") 10 | simple_example.test.foo(len_a) 11 | 12 | print("bar:") 13 | a_out = simple_example.test.bar(len_a, a) 14 | print a_out 15 | 16 | print("sub:") 17 | a_out = simple_example.test.sub(a, len_a) 18 | print(a_out) 19 | -------------------------------------------------------------------------------- /scipy/interpolation.py: -------------------------------------------------------------------------------- 1 | from scipy.interpolate import interp1d, UnivariateSpline 2 | from scipy.stats import norm 3 | from numpy import arange 4 | from numpy.random import uniform 5 | import matplotlib.pyplot as plt 6 | from time import time 7 | 8 | deltax = 0.1 9 | xmin = -5.0 10 | xmax = 5.0 11 | 12 | # Set up samples 13 | x_samples = arange(xmin, xmax, deltax) 14 | pdf_samples = norm.pdf(x_samples) 15 | fig = plt.plot(x_samples, pdf_samples, 'ro', label='Sampled') 16 | 17 | # Interpolate on a finer grid 18 | pdf_interp = interp1d(x_samples, pdf_samples, kind='linear') 19 | x_interp = arange(xmin+deltax, xmax-deltax, 0.001) 20 | plt.plot(x_interp, pdf_interp(x_interp), 'b-', label='Interpolated') 21 | 22 | # Do the same thing with UnivariateSpline 23 | u = UnivariateSpline(x_samples, pdf_samples, k=1, s=0.0) 24 | plt.plot(x_interp, u(x_interp), 'k-', label='Spline') 25 | 26 | plt.xlabel('x') 27 | plt.ylabel('pdf') 28 | plt.legend() 29 | plt.show() 30 | 31 | # Time tests 32 | start_time = time() 33 | for i in range(100000): 34 | pdf_interp(uniform(xmin+deltax, xmax-deltax)) 35 | print("interp1d run time: {}".format(time() - start_time)) 36 | 37 | start_time = time() 38 | for i in range(100000): 39 | u(uniform(xmin+deltax, xmax-deltax)) 40 | print("UnivariateSpline run time: {}".format(time() - start_time)) 41 | 42 | x_fine = arange(xmin + deltax, xmax - deltax - 0.001, 1e-6) 43 | 44 | start_time = time() 45 | pdf_interp(x_fine) 46 | print("interp1d run time: {}".format(time() - start_time)) 47 | 48 | start_time = time() 49 | u(x_fine) 50 | print("UnivariateSpline run time: {}".format(time() - start_time)) --------------------------------------------------------------------------------