set up coefficient matrix and rhs vector using pointer for a 2d unsteady heat conduction equation. implicit euler for time and central differencing for space. use a jacobi solver. in javascript

To set up the coefficient matrix and RHS vector using pointer for a 2D unsteady heat conduction equation, we will use implicit euler for time and central differencing for space. We will use a Jacobi solver.

Assuming a 2D grid, the equation for heat conduction is:

equation

where k is thermal conductivity, T is the temperature, and delta x and delta y are the spatial steps in the x and y directions respectively.

To discretize the equation we will use central differences. The implicit scheme allows us to write:

equation

where T^{n+1} is the temperature at time step n+1, T^n is the temperature at time step n and r = (delta t)/(k*(delta x)^2).

Rearranging the equation, we obtain:

equation

We can then set up a system of linear equations in the form Ax = b. To do this, we will set up a coefficient matrix, A, and a RHS vector, b.

We initialize A as a sparse matrix and b as a vector of zeros. We then loop over all internal points in the grid and set the corresponding entries in A and b.

index.tsx
function solveHeatConductionEquation(nx, ny, nt, dt, dx, dy, k, T0, Tleft, Tright, Ttop, Tbottom) {
  // Initialize A as a sparse matrix and b as a vector of zeros
  const A = new SparseMatrix(nx*ny, nx*ny);
  const b = new Vector(nx*ny);

  const r = (dt/(k*dx*dx));
  
  // Loop over all internal points in the grid and set the corresponding entries in A and b
  for (let i = 1; i < nx-1; i++) {
    for (let j = 1; j < ny-1; j++) {
      const index = i*ny + j;

      // Set the diagonal entry of A
      A.set(index, index, 1 + 2*r);

      // Set the off-diagonal entries of A
      A.set(index, index-1, -r);
      A.set(index, index+1, -r);
      A.set(index, index-ny, -r);
      A.set(index, index+ny, -r);

      // Set the RHS entry
      b.set(index, T0[index] + r*(Tleft[i]+Tright[i]+Ttop[j]+Tbottom[j]) + (1-2*r)*T[index]);
    }
  }

  // Solve the linear system using Jacobi solver
  const SOL = jacobiSolver(A, b);
  
  // Return the solution as a 2D array
  const T = new Array(nx);
  for (let i = 0; i < nx; i++) {
    T[i] = new Array(ny);
    for (let j = 0; j < ny; j++) {
      const index = i*ny + j;
      T[i][j] = SOL.get(index);
    }
  }
  
  return T;
}
1185 chars
42 lines

Here, "SparseMatrix" and "Vector" are classes that implement a sparse matrix and a vector respectively. "jacobiSolver" is a function that implements the Jacobi method to solve the linear system.

Note that the above code assumes that the boundary conditions are given by Tleft, Tright, Ttop, Tbottom. T0 is the initial temperature distribution. The function returns the solution as a 2D array.

gistlibby LogSnag