function fem2d_project ( sample_prefix, fem_prefix )

%*****************************************************************************80
%
%% MAIN is the main program for FEM2D_PROJECT.
%
%  Discussion:
%
%    FEM2D_PROJECT reads files defining a sampling of a (scalar or vector)
%    function of 2 arguments, and a list of nodes and triangular elements
%    to use for a finite element representation of the data.
%
%    It computes a set of finite element coefficients to be associated with
%    the given finite element mesh, and writes that information to a file
%    so that an FEM representation is formed by the node, element and value
%    files.
%
%  Usage:
%
%    fem2d_project ( 'sample_prefix', 'fem_prefix' )
%
%    where 'sample_prefix' is the common prefix for the SAMPLE files:
%
%    * sample_prefix_nodes.txt,     the node coordinates where samples were taken;
%    * sample_prefix_elements.txt,  the nodes that make up each element;
%    * sample_prefix_values.txt,    the sample values.
%
%    and 'fem_prefix' is the common prefix for the FEM files:
%
%    * fem_prefix_nodes.txt,    the node coordinates;
%    * fem_prefix_elements.txt, the nodes that make up each element;
%    * fem_prefix_values.txt,   the values defined at each node,
%                               (computed by this program).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string SAMPLE_PREFIX, the common prefix for sample files.
%
%    Input, string FEM_PREFIX, the common prefix for FEM files.
%
  timestamp ( );

  fprintf ( '\n' );
  fprintf ( 'FEM2D_PROJECT\n' );
  fprintf ( '  MATLAB version.\n' );
  fprintf ( '\n' );
  fprintf ( '  Read files defining a sampling of a function of 2 arguments.\n' );
  fprintf ( '  Read files defining a finite element mesh.\n' );
  fprintf ( '  Project the sample data onto the mesh, and\n' );
  fprintf ( '  write a file of FEM coefficient values.\n' );
%
%  Get the number of command line arguments.
%
  if ( nargin < 1 )

    fprintf ( '\n' );
    sample_prefix = input ( 'Enter the sample file prefix:  ' );

  else

  end

  if ( nargin < 2 )

    fprintf ( '\n' );
    fem_prefix = input ( 'Enter the FEM file prefix:  ' );

  else

  end
%
%  Create the filenames.
%
  sample_node_filename    = strcat ( sample_prefix, '_nodes.txt' );
  sample_element_filename = strcat ( sample_prefix, '_elements.txt' );
  sample_value_filename   = strcat ( sample_prefix, '_values.txt' );

  fem_node_filename       = strcat ( fem_prefix, '_nodes.txt' );
  fem_element_filename    = strcat ( fem_prefix, '_elements.txt' );
  fem_value_filename      = strcat ( fem_prefix, '_values.txt' );
%
%  Read the SAMPLE NODE, ELEMENT and VALUE data.
%
  sample_node_xy = load ( sample_node_filename );
  sample_node_xy = sample_node_xy';
  [sample_node_dim, sample_node_num ] = size ( sample_node_xy );

  fprintf ( '\n' );
  fprintf ( '  Sample node spatial dimension is %d\n', sample_node_dim );
  fprintf ( '  Sample node number is            %d\n', sample_node_num );

  if ( sample_node_dim ~= 2 )
    fprintf ( '\n' );
    fprintf ( 'FEM2D_PROJECT - Fatal error!\n' );
    fprintf ( '  Spatial dimension of the sample nodes is not 2.\n' );
    return
  end

  sample_element_node = load ( sample_element_filename );
  sample_element_node = sample_element_node';
  [ sample_element_order, sample_element_num ] = size ( sample_element_node );

  fprintf ( '\n' );
  fprintf ( '  Sample element order is  %d\n', sample_element_order );
  fprintf ( '  Sample element number is %d\n', sample_element_num );

  if ( sample_element_order ~= 3 )
    fprintf ( '\n' );
    fprintf ( 'FEM2D_PROJECT - Fatal error!\n' );
    fprintf ( '  The sample elements must be of order 3.\n' );
    return
  end

  sample_value = load ( sample_value_filename );
  sample_value = sample_value';
  [ sample_value_dim, sample_value_num ] = size ( sample_value );

  fprintf ( '\n' );
  fprintf ( '  Sample value dimension is        %d\n', sample_value_dim );
  fprintf ( '  Sample value number is           %d\n', sample_value_num );

  if ( sample_value_num ~= sample_node_num )
    fprintf ( '\n' );
    fprintf ( 'FEM2D_PROJECT - Fatal error!\n' );
    fprintf ( '  Number of sample nodes and values are not equal.\n' );
    return
  end

  sample_value_min = min ( sample_value, [], 2 );
  sample_value_max = max ( sample_value, [], 2 );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     Index      SAMPLE Min      SAMPLE Max\n' );
  fprintf ( 1, '\n' );
  for i = 1 : sample_value_dim
    fprintf ( 1, '  %8d  %14f  %14f\n', i, sample_value_min(i), sample_value_max(i) );
  end
%
%  Create the sample element neighbor array.
%
  sample_element_neighbor = triangulation_order3_neighbor_triangles ( ...
    sample_element_num, sample_element_node );

  fprintf ( '\n' );
  fprintf ( '  The element neighbor array has been computed.\n' );
%
%  Read the FEM NODE and ELEMENT data.
%
  fem_node_xy = load ( fem_node_filename );
  fem_node_xy = fem_node_xy';
  [ fem_node_dim, fem_node_num ] = size ( fem_node_xy );

  fprintf ( '\n' );
  fprintf ( '  The FEM node dimension is        %d\n', fem_node_dim );
  fprintf ( '  The FEM node number is           %d\n', fem_node_num );

  if ( fem_node_dim ~= 2 )
    fprintf ( '\n' );
    fprintf ( 'FEM2D_PROJECT - Fatal error!\n' );
    fprintf ( '  Spatial dimension of the nodes is not 2.\n' );
    return
  end

  fem_element_node = load ( fem_element_filename );
  fem_element_node = fem_element_node';
  [ fem_element_order, fem_element_num ] = size ( fem_element_node );

  fprintf ( '  The FEM element order is         %d\n', fem_element_order );
  fprintf ( '  The FEM element number is        %d\n', fem_element_num );

  if ( fem_element_order ~= 3 )
    fprintf ( '\n' );
    fprintf ( 'FEM2D_PROJECT - Fatal error!\n' );
    fprintf ( '  The FEM elements must be of order 3.\n' );
    return
  end
%
%  Compute the FEM values.
%
  fem_value_dim = sample_value_dim;
  fem_value_num = fem_node_num;

  fem_value = fem2d_transfer ( sample_element_order, ...
    sample_element_num, sample_value_dim, ...
    sample_node_xy, sample_element_node, sample_element_neighbor, sample_value, ...
    fem_node_num, fem_element_num, fem_value_dim, fem_node_xy, fem_element_node );
%
%  Print Min, Max.
%
  fem_value_min = min ( fem_value, [], 2 );
  fem_value_max = max ( fem_value, [], 2 );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     Index         FEM Min         FEM Max\n' );
  fprintf ( 1, '\n' );
  for i = 1 : fem_value_dim
    fprintf ( 1, '  %8d  %14f  %14f\n', i, fem_value_min(i), fem_value_max(i) );
  end
%
%  Write the FEM values.
%
  r8mat_write ( fem_value_filename, fem_value_dim, fem_value_num, fem_value );

  fprintf ( '\n' );
  fprintf ( '  FEM value data written to "%s".\n',  fem_value_filename );
%
%  Terminate.
%
  fprintf ( '\n' );
  fprintf ( 'FEM2D_PROJECT\n' );
  fprintf ( '  Normal end of execution.\n' );

  fprintf ( '\n' );
  timestamp ( );

  return
end
function [ phi, dphidx, dphidy ] = basis_mn_t3 ( t, n, p )

%*****************************************************************************80
%
%% BASIS_MN_T3: all bases functions at N points for a T3 element.
%
%  Discussion:
%
%    The routine is given the coordinates of the vertices of a triangle.
%    It works directly with these coordinates, and does not refer to a
%    reference element.
%
%    The sides of the triangle DO NOT have to lie along a coordinate
%    axis.
%
%    The routine evaluates the basis functions associated with each vertex,
%    and their derivatives with respect to X and Y.
%
%  Physical Element T3:
%
%            3
%           / \
%          /   \
%         /     \
%        /       \
%       1---------2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real T(2,3), the vertices of the triangle.  It is common to list
%    these points in counter clockwise order.
%
%    Input, integer N, the number of evaluation points.
%
%    Input, real P(2,N), the coordinates of the evaluation points.
%
%    Output, real PHI(3,N), the basis functions at the evaluation points.
%
%    Output, real DPHIDX(3,N), DPHIDY(3,N), the basis derivatives
%    at the evaluation points.
%
%  Local parameters:
%
%    Local, real AREA, is (twice) the area of the triangle.
%
  area = t(1,1) * ( t(2,2) - t(2,3) ) ...
       + t(1,2) * ( t(2,3) - t(2,1) ) ...
       + t(1,3) * ( t(2,1) - t(2,2) );

  phi(1,1:n) =     (  ( t(1,3) - t(1,2) ) * ( p(2,1:n) - t(2,2) )     ...
                    - ( t(2,3) - t(2,2) ) * ( p(1,1:n) - t(1,2) ) );
  dphidx(1,1:n) =   - ( t(2,3) - t(2,2) );
  dphidy(1,1:n) =     ( t(1,3) - t(1,2) );

  phi(2,1:n) =     (  ( t(1,1) - t(1,3) ) * ( p(2,1:n) - t(2,3) )     ...
                    - ( t(2,1) - t(2,3) ) * ( p(1,1:n) - t(1,3) ) );
  dphidx(2,1:n) =   - ( t(2,1) - t(2,3) );
  dphidy(2,1:n) =     ( t(1,1) - t(1,3) );

  phi(3,1:n) =     (  ( t(1,2) - t(1,1) ) * ( p(2,1:n) - t(2,1) )     ...
                    - ( t(2,2) - t(2,1) ) * ( p(1,1:n) - t(1,1) ) );
  dphidx(3,1:n) =   - ( t(2,2) - t(2,1) );
  dphidy(3,1:n) =     ( t(1,2) - t(1,1) );
%
%  Normalize.
%
  phi(1:3,1:n)    = phi(1:3,1:n) / area;
  dphidx(1:3,1:n) = dphidx(1:3,1:n) / area;
  dphidy(1:3,1:n) = dphidy(1:3,1:n) / area;

  return
end
function [ phi, dphidx, dphidy ] = basis_mn_t6 ( t, n, p )

%*****************************************************************************80
%
%% BASIS_MN_T6: all bases for N points in a T6 element.
%
%  Discussion:
%
%    The routine is given the coordinates of the vertices and midside
%    nodes of a triangle.  It works directly with these coordinates, and does
%    not refer to a reference element.
%
%    This routine requires that the midside nodes be "in line"
%    with the vertices, that is, that the sides of the triangle be
%    straight.  However, the midside nodes do not actually have to
%    be halfway along the side of the triangle.
%
%  Physical element T6:
%
%    This picture indicates the assumed ordering of the six nodes
%    of the triangle.
%
%             3
%            / \
%           /   \
%          6     5
%         /       \
%        /         \
%       1-----4-----2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real T(2,6), the nodal oordinates of the element.
%    It is common to list these points in counter clockwise order.
%
%    Input, real P(2,N), the evaluation points.
%
%    Output, real PHI(6,N), the basis functions at the evaluation points.
%
%    Output, real DPHIDX(6,N), DPHIDY(6,N), the basis derivatives at the
%    evaluation points.
%
%  Local Parameters:
%
%    Local, real AREA, is (twice) the area of the triangle.
%

%
%  Basis function 1: PHI(X,Y) = G(3,2) * H(6,4) / normalization.
%
  gx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,3)   - t(2,2) ) ...
          - ( t(1,3)   - t(1,2) ) * ( p(2,1:n) - t(2,2) );

  gn(1:n) = ( t(1,1) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...
          - ( t(1,3) - t(1,2) ) * ( t(2,1) - t(2,2) );

  hx(1:n) = ( p(1,1:n) - t(1,4) ) * ( t(2,6)   - t(2,4) ) ...
          - ( t(1,6)   - t(1,4) ) * ( p(2,1:n) - t(2,4) );

  hn(1:n) = ( t(1,1) - t(1,4) ) * ( t(2,6) - t(2,4) ) ...
          - ( t(1,6) - t(1,4) ) * ( t(2,1) - t(2,4) );

  phi(1,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );

  dphidx(1,1:n) =  ( ( t(2,3) - t(2,2) ) * hx(1:n) ...
                    + gx(1:n) * ( t(2,6) - t(2,4) ) ) ...
                  ./ ( gn(1:n) .* hn(1:n) );

  dphidy(1,1:n) = -( ( t(1,3) - t(1,2) ) * hx(1:n) ...
                   + gx * ( t(1,6) - t(1,4) ) ) ...
                  ./ ( gn(1:n) .* hn(1:n) );
%
%  Basis function 2: PHI(X,Y) = G(3,1) * H(4,5) / normalization.
%
  gx(1:n) = ( p(1,1:n) - t(1,1) ) * ( t(2,3)   - t(2,1) ) ...
          - ( t(1,3)   - t(1,1) ) * ( p(2,1:n) - t(2,1) );

  gn(1:n) = ( t(1,2) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...
          - ( t(1,3) - t(1,1) ) * ( t(2,2) - t(2,1) );

  hx(1:n) = ( p(1,1:n) - t(1,5) ) * ( t(2,4)   - t(2,5) ) ...
          - ( t(1,4)   - t(1,5) ) * ( p(2,1:n) - t(2,5) );

  hn(1:n) = ( t(1,2) - t(1,5) ) * ( t(2,4) - t(2,5) ) ...
          - ( t(1,4) - t(1,5) ) * ( t(2,2) - t(2,5) );

  phi(2,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );

  dphidx(2,1:n) =  ( ( t(2,3) - t(2,1) ) * hx(1:n) ...
              + gx(1:n) * ( t(2,4) - t(2,5) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );

  dphidy(2,1:n) = -( ( t(1,3) - t(1,1) ) * hx(1:n) ...
              + gx(1:n) * ( t(1,4) - t(1,5) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );
%
%  Basis function 3: PHI(X,Y) = G(1,2) * H(5,6) / normalization.
%
  gx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,1)   - t(2,2) ) ...
          - ( t(1,1)   - t(1,2) ) * ( p(2,1:n) - t(2,2) );

  gn(1:n) = ( t(1,3) - t(1,2) ) * ( t(2,1) - t(2,2) ) ...
          - ( t(1,1) - t(1,2) ) * ( t(2,3) - t(2,2) );

  hx(1:n) = ( p(1,1:n) - t(1,6) ) * ( t(2,5)   - t(2,6) ) ...
          - ( t(1,5)   - t(1,6) ) * ( p(2,1:n) - t(2,6) );

  hn(1:n) = ( t(1,3) - t(1,6) ) * ( t(2,5) - t(2,6) ) ...
          - ( t(1,5) - t(1,6) ) * ( t(2,3) - t(2,6) );

  phi(3,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );

  dphidx(3,1:n) =  ( ( t(2,1) - t(2,2) ) * hx(1:n) ...
              + gx(1:n) * ( t(2,5) - t(2,6) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );

  dphidy(3,1:n) = -( ( t(1,1) - t(1,2) ) * hx(1:n) ...
              + gx(1:n) * ( t(1,5) - t(1,6) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );
%
%  Basis function 4: PHI(X,Y) = G(1,3) * H(2,3) / normalization.
%
  gx(1:n) = ( p(1,1:n) - t(1,3) ) * ( t(2,1)   - t(2,3) ) ...
          - ( t(1,1)   - t(1,3) ) * ( p(2,1:n) - t(2,3) );

  gn(1:n) = ( t(1,4) - t(1,3) ) * ( t(2,1) - t(2,3) ) ...
          - ( t(1,1) - t(1,3) ) * ( t(2,4) - t(2,3) );

  hx(1:n) = ( p(1,1:n) - t(1,3) ) * ( t(2,2)   - t(2,3) ) ...
          - ( t(1,2)   - t(1,3) ) * ( p(2,1:n) - t(2,3) );

  hn(1:n) = ( t(1,4) - t(1,3) ) * ( t(2,2) - t(2,3) ) ...
          - ( t(1,2) - t(1,3) ) * ( t(2,4) - t(2,3) );

  phi(4,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );

  dphidx(4,1:n) =  ( ( t(2,1) - t(2,3) ) * hx(1:n) ...
              + gx(1:n) * ( t(2,2) - t(2,3) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );

  dphidy(4,1:n) = -( ( t(1,1) - t(1,3) ) * hx(1:n) ...
              + gx(1:n) * ( t(1,2) - t(1,3) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );
%
%  Basis function 5: PHI(X,Y) = G(2,1) * H(3,1) / normalization.
%
  gx(1:n) = ( p(1,1:n) - t(1,1) ) * ( t(2,2)   - t(2,1) ) ...
          - ( t(1,2)   - t(1,1) ) * ( p(2,1:n) - t(2,1) );

  gn(1:n) = ( t(1,5) - t(1,1) ) * ( t(2,2) - t(2,1) ) ...
          - ( t(1,2) - t(1,1) ) * ( t(2,5) - t(2,1) );

  hx(1:n) = ( p(1,1:n) - t(1,1) ) * ( t(2,3)   - t(2,1) ) ...
          - ( t(1,3)   - t(1,1) ) * ( p(2,1:n) - t(2,1) );

  hn(1:n) = ( t(1,5) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...
          - ( t(1,3) - t(1,1) ) * ( t(2,5) - t(2,1) );

  phi(5,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );

  dphidx(5,1:n) =  ( ( t(2,2) - t(2,1) ) * hx(1:n) ...
              + gx(1:n) * ( t(2,3) - t(2,1) ) ) ...
               ./ ( gn(1:n) .* hn(1:n) );

  dphidy(5,1:n) = -( ( t(1,2) - t(1,1) ) * hx(1:n) ...
              + gx(1:n) * ( t(1,3) - t(1,1) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );
%
%  Basis function 6: PHI(X,Y) = G(1,2) * H(3,2) / normalization.
%
  gx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,1)   - t(2,2) ) ...
          - ( t(1,1)   - t(1,2) ) * ( p(2,1:n) - t(2,2) );

  gn(1:n) = ( t(1,6) - t(1,2) ) * ( t(2,1) - t(2,2) ) ...
          - ( t(1,1) - t(1,2) ) * ( t(2,6) - t(2,2) );

  hx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,3)   - t(2,2) ) ...
          - ( t(1,3)   - t(1,2) ) * ( p(2,1:n) - t(2,2) );

  hn(1:n) = ( t(1,6) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...
          - ( t(1,3) - t(1,2) ) * ( t(2,6) - t(2,2) );

  phi(6,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );

  dphidx(6,1:n) =  ( ( t(2,1) - t(2,2) ) * hx(1:n) ...
              + gx(1:n) * ( t(2,3) - t(2,2) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );

  dphidy(6,1:n) = -( ( t(1,1) - t(1,2) ) * hx(1:n) ...
              + gx(1:n) * ( t(1,3) - t(1,2) ) ) ...
              ./ ( gn(1:n) .* hn(1:n) );

  return
end
function fem_value = fem2d_transfer ( sample_element_order, ...
  sample_element_num, sample_value_dim, sample_node_xy, ...
  sample_element_node, sample_element_neighbor, sample_value, fem_node_num, ...
  fem_element_num, fem_value_dim, fem_node_xy, fem_element_node )

%*****************************************************************************80
%
%% FEM2D_TRANSFER "transfers" from one finite element mesh to another.
%
%  Discussion:
%
%    1) the linear system A*X=B is defined with A being a full storage matrix.
%       This can easily be fixed using MATLAB's SPARSE facility.
%
%    2) the quadrature rule used is low order.
%
%    3) the triangular elements are assumed to be linear.
%
%
%    We are also given a set of "sample" finite element function defined
%    by SAMPLE_NODE_XY, SAMPLE_ELEMENT, and SAMPLE_VALUE.
%
%    We are given a second finite element mesh, FEM_NODE_XY and
%    FEM_ELEMENT_NODE.
%
%    Our aim is to "project" the sample data values into the finite element
%    space, that is, to come up with a finite element function FEM_VALUE which
%    well approximates the sample data.
%
%    Now let W(x,y) represent a function interpolating the sample data, and
%    let Vk(x,y) represent the finite element basis function associated with
%    node K.
%
%    Then we seek the coefficient vector U corresponding to a finite element
%    function U(x,y) of the form:
%
%      U(x,y) = sum ( 1 <= K <= N ) Uk * Vk(x,y)
%
%    To determine the coefficent vector entries U, we form a set of
%    projection equations.  For node K at grid point (I,J), the associated
%    basis function Vk(x,y) is used to pose the equation:
%
%      Integral U(x,y) Vk(x,y) dx dy = Integral W(x,y) Vk(x,y) dx dy
%
%    The left hand side is the usual stiffness matrix times the desired
%    coefficient vector U.  To complete the system, we simply need to
%    determine the right hand side, that is, the integral of the data function
%    W against the basis function Vk.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer SAMPLE_NODE_NUM, the number of nodes.
%
%    Input, integer SAMPLE_ELEMENT_ORDER, the element order.
%
%    Input, integer SAMPLE_ELEMENT_NUM, the number of elements.
%
%    Input, integer SAMPLE_VALUE_DIM, the value dimension.
%
%    Input, integer SAMPLE_VALUE_NUM, the number of values.
%
%    Input, real SAMPLE_NODE_XY(2,SAMPLE_NODE_NUM), the nodes.
%
%    Input, integer SAMPLE_ELEMENT_NODE(SAMPLE_ELEMENT_ORDER,SAMPLE_ELEMENT_NUM),
%    the nodes that make up each element.
%
%    Input, integer SAMPLE_ELEMENT_NEIGHBOR(3,SAMPLE_ELEMENT_NUM),
%    the neighbor triangles.
%
%    Input, real SAMPLE_VALUE(SAMPLE_VALUE_DIM,SAMPLE_NODE_NUM),
%    the values.
%
%    Input, integer FEM_NODE_NUM, the number of nodes.
%
%    Input, integer FEM_ELEMENT_ORDER, the element order.
%
%    Input, integer FEM_ELEMENT_NUM, the number of elements.
%
%    Input, integer FEM_VALUE_DIM, the value dimension.
%
%    Input, integer FEM_VALUE_NUM, the number of values.
%
%    Input, real FEM_NODE_XY(2,FEM_NODE_NUM), the nodes.
%
%    Input, integer FEM_ELEMENT_NODE(FEM_ELEMENT_ORDER,FEM_ELEMENT_NUM),
%    the nodes that make up each element.
%
%    Output, real FEM_VALUE(FEM_VALUE_DIM,FEM_VALUE_NUM),
%    the values.
%
  project_node_num = 1;
  quad_num = 3;
%
%  Assemble the coefficient matrix A and the right-hand side B.
%
  b = zeros (fem_node_num,fem_value_dim);
%
%  Define A as a sparse matrix.
%
  a = sparse ( [], [], [], fem_node_num, fem_node_num );

% a = zeros (fem_node_num,fem_node_num);

  for element = 1 : fem_element_num

    i1 = fem_element_node(1,element);
    i2 = fem_element_node(2,element);
    i3 = fem_element_node(3,element);

    area = 0.5 * ...
      ( fem_node_xy(1,i1) * ( fem_node_xy(2,i2) - fem_node_xy(2,i3) ) ...
      + fem_node_xy(1,i2) * ( fem_node_xy(2,i3) - fem_node_xy(2,i1) ) ...
      + fem_node_xy(1,i3) * ( fem_node_xy(2,i1) - fem_node_xy(2,i2) ) );
%
%  Consider each quadrature point.
%  Here, we use the midside nodes as quadrature points.
%
    for quad = 1 : quad_num

      q1 =       quad;
      q2 = mod ( quad, quad_num ) + 1;

      nq1 = fem_element_node(q1,element);
      nq2 = fem_element_node(q2,element);

      xq = 0.5 * ( fem_node_xy(1,nq1) + fem_node_xy(1,nq2) );
      yq = 0.5 * ( fem_node_xy(2,nq1) + fem_node_xy(2,nq2) );
      wq = 1.0 / 3.0;
%
%  Consider each test function in the element.
%
      for ti1 = 1 : 3

        ti2 = mod ( ti1,     3 ) + 1;
        ti3 = mod ( ti1 + 1, 3 ) + 1;

        nti1 = fem_element_node(ti1,element);
        nti2 = fem_element_node(ti2,element);
        nti3 = fem_element_node(ti3,element);

        qi = 0.5 * ( ...
            ( fem_node_xy(1,nti3) - fem_node_xy(1,nti2) ) ...
          * ( yq - fem_node_xy(2,nti2) ) ...
          - ( fem_node_xy(2,nti3) - fem_node_xy(2,nti2) ) ...
          * ( xq - fem_node_xy(1,nti2) ) ) / area;
%
%  The projection takes place here.  The finite element code needs the value
%  of the sample function at the point (XQ,YQ).  The call to PROJECTION
%  locates (XQ,YQ) in the triangulated mesh of sample data, and returns a
%  value produced by piecewise linear interpolation.
%
        project_node_xy(1,1) = xq;
        project_node_xy(2,1) = yq;

        project_value = projection ( sample_node_xy, ...
          sample_element_order, sample_element_num, sample_element_node, ...
          sample_element_neighbor, sample_value_dim, sample_value, ...
          project_node_num, project_node_xy );

        b(nti1,1:fem_value_dim) = b(nti1,1:fem_value_dim) ...
          + area * wq * ( project_value(1:fem_value_dim,1)' * qi );
%
%  Consider each basis function in the element.
%
        for tj1 = 1 : 3

          tj2 = mod ( tj1,     3 ) + 1;
          tj3 = mod ( tj1 + 1, 3 ) + 1;

          ntj1 = fem_element_node(tj1,element);
          ntj2 = fem_element_node(tj2,element);
          ntj3 = fem_element_node(tj3,element);

          qj = 0.5 * ( ...
              ( fem_node_xy(1,ntj3) - fem_node_xy(1,ntj2) ) ...
            * ( yq - fem_node_xy(2,ntj2) ) ...
            - ( fem_node_xy(2,ntj3) - fem_node_xy(2,ntj2) ) ...
            * ( xq - fem_node_xy(1,ntj2) ) ) / area;

          a(nti1,ntj1) = a(nti1,ntj1) + area * wq * ( qi * qj );

        end

      end

    end

  end
%
%  Solve the linear system A * X = B.
%
  fem_value = ( a \ b )';

  return
end
function isgn = i4col_compare ( m, n, a, i, j )

%*****************************************************************************80
%
%% I4COL_COMPARE compares columns I and J of a integer array.
%
%  Example:
%
%    Input:
%
%      M = 3, N = 4, I = 2, J = 4
%
%      A = (
%        1  2  3  4
%        5  6  7  8
%        9 10 11 12 )
%
%    Output:
%
%      ISGN = -1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 June 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns.
%
%    Input, integer A(M,N), an array of N columns of vectors of length M.
%
%    Input, integer I, J, the columns to be compared.
%    I and J must be between 1 and N.
%
%    Output, integer ISGN, the results of the comparison:
%    -1, column I < column J,
%     0, column I = column J,
%    +1, column J < column I.
%

%
%  Check.
%
  if ( i < 1)
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  Column index I = %d < 1.\n', i );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  if ( n < i )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  N = %d < column index I = %d.\n', n, i );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  if ( j < 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  Column index J = %d < 1.\n', j );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  if ( n < j )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_COMPARE - Fatal error!\n' );
    fprintf ( 1, '  N = %d < column index J = %d.\n', n, j );
    error ( 'I4COL_COMPARE - Fatal error!' );
  end

  isgn = 0;

  if ( i == j )
    return
  end

  k = 1;

  while ( k <= m )

    if ( a(k,i) < a(k,j) )
      isgn = -1;
      return
    elseif ( a(k,j) < a(k,i) )
      isgn = +1;
      return
    end

    k = k + 1;

  end

  return
end
function a = i4col_sort_a ( m, n, a )

%*****************************************************************************80
%
%% I4COL_SORT_A ascending sorts an I4COL.
%
%  Discussion:
%
%    In lexicographic order, the statement "X < Y", applied to two real
%    vectors X and Y of length M, means that there is some index I, with
%    1 <= I <= M, with the property that
%
%      X(J) = Y(J) for J < I,
%    and
%      X(I) < Y(I).
%
%    In other words, the first time they differ, X is smaller.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows of A, and the length of
%    a vector of data.
%
%    Input, integer N, the number of columns of A.
%
%    Input, integer A(M,N), the array of N columns of M-vectors.
%
%    Output, integer A(M,N), the columns of A have been sorted in ascending
%    lexicographic order.
%
  if ( m <= 0 )
    return
  end

  if ( n <= 1 )
    return
  end
%
%  Initialize.
%
  indx = 0;
  isgn = 0;
%
%  Call the external heap sorter.
%
  while ( 1 )

    [ indx, i, j ] = sort_heap_external ( n, indx, isgn );
%
%  Interchange the I and J objects.
%
    if ( 0 < indx )

      a = i4col_swap ( m, n, a, i, j );
%
%  Compare the I and J objects.
%
    elseif ( indx < 0 )

      isgn = i4col_compare ( m, n, a, i, j );

    elseif ( indx == 0 )

      break

    end

  end

  return
end
function a = i4col_swap ( m, n, a, i, j )

%*****************************************************************************80
%
%% I4COL_SWAP swaps columns I and J of a integer array of column data.
%
%  Example:
%
%    Input:
%
%      M = 3, N = 4, I = 2, J = 4
%
%      A = (
%        1  2  3  4
%        5  6  7  8
%        9 10 11 12 )
%
%    Output:
%
%      A = (
%        1  4  3  2
%        5  8  7  6
%        9 12 11 10 )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns in the array.
%
%    Input, integer A(M,N), an array of N columns of length M.
%
%    Input, integer I, J, the columns to be swapped.
%
%    Output, integer A(M,N), the array, with columns I and J swapped.
%
  if ( i < 1 || n < i || j < 1 || n < j )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4COL_SWAP - Fatal error!\n' );
    fprintf ( 1, '  I or J is out of bounds.\n' );
    fprintf ( 1, '  I =    %d\n', i );
    fprintf ( 1, '  J =    %d\n', j );
    fprintf ( 1, '  N =    %d\n', n );
    error ( 'I4COL_SWAP - Fatal error!' );
  end

  if ( i == j )
    return
  end

  col(1:m) = a(1:m,i)';
  a(1:m,i) = a(1:m,j);
  a(1:m,j) = col(1:m)';

  return
end
function sample_value = projection ( fem_node_xy, ...
  fem_element_order, fem_element_num, fem_element_node, ...
  fem_element_neighbor, fem_value_dim, fem_value, sample_node_num, ...
  sample_node_xy )

%*****************************************************************************80
%
%% PROJECTION evaluates an FEM function on a T3 or T6 triangulation.
%
%  Discussion:
%
%    Note that the sample values returned are true values of the underlying
%    finite element function.  They are NOT produced by constructing some
%    other function that interpolates the data at the finite element nodes
%    (something which MATLAB's griddata function can easily do.)  Instead,
%    each sampling node is located within one of the associated finite
%    element triangles, and the finite element function is developed and
%    evaluated there.
%
%    MATLAB's scattered data interpolation is wonderful, but it cannot
%    be guaranteed to reproduce the finite element function corresponding
%    to nodal data.  This routine can (or at least tries to%).
%
%    So if you are using finite elements, then using THIS routine
%    (but not MATLAB's griddata function), what you see is what you have%
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 June 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer FEM_NODE_NUM, the number of nodes.
%
%    Input, real FEM_NODE_XY(2,FEM_NODE_NUM), the coordinates
%    of the nodes.
%
%    Input, integer FEM_ELEMENT_ORDER, the order of the elements,
%    either 3 or 6.
%
%    Input, integer FEM_ELEMENT_NUM, the number of triangles.
%
%    Input, integer FEM_ELEMENT_NODE(FEM_ELEMENT_ORDER,FEM_ELEMENT_NUM), the
%    nodes that make up each triangle.
%
%    Input, integer FEM_ELEMENT_NEIGHBOR(3,FEM_ELEMENT_NUM), the
%    index of the neighboring triangle on each side, or -1 if no neighbor there.
%
%    Input, integer FEM_VALUE_DIM, the "dimension" of the values.
%
%    Input, real FEM_VALUE(FEM_VALUE_DIM,FEM_NODE_NUM), the
%    finite element coefficient values at each node.
%
%    Input, integer SAMPLE_NODE_NUM, the number of sample nodes.
%
%    Input, real SAMPLE_NODE_XY(2,SAMPLE_NODE_NUM), the sample nodes.
%
%    Output, real SAMPLE_VALUE(FEM_VALUE_DIM,SAMPLE_NODE_NUM),
%    the sampled values.
%
  sample_value = zeros(fem_value_dim,sample_node_num);
%
%  For each sample point: find the triangle T that contains it,
%  and evaluate the finite element function there.
%
  for j = 1 : sample_node_num

    p_xy(1:2,1) = sample_node_xy(1:2,j);
%
%  Find the triangle T that contains the point.
%
    t = triangulation_search_delaunay ( ...
      fem_node_xy, fem_element_num, fem_element_node, ...
      fem_element_neighbor, p_xy );

    if ( t == -1 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'PROJECTION - Fatal error!\n' );
      fprintf ( 1, '  Triangulation search failed!\n' );
      error ( 'PROJECTION - Fatal error!' );
    end
%
%  Evaluate the finite element basis functions at the point in T.
%
    t_node(1:fem_element_order) = fem_element_node(1:fem_element_order,t);

    t_xy(1:2,1:fem_element_order) = fem_node_xy(1:2,t_node);

    if ( fem_element_order == 3 )
      b = basis_mn_t3 ( t_xy, 1, p_xy );
    elseif ( fem_element_order == 6 )
      b = basis_mn_t6 ( t_xy, 1, p_xy );
    end
%
%  Multiply by the finite element values to get the sample values.
%
    for i = 1 : fem_value_dim
      sample_value(i,j) = fem_value(i,t_node(1:fem_element_order)) ...
        * b(1:fem_element_order);
    end

  end

  return
end
function r8mat_write ( output_filename, m, n, table )

%*****************************************************************************80
%
%% R8MAT_WRITE writes an R8MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 June 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the output filename.
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real TABLE(M,N), the points.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'R8MAT_WRITE - Error!' );
  end
%
%  Write the data.
%
%  For greater precision, try:
%
%     fprintf ( output_unit, '  %24,16f', table(i,j) );
%
  for j = 1 : n
    for i = 1 : m
      fprintf ( output_unit, '  %14f', table(i,j) );
    end
    fprintf ( output_unit, '\n' );
  end
%
%  Close the file.
%
  fclose ( output_unit );

  return
end
function [ indx, i, j ] = sort_heap_external ( n, indx, isgn )

%*****************************************************************************80
%
%% SORT_HEAP_EXTERNAL externally sorts a list of items into ascending order.
%
%  Discussion:
%
%    The actual list of data is not passed to the routine.  Hence this
%    routine may be used to sort integers, reals, numbers, names,
%    dates, shoe sizes, and so on.  After each call, the routine asks
%    the user to compare or interchange two items, until a special
%    return value signals that the sorting is completed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 February 2004
%
%  Author:
%
%    Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    Albert Nijenhuis, Herbert Wilf.
%    Combinatorial Algorithms,
%    Academic Press, 1978, second edition,
%    ISBN 0-12-519260-6.
%
%  Parameters:
%
%    Input, integer N, the number of items to be sorted.
%
%    Input, integer INDX, the main communication signal.
%    The user must set INDX to 0 before the first call.
%    Thereafter, the user should set the input value of INDX
%    to the output value from the previous call.
%
%    Input, integer ISGN, results of comparison of elements I and J.
%    (Used only when the previous call returned INDX less than 0).
%    ISGN <= 0 means I is less than or equal to J;
%    0 <= ISGN means I is greater than or equal to J.
%
%    Output, integer INDX, the main communication signal.
%    If INDX is
%
%      greater than 0, the user should:
%      * interchange items I and J;
%      * call again.
%
%      less than 0, the user should:
%      * compare items I and J;
%      * set ISGN = -1 if I < J, ISGN = +1 if J < I;
%      * call again.
%
%      equal to 0, the sorting is done.
%
%    Output, integer I, J, the indices of two items.
%    On return with INDX positive, elements I and J should be interchanged.
%    On return with INDX negative, elements I and J should be compared, and
%    the result reported in ISGN on the next call.
%
  persistent i_save;
  persistent j_save;
  persistent k;
  persistent k1;
  persistent n1;

  if ( isempty ( i_save ) )
    i_save = -1;
  end

  if ( isempty ( j_save ) )
    j_save = -1;
  end
%
%  INDX = 0: This is the first call.
%
  if ( indx == 0 )

    k = floor ( n / 2 );
    k1 = k;
    n1 = n;
%
%  INDX < 0: The user is returning the results of a comparison.
%
  elseif ( indx < 0 )

    if ( indx == -2 )

      if ( isgn < 0 )
        i_save = i_save + 1;
      end

      j_save = k1;
      k1 = i_save;
      indx = -1;
      i = i_save;
      j = j_save;
      return;
    end

    if ( 0 < isgn )
      indx = 2;
      i = i_save;
      j = j_save;
      return;
    end

    if ( k <= 1 )

      if ( n1 == 1 )
        i_save = 0;
        j_save = 0;
        indx = 0;
      else
        i_save = n1;
        n1 = n1 - 1;
        j_save = 1;
        indx = 1;
      end

      i = i_save;
      j = j_save;
      return;

    end

    k = k - 1;
    k1 = k;
%
%  0 < INDX, the user was asked to make an interchange.
%
  elseif ( indx == 1 )

    k1 = k;

  end

  while ( 1 )

    i_save = 2 * k1;

    if ( i_save == n1 )
      j_save = k1;
      k1 = i_save;
      indx = -1;
      i = i_save;
      j = j_save;
      return;
    elseif ( i_save <= n1 )
      j_save = i_save + 1;
      indx = -2;
      i = i_save;
      j = j_save;
      return;
    end

    if ( k <= 1 )
      break;
    end

    k = k - 1;
    k1 = k;

  end

  if ( n1 == 1 )
    i_save = 0;
    j_save = 0;
    indx = 0;
    i = i_save;
    j = j_save;
  else
    i_save = n1;
    n1 = n1 - 1;
    j_save = 1;
    indx = 1;
    i = i_save;
    j = j_save;
  end

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end
function triangle_neighbor = triangulation_order3_neighbor_triangles ( ...
  triangle_num, triangle_node )

%*****************************************************************************80
%
%% TRIANGULATION_ORDER3_NEIGHBOR_TRIANGLES determines triangle neighbors.
%
%  Discussion:
%
%    A triangulation of a set of nodes can be completely described by
%    the coordinates of the nodes, and the list of nodes that make up
%    each triangle.  However, in some cases, it is necessary to know
%    triangle adjacency information, that is, which triangle, if any,
%    is adjacent to a given triangle on a particular side.
%
%    This routine creates a data structure recording this information.
%
%    The primary amount of work occurs in sorting a list of 3 * TRIANGLE_NUM
%    data items.
%
%    This routine was modified to use columns instead of rows.
%
%  Example:
%
%    The input information from TRIANGLE_NODE:
%
%    Triangle   Nodes
%    --------   ---------------
%     1         3      4      1
%     2         3      1      2
%     3         3      2      8
%     4         2      1      5
%     5         8      2     13
%     6         8     13      9
%     7         3      8      9
%     8        13      2      5
%     9         9     13      7
%    10         7     13      5
%    11         6      7      5
%    12         9      7      6
%    13        10      9      6
%    14         6      5     12
%    15        11      6     12
%    16        10      6     11
%
%    The output information in TRIANGLE_NEIGHBOR:
%
%    Triangle  Neighboring Triangles
%    --------  ---------------------
%
%     1        -1     -1      2
%     2         1      4      3
%     3         2      5      7
%     4         2     -1      8
%     5         3      8      6
%     6         5      9      7
%     7         3      6     -1
%     8         5      4     10
%     9         6     10     12
%    10         9      8     11
%    11        12     10     14
%    12         9     11     13
%    13        -1     12     16
%    14        11     -1     15
%    15        16     14     -1
%    16        13     15     -1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 February 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer TRIANGLE_NUM, the number of triangles.
%
%    Input, integer TRIANGLE_NODE(3,TRIANGLE_NUM), the nodes that make up each triangle.
%
%    Output, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the three triangles that are direct
%    neighbors of a given triangle.  TRIANGLE_NEIGHBOR(1,I) is the index of the triangle
%    which touches side 1, defined by nodes 2 and 3, and so on.  TRIANGLE_NEIGHBOR(1,I)
%    is negative if there is no neighbor on that side.  In this case, that
%    side of the triangle lies on the boundary of the triangulation.
%

%
%  Step 1.
%  From the list of nodes for triangle T, of the form: (I,J,K)
%  construct the three neighbor relations:
%
%    (I,J,1,T) or (J,I,1,T),
%    (J,K,2,T) or (K,J,2,T),
%    (K,I,3,T) or (I,K,3,T)
%
%  where we choose (I,J,1,T) if I < J, or else (J,I,1,T)
%
  col = zeros ( 4, 3 * triangle_num );

  for tri = 1 : triangle_num

    i = triangle_node(1,tri);
    j = triangle_node(2,tri);
    k = triangle_node(3,tri);

    if ( i < j )
      col(1:4,1+3*(tri-1)) = [ i, j, 1, tri ]';
    else
      col(1:4,1+3*(tri-1)) = [ j, i, 1, tri ]';
    end

    if ( j < k )
      col(1:4,2+3*(tri-1)) = [ j, k, 2, tri ]';
    else
      col(1:4,2+3*(tri-1)) = [ k, j, 2, tri ]';
    end

    if ( k < i )
      col(1:4,3+3*(tri-1)) = [ k, i, 3, tri ]';
    else
      col(1:4,3+3*(tri-1)) = [ i, k, 3, tri ]';
    end

  end
%
%  Step 2. Perform an ascending dictionary sort on the neighbor relations.
%  We only intend to sort on rows 1 and 2; the routine we call here
%  sorts on rows 1 through 4 but that won't hurt us.
%
%  What we need is to find cases where two triangles share an edge.
%  Say they share an edge defined by the nodes I and J.  Then there are
%  two columns of COL that start out ( I, J, ?, ? ).  By sorting COL,
%  we make sure that these two columns occur consecutively.  That will
%  make it easy to notice that the triangles are neighbors.
%
  col = i4col_sort_a ( 4, 3*triangle_num, col );
%
%  Step 3. Neighboring triangles show up as consecutive columns with
%  identical first two entries.  Whenever you spot this happening,
%  make the appropriate entries in TRIANGLE_NEIGHBOR.
%
  triangle_neighbor(1:3,1:triangle_num) = -1;

  icol = 1;

  while ( 1 )

    if ( 3 * triangle_num <= icol )
      break
    end

    if ( col(1,icol) ~= col(1,icol+1) || col(2,icol) ~= col(2,icol+1) )
      icol = icol + 1;
      continue
    end

    side1 = col(3,icol);
    tri1 =  col(4,icol);
    side2 = col(3,icol+1);
    tri2 =  col(4,icol+1);

    triangle_neighbor(side1,tri1) = tri2;
    triangle_neighbor(side2,tri2) = tri1;

    icol = icol + 2;

  end

  return
end
function [ triangle_index, edge ] = ...
  triangulation_search_delaunay ( node_xy, ...
  triangle_num, triangle_node, triangle_neighbor, p )

%*****************************************************************************80
%
%% TRIANGULATION_SEARCH_DELAUNAY searches a Delaunay triangulation for a point.
%
%  Purpose:
%
%    The algorithm "walks" from one triangle to its neighboring triangle,
%    and so on, until a triangle is found containing point P, or P is found
%    to be outside the convex hull.
%
%    The algorithm computes the barycentric coordinates of the point with
%    respect to the current triangle.  If all three quantities are positive,
%    the point is contained in the triangle.  If the I-th coordinate is
%    negative, then P lies on the far side of edge I, which is opposite
%    from vertex I.  This gives a hint as to where to search next.
%
%    For a Delaunay triangulation, the search is guaranteed to terminate.
%    For other triangulations, a cycle may occur.
%
%    Note the surprising fact that, even for a Delaunay triangulation of
%    a set of points, the nearest point to P need not be one of the
%    vertices of the triangle containing P.
%
%    The code can be called for triangulations of any order, but only
%    the first three nodes in each triangle are considered.  Thus, if
%    higher order triangles are used, and the extra nodes are intended
%    to give the triangle a polygonal shape, these will have no effect,
%    and the results obtained here might be misleading.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 January 2010
%
%  Author:
%
%    Original FORTRAN77 version by Barry Joe.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Barry Joe,
%    GEOMPACK - a software package for the generation of meshes
%    using geometric algorithms,
%    Advances in Engineering Software,
%    Volume 13, pages 325-331, 1991.
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, real NODE_XY(2,NODE_NUM), the vertices.
%
%    Input, integer TRIANGLE_ORDER, the order of the triangles.
%
%    Input, integer TRIANGLE_NUM, the number of triangles in the triangulation.
%
%    Input, integer TRIANGLE_NODE(TRIANGLE_ORDER,TRIANGLE_NUM),
%    the nodes that make up each triangle.
%
%    Input, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the triangle
%    neighbor list.
%
%    Input, real P(2), the coordinates of a point.
%
%    Output, integer TRIANGLE_INDEX, the index of the triangle where the
%    search ended.  If a cycle occurred, then TRIANGLE_INDEX = -1.
%
%    Output, integer EDGE, indicates the position of the point P in
%    triangle TRIANGLE_INDEX:
%    0, the interior or boundary of the triangle;
%    -1, outside the convex hull of the triangulation, past edge 1;
%    -2, outside the convex hull of the triangulation, past edge 2;
%    -3, outside the convex hull of the triangulation, past edge 3.
%
  persistent triangle_index_save;

  if ( isempty ( triangle_index_save ) )
    triangle_index_save = -1;
  end

  count = 0;
  edge = 0;

  if ( triangle_index_save < 1 || triangle_num < triangle_index_save )
    triangle_index = floor ( ( triangle_num + 1 ) / 2 );
  else
    triangle_index = triangle_index_save;
  end

  while ( 1 )

    count = count + 1;

    if ( triangle_num < count )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'TRIANGULATION_SEARCH_DELAUNAY - Fatal error!\n' );
      fprintf ( 1, '  The algorithm seems to be cycling.\n' );
      triangle_index = -1;
      edge = -1;
      return
    end
%
%  Get the vertices of triangle TRIANGLE_INDEX.
%
    a = triangle_node(1,triangle_index);
    b = triangle_node(2,triangle_index);
    c = triangle_node(3,triangle_index);
%
%  Using vertex C as a base, compute the distances to vertices A and B,
%  and the point P.
%
    dxa = node_xy(1,a) - node_xy(1,c);
    dya = node_xy(2,a) - node_xy(2,c);

    dxb = node_xy(1,b) - node_xy(1,c);
    dyb = node_xy(2,b) - node_xy(2,c);

    dxp = p(1)         - node_xy(1,c);
    dyp = p(2)         - node_xy(2,c);

    det = dxa * dyb - dya * dxb;
%
%  Compute the barycentric coordinates of the point P with respect
%  to this triangle.
%
    alpha = ( dxp * dyb - dyp * dxb ) / det;
    beta =  ( dxa * dyp - dya * dxp ) / det;
    gamma = 1.0 - alpha - beta;
%
%  If the barycentric coordinates are all positive, then the point
%  is inside the triangle and we're done.
%
    if ( 0.0 <= alpha && 0.0 <= beta && 0.0 <= gamma )
      break
    end
%
%  At least one barycentric coordinate is negative.
%
%  If there is a negative barycentric coordinate for which there exists
%  an opposing triangle neighbor closer to the point, move to that triangle.
%
%  (Two coordinates could be negative, in which case we could go for the
%  most negative one, or the most negative one normalized by the actual
%  distance it represents).
%
    if ( alpha < 0.0 && 0 < triangle_neighbor(2,triangle_index) )
      triangle_index = triangle_neighbor(2,triangle_index);
      continue;
    elseif ( beta < 0.0 && 0 < triangle_neighbor(3,triangle_index) )
      triangle_index = triangle_neighbor(3,triangle_index);
      continue;
    elseif ( gamma < 0.0 && 0 < triangle_neighbor(1,triangle_index) )
      triangle_index = triangle_neighbor(1,triangle_index);
      continue;
    end
%
%  All negative barycentric coordinates correspond to vertices opposite
%  sides on the convex hull.
%
%  Note the edge and exit.
%
    if ( alpha < 0.0 )
      edge = -2;
      break
    elseif ( beta < 0.0 )
      edge = -3;
      break
    elseif ( gamma < 0.0 )
      edge = -1;
      break
    end

  end

  triangle_index_save = triangle_index;

  return
end


function efv = pne_event_nose(cx, opt)
%PNE_EVENT_NOSE  Event function to detect the limit or nose point
%   EFV = PNE_EVENT_NOSE(CX, OPT)
%
%   PNE_MASTER event function to detect the limit or nose point of the
%   continuation curve, based on the sign of the lambda component of the
%   tangent vector.
%
%   Set OPT.stop_at to 'NOSE' to use this function to trigger termination
%   of the continuation at the limit or nose point.
%
%   Inputs:
%       CX : struct containing info about current point (continuation soln)
%       OPT - PNES_MASTER options struct
%
%   Outputs:
%       EFV : event function value
%
%   See also PNES_MASTER, PNE_REGISTER_EVENTS, PNE_EVENT_TARGET_LAM.

%   MP-Opt-Model
%   Copyright (c) 2016-2021, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%   and Shrirang Abhyankar, Argonne National Laboratory
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

%% event function value is dlam, the last element of the
%% normalized tangent vector at the current soln
efv = cx.z(end);


%% Selecting Grains
%
%%
% In this section we discuss how to select grains by properties. We start
% our discussion by reconstructing the grain structure from a sample EBSD
% data set.

% load sample EBSD data set
mtexdata forsterite silent

% restrict it to a subregion of interest.
ebsd = ebsd(inpolygon(ebsd,[5 2 10 5]*10^3));

% remove all not indexed pixels
ebsd = ebsd('indexed');

% reconstruct grains
[grains, ebsd.grainId] = calcGrains(ebsd,'angle',5*degree);

% smooth them
grains = smooth(grains,5);

% plot the orientation data of the Forsterite phase
plot(ebsd('fo'),ebsd('fo').orientations)

% plot the grain boundary on top of it
hold on
plot(grains.boundary,'lineWidth',2)
hold off

%% Selecting grains by mouse
% The most easiest way to select a grain is by using the mouse and the
% command <grain2d.selectInteractive.html selectInteractive> which allows
% you to select an arbitrary amount of grains. The index of the selected
% grains appear as the global variable |indSelected| in your workspace

selectInteractive(grains,'lineColor','gold')

% this simulates a mouse click
pause(0.1)
simulateClick(9000,3500)
pause(0.1)

global indSelected;
grains(indSelected)

hold on
plot(grains(indSelected).boundary,'lineWidth',4,'lineColor','gold')
hold off

%% Indexing by orientation or position
% One can also to select a grain by spatial coordinates without user
% interaction. This is done using the syntax |grains(x,y)|, i.e.,

x = 12000; y = 4000;

hold on
plot(grains(x,y).boundary,'linewidth',4,'linecolor','blue')

plot(x,y,'marker','s','markerfacecolor','k',...
  'markersize',10,'markeredgecolor','w')
hold off

%%
% Alternatively one can also select all grains with a certain orientation.
% Lets find all grains with a similar orientation as the one marked in
% gold. As threshold we shall use 20 degree

% select grains by orientation
grains_selected = grains.findByOrientation(grains(indSelected).meanOrientation,20*degree)

hold on
plot(grains_selected.boundary,'linewidth',4,'linecolor','gold')
hold off

%% Indexing by a Property
% In order the generalize the above concept lets remember that the variable
% |grains| is essentially a large vector of grains. Thus when applying a
% function like <grain2d.area.html area> to this variable we obtain a
% vector of the same lenght with numbers representing the area of each
% grain

grain_area = grains.area;

%%
% As a first rather simple application we could colorize the grains
% according to their area, i.e., according to the numbers stored in
% |grain_area|

plot(grains,grain_area)

%%
% As a second application, we can ask for the largest grain within our data
% set. The maximum value and its position within a vector are found by the
% Matlab command |max|.

[max_area,max_id] = max(grain_area)

%%
% The number |max_id| is the position of the grain with a maximum area within
% the variable |grains|. We can access this specific grain by direct
% indexing

grains(max_id)

%%
% and so we can plot it

hold on
plot(grains(max_id).boundary,'linecolor','red','linewidth',4)
hold off

%%
% Note that this way of addressing individual grains can be generalized to
% many grains. E.g. assume we are interested in the largest 5 grains. Then
% we can sort the vector |grain_area| and take the indices of the 5 largest
% grains.

[sorted_area,sorted_id] = sort(grain_area,'descend');

large_grain_id = sorted_id(2:5);

hold on
plot(grains(large_grain_id).boundary,'linecolor','Orange','linewidth',4)
hold off

%% Indexing by a Condition
% By the same syntax as above we can also single out grains that satisfy a
% certain condition. I.e., to access are grains that are at least one
% quarter as large as the largest grain we can do

condition = grain_area > max_area/4;

hold on
plot(grains(condition).boundary,'linecolor','Yellow','linewidth',4)
hold off

%%
% This is a very powerful way of accessing grains as the condition can be
% build up using any grain property. As an example let us consider the
% phase. The phase of the first five grains we get by

grains(1:5).phase

%%
% Now we can access or grains of the first phase Forsterite by the
% condition

condition = grains.phase == 1;
plot(grains(condition))

%%
% To make the above more directly you can use the mineral name for indexing

grains('forsterite')

%%
% Logical indexing allows also for more complex queries, e.g. selecting all
% grains perimeter larger than 6000 and at least 600 measurements within

condition = grains.perimeter>6000 & grains.grainSize >= 600;

selected_grains = grains(condition)

plot(selected_grains)

%% The grainId and how to select EBSD inside specific grains
%
% Besides, the list of grains the command <EBSD.calcGrains.html calcGrains>
% returns also two other output arguments.

plot(grains)
largeGrains = grains(grains.grainSize > 50);

text(largeGrains,largeGrains.id)

%%
% The second output argument grainId is a list with the same size as the
% EBSD measurements that stores for each measurement the corresponding
% grainId. The above syntax stores this list directly inside the ebsd
% variable. This enables MTEX to select EBSD data by grains. The following
% command returns all the EBSD data that belong to grain number 33.

ebsd(grains(33))

%%
% and is equivalent to the command

ebsd(ebsd.grainId == 33)

%%
% The following picture plots the largest grains together with its
% individual orientation measurements.

plot(ebsd(grains(max_id)),ebsd(grains(max_id)).orientations)
hold on
plot(grains(max_id).boundary,'lineWidth',2)
hold off

%% Boundary grains
% Sometimes it is desirable to remove all boundary grains as they might
% distort grain statistics. To do so one should remember that each grain
% boundary has a property |grainId| which stores the ids of the neigbouring
% grains. In the case of an outer grain boundary, one of the neighbouring
% grains has the id zero. We can filter out all these boundary segments by

% ids of the outer boundary segment
outerBoundary_id = any(grains.boundary.grainId==0,2);

% plot the outer boundary segments
plot(grains)
hold on
plot(grains.boundary(outerBoundary_id),'linecolor','red','linewidth',2)
hold off

%%
% Now |grains.boundary(outerBoundary_id).grainId| is a list of grain ids
% where the first column is zero, indicating the outer boundary, and the
% second column contains the id of the boundary grain. Hence, it remains to
% remove all grains with these ids.

% next we compute the corresponding grain_id
grain_id = grains.boundary(outerBoundary_id).grainId;

% remove all zeros
grain_id(grain_id==0) = [];

% and plot the boundary grains
plot(grains(grain_id))

%%
% finally, we could remove the boundary grains by
%
%   grains(grain_id) = []
%
% However, boundary grains can be selected more easily be the command
% |<grain2d/isBoundary.html isBoundary>|.

plot(grains(~grains.isBoundary))


function [NV,NF,OV,OE,OV1,OE1,epsilon] = remesh_at_handles(V,F,C,P,BE,CE)
  % REMESH_AT_HANDLES  remesh a given mesh using its outline and constraining
  % interrior controls at given handles. Point handles are met exactly and
  % bones are sample at the given rate.
  %
  % [NV,NF] = remesh_at_handles(V,F,C,P,BE,CE)
  %
  % Inputs:
  %  V  list of vertex positions
  %  F  list of face indices
  %  C  list of control vertex positions
  %  P  list of indices into C for point controls, { 1:size(C,1) }
  %  BE  list of bones, pairs of indices into C, connecting control vertices,
  %    { [] }
  %  CE  list of "cage edges", pairs of indices into ***P***, connecting
  %    control ***points***. A "cage edge" just tells point boundary conditions
  %    to vary linearly along straight lines between the end points, and to be
  %    zero for all other handles. { [] }
  % Outputs
  %  NV  new list of vertex positions
  %  NF  new list of face indices
  %  OV  list of vertex positions sent to triangle
  %  OE  list of edges sent to triangle
  %  OV1 list of vertex positions before performing close point collapses and
  %    edge splits
  %  OE1 list of edges before performing close point collapses and edge splits
  %  epsilon  used to collapse points and split edges
  %
  % Example:
  %  [NV,NF,OV,OE,OV1,OE1] = remesh_at_handles(V,F,C,P,BE,CE);
  %  % show a plot of what's sent to triangle
  %  subplot(3,1,1);
  %  plot([OV1(OE1(:,1),1) OV1(OE1(:,2),1)]',[OV1(OE1(:,1),2) OV1(OE1(:,2),2)]','-','LineWidth',1);
  %  hold on;
  %  plot(OV1(:,1),OV1(:,2),'.');
  %  hold off;
  %  axis equal;
  %  title('Outline + handle samples');
  %  subplot(3,1,2);
  %  plot([OV(OE(:,1),1) OV(OE(:,2),1)]',[OV(OE(:,1),2) OV(OE(:,2),2)]','-','LineWidth',1);
  %  hold on;
  %  plot(OV(:,1),OV(:,2),'.');
  %  hold off;
  %  axis equal;
  %  title('Input to triangle (collapsed points + split edges)');
  %  % show a plot of the result
  %  subplot(3,1,3);
  %  tsurf(NF,NV);
  %  hold on;
  %  plot([OV(OE(:,1),1) OV(OE(:,2),1)]',[OV(OE(:,1),2) OV(OE(:,2),2)]','-','LineWidth',2);
  %  hold off;
  %  axis equal;
  %  title('Output of triangle');

  %% THIS DOES NOT WORK FOR MESHES THAT AREN"T TOPOLOGICAL DISKS!! HOLES WILL
  %% BE CLOSED

  dim = size(V,2);
  assert(dim == size(C,2));
  % only work with 2D
  assert(dim == 2);

  % Find all edges in mesh, note internal edges are repeated
  E = sort([F(:,1) F(:,2); F(:,2) F(:,3); F(:,3) F(:,1)]')';
  % determine uniqueness of edges
  [u,m,n] = unique(E,'rows');
  % determine counts for each unique edge
  counts = accumarray(n(:), 1);
  % extract edges that only occurred once
  O = u(counts==1,:);
  % extract unique vertex indices on outline
  [u,m,n] = unique(O(:));
  % original map O = IM(O)
  IM = 1:size(V,1);
  IM(O(:)) = n;
  OV = V(u,:);
  OE = IM(O);

  samples_per_edge = 10;
  % Bone samples
  [BES,BESE] = sample_edges(C,BE,samples_per_edge);
  % Cage edge samples
  [CES,CESE] = sample_edges(C(P,:),CE,samples_per_edge);
  % Append handle samples
  OV = [OV;C(P,:);BES;CES];
  OE = [ ...
    OE; ...
    (size(OV,1)-size(BES,1)-size(CES,1))+BESE; ...
    (size(OV,1)-size(CES,1))+CESE];

  % save old values
  OV1 = OV;
  OE1 = OE;

  % phony counts to enter while loop
  prev_v_count = size(OV,1)+1;
  prev_e_count = size(OE,1)+1;
  % this epsilon is a parameter that probably needs to be tweaked and should at
  % least be exposed.
  % Use fraction of average edge length
  epsilon = mean(sqrt(sum((OV(OE(:,1),:) - OV(OE(:,2),:)).^2,2)))/8;
  % continue to collapse points and split edges until nothing more to do
  while( prev_v_count ~= size(OV,1) || prev_e_count ~= size(OE,1))
    prev_v_count = size(OV,1);
    prev_e_count = size(OE,1);
    [OV,OE] = collapse_close_points(OV,OE,epsilon);
    [OV,OE] = snap_points_to_close_edges(OV,OE,epsilon);
  end

  % Again, max area term here is a heuristic
  %sum((OV(OE(:,1)) - OV(OE(:,2))).^2,2)
  % use a multiple of min edge length
  %max_area = 2*(sqrt(3)/4)*min(sum((OV(OE(:,1),:) - OV(OE(:,2),:)).^2,2));
  max_area = 8*(sqrt(3)/4)*min(sum((OV(OE(:,1),:) - OV(OE(:,2),:)).^2,2));
  [NV,NF] = triangle(OV,OE,[],'Quality',30,'MaxArea',max_area);
end


function [ m, n, nst, ist, jst, ast ] = st_transpose ( m, n, nst, ist, jst, ...
  ast )

%*****************************************************************************80
%
%% ST_TRANSPOSE transposes an ST matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 July 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input/output, integer M, the number of row.
%
%    Input/output, integer N, the number of columns.
%
%    Input/output, integer NST, the number of nonzeros.
%
%    Input/output, integer IST(NST), JST(NST), the row and column indices.
%
%    Input/output, real AST(NST), the nonzero values.
%
  t = m;
  m = n;
  n = t;

  t          = ist(1:nst);
  ist(1:nst) = jst(1:nst);
  jst(1:nst) = t(1:nst);

  return
end


function TP = getTransProbs (hmm)
% Returns the transition probabilies from any state to any other state,
% without considering the persistence probabilities (i.e. the probability
% to remain in the same state)
%
% Author: Diego Vidaurre, University of Oxford (2017)

TP = hmm.P;
[K,~,Q] = size(TP);
for j = 1:Q
   TPj = TP(:,:,j);
   TPj(eye(K)==1) = 0;
   for k = 1:K
      TPj(k,:) = TPj(k,:) / sum(TPj(k,:));
   end
   TP(:,:,j) = TPj;
end

end


function [fidout] = improvfid(ecg,fidin,fs,fidtype,fidhelp,N2)
%
% OVERVIEW, This function improves the fiducial point detection for the
% Q,R,S,Toff points in the beat variable. The improved fiducial points are
% stored in the beato variable.
%
% INPUTS    MANDATORY       DESCRIPTION
%
%           ecg             input ecg data in num of samples by 1
%                           dimensions
%           fidin           fiducial point input in samples number.
%           fs              sampling frequency of the input ecg data.
%           fidtype         type of fiducial point input. i.e. Q, R, S or T.
%           fidhelp         R peak annotations used for improving S and Q point detections.
%           N2              window size of 2*N2 is used to find improved fiducial point detection for fiducial point specified as fidtype.
%
% OUTPUTS
%           fidout          Adjusted fiducial point location after
%                           improving fiducial point detection.
%
%
% REPO:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   ORIGINAL SOURCE AND AUTHORS:
%       Written by Shamim Nemati
%       editted by Ismail Sadiq on 10/26/2019.
%	COPYRIGHT (C) 2019
%   LICENSE:
%       This software is offered freely and without warranty under
%       the GNU (v3 or later) public license. See license file for
%       more information. The license may be found in
%       the Documents folder of the Physionet-Cardiovascular-Signal-Toolbox.

fidout=zeros(1,size(fidin,2));

if (nargin<5 || isempty(fidhelp))
    Rp=[]; Sp=[];
elseif (strcmp(fidtype,'S'))
    Rp=fidhelp; Sp=[];
elseif (strcmp(fidtype,'T'))
    Sp = fidhelp; Rp=[];
else
    Rp=[]; Sp=[];
end

if (nargin<4)
    direc=mean(ecg(fidin(:,1)))-mean(ecg);
else
    if (strcmp(fidtype,'R'))
        direc = 1;
    elseif (strcmp(fidtype,'T') & ~isempty(fidhelp))
        direc = median(ecg(fidin))-median(ecg(Sp));
    else
        direc=-1;
    end
end

if (nargin<6)
    N2 = round(0.04*fs);
end

for i=1:size(fidout,2)
    if (~isempty(Rp) & fidin(i)>Rp(i))%S
        upper = min(fidin(i)+N2,Rp(i)+2*N2+10);
        %upper=fidin(i)+N2;
        v=ecg(Rp(i):upper)';% if there's a R right before use it
    else
        v=ecg(fidin(i)-N2:fidin(i)+N2)';
    end
    vi=v;
    if direc>0
        [val,ind]=max(vi);
        fidout(i)=(fidin(i)-N2-1)+ind;
    else
        [val,ind]=min(vi);
        if (~isempty(Rp) & fidin(i)>Rp(i))%S
            fidout(i)=Rp(i)-1+ind;
        else
            fidout(i)=(fidin(i)-N2-1)+ind;
        end
    end
end


function twRatio = computeTWRatio(throttle, ut, rVect, vVect, tankMasses, dryMass, stgStates, lvState, tankStates, bodyInfo, storageSoCs, powerStorageStates)
    altitude = norm(rVect) - bodyInfo.radius;
    presskPa = getPressureAtAltitude(bodyInfo, altitude);

    [~, totalThrust]= LaunchVehicleStateLogEntry.getTankMassFlowRatesDueToEngines(tankStates, tankMasses, stgStates, throttle, lvState, presskPa, ut, rVect, vVect, bodyInfo, [], storageSoCs, powerStorageStates, []);

    totalMass = (dryMass + sum(tankMasses))*1000; %kg
    totalThrust = totalThrust * 1000; % N

%     twRatio = computeSLThrustToWeight(bodyInfo, totalThrust, totalMass);
    twRatio = computeTrueThrustToWeight(bodyInfo, totalThrust, totalMass, altitude);
end


classdef TethaedraSubMeshConnecComputer < handle

    properties (Access = public)
        nSubCellNodes
        nSubCellsByElem
    end

    properties (Access = private)
        connecCase
    end

    properties (Access = private)
        nElemInCase
        cellNodes
    end

    methods (Access = public)

        function obj = TethaedraSubMeshConnecComputer(cParams)
            obj.init(cParams)
        end

        function compute(obj,nodes,icase)

            switch mode(size(nodes,2))
                case 7
                    obj.nSubCellsByElem = 4;
                case 8
                    obj.nSubCellsByElem = 6;
            end

            obj.nElemInCase = size(nodes,1);
            obj.cellNodes   = nodes;
            nodesC = zeros(obj.nSubCellsByElem,obj.nSubCellNodes,obj.nElemInCase);
            isActive = true(obj.nElemInCase,1);
            switch mode(size(nodes,2))
                case 7
                     [nodesT,nodesP] = obj.computeNodesTAndNodesP(icase);
                    for inode = 1:obj.nSubCellNodes
                        nodesC(1,inode,isActive) = nodesT(inode);
                        nodesC(2,inode,isActive) = nodesP(1,inode);
                        nodesC(3,inode,isActive) = nodesP(2,inode);
                        nodesC(4,inode,isActive) = nodesP(3,inode);
                    end
                case 8
                    nodesCC = obj.computeNodesFourCutNodes(icase);
                    for inode = 1:obj.nSubCellNodes
                        nodesC(1,inode,isActive) = nodesCC(1,inode);
                        nodesC(2,inode,isActive) = nodesCC(2,inode);
                        nodesC(3,inode,isActive) = nodesCC(3,inode);
                        nodesC(4,inode,isActive) = nodesCC(4,inode);
                        nodesC(5,inode,isActive) = nodesCC(5,inode);
                        nodesC(6,inode,isActive) = nodesCC(6,inode);
                    end

            end
            obj.connecCase = nodesC;
        end

        function nodePartition = partition(obj,nodes)
            connec = permute(obj.connecCase,[3 1 2]);
            nodePartition = obj.initNodePartition();
            nNodesSubCell = size(nodes,2);
            for isubcell = 1:obj.nSubCellsByElem
                for inode = 1:obj.nSubCellNodes
                    node = connec(:,isubcell,inode);
                    ind  = obj.computeAbsoluteMatrixIndex(node,nNodesSubCell);
                    nodePartition(inode,isubcell,:) = nodes(ind);
                end
            end
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.nSubCellNodes = 4;
        end

        function nodes = computeNodesFourCutNodes(obj,icase)

            switch icase
                case 3
                    nodes1 = obj.prismaTriangulation([1 5 6],[3 7 8]);
                    nodes2 = obj.prismaTriangulation([2 5 7],[4 6 8]);
                    nodes = [nodes1;nodes2];
                case 2
                    nodes1 = obj.prismaTriangulation([2 7 8],[1 5 6]);
                    nodes2 = obj.prismaTriangulation([5 3 7],[6 4 8]);
                    nodes = [nodes1;nodes2];
                case 1
                    nodes1 = obj.prismaTriangulation([4 7 8],[1 5 6]);
                    nodes2 = obj.prismaTriangulation([5 2 7],[6 3 8]);
                    nodes = [nodes1;nodes2];
            end

        end

        function [nodesT,nodesP] = computeNodesTAndNodesP(obj,icase)
            switch icase
                case 4
                    nodesT = [5 6 7 4];
                    nodesP = obj.prismaTriangulation([5 6 7],[1 2 3]);
                    %nodesP = [1 5 6 7;1 2 7 6;1 2 3 7];
                case 3
                    nodesP = [5 6 7 1 ;2 7 6 1;2 4 7 1 ];
                    nodesP = obj.prismaTriangulation([5 7 6],[1 4 2]);
                    nodesT = [5 7 6 3];

                    %nodesP = [1 5 7 6;1 4 6 7;1 4 2 6];
                    %nodesP  = [5 6 7 2;1 5 7 2;4 1 7 2];
                case 2
                    nodesT = [5 6 7 2];
%                    nodesP = [1 5 6 7;1 4 7 6;6 1 4 3];
                    nodesP = obj.prismaTriangulation([5 6 7],[1 3 4]);

                case 1
                    nodesT = [6 7 1 5];
%                    nodesP = [5 6 7 2;4 2 7 6;2 3 6 4];
                    nodesP = obj.prismaTriangulation([5 7 6],[2 4 3]);

            end

        end

       function nodes = prismaTriangulation2(obj,nodesA,nodesB)
             nodes =  [nodesA(1) nodesA(2) nodesA(3) nodesB(1);
                       nodesA(1) nodesA(2) nodesA(3) nodesB(2);
                       nodesA(1) nodesA(2) nodesA(3) nodesB(3)];
       end

        function nodes = prismaTriangulation(obj,nodesA,nodesB)
             nodes =  [nodesB(1) nodesA(1) nodesA(2) nodesA(3);
                       nodesB(1) nodesB(2) nodesA(3) nodesA(2);
                       nodesB(1) nodesB(2) nodesB(3) nodesA(3)];
        end

        function c = initNodePartition(obj)
            c = zeros(obj.nSubCellNodes,obj.nSubCellsByElem,obj.nElemInCase);
        end

        function ind = computeAbsoluteMatrixIndex(obj,colums,nNodesSubCell)
            nElem = obj.nElemInCase;
            rows = (1:nElem)';
            ind = sub2ind([nElem,nNodesSubCell],rows,colums);
        end

    end

end


function mObject3 = directSTRAIGHTmorphing(mObject1,mObject2,mRate,mixMethod);
%   Morphing based on direct mixing of STRAIGHT parameters
%   (Without time alignment)
%   mObject3 = directSTRAIGHTmorphing(mObject1,mObject2,mRate);

%   Designed and coded by Hideki Kawahara
%   27/Feb./2005
%   Copyright(c) 2005, Hideki Kawahara

if mObject1.samplingFrequency ~= mObject2.samplingFrequency
    mObject3 = [];
    return
end;
if mObject1.frameUpdateInterval ~= mObject2.frameUpdateInterval
    mObject3 = [];
    return
end;

nw1 = length(mObject1.F0);
nw2 = length(mObject2.F0);
[nr1,nc1] = size(mObject1.spectrogram);
[nr2,nc2] = size(mObject2.spectrogram);
nr3 = max(nr1,nr2);
nc3 = max(max(nc1,nc2),max(nw1,nw2));
nsg = zeros(nr3,nc3);
nSgram = zeros(nr3,nc3);
ap = zeros(nr3,nc3);
f0 = zeros(nc3);
nVoice = zeros(nc3);

switch mixMethod
    case 'linear'
        nsg(1:nr1,1:nc1) = (1-mRate)*mObject1.spectrogram;
        nSgram(1:nr1,1:nc1) = nSgram(1:nr1,1:nc1)+(1-mRate);
        nsg(1:nr2,1:nc2) = mRate*mObject2.spectrogram+nsg(1:nr2,1:nc2);
        nSgram(1:nr2,1:nc2) = nSgram(1:nr2,1:nc2)+mRate;
        nsg = nsg./nSgram;
    case 'log'
        nsg(1:nr1,1:nc1) = (1-mRate)*log(mObject1.spectrogram);
        nSgram(1:nr1,1:nc1) = nSgram(1:nr1,1:nc1)+(1-mRate);
        nsg(1:nr2,1:nc2) = mRate*log(mObject2.spectrogram)+nsg(1:nr2,1:nc2);
        nSgram(1:nr2,1:nc2) = nSgram(1:nr2,1:nc2)+mRate;
        nsg = exp(nsg./nSgram);
end;
ap(1:nr1,1:nc1) = (1-mRate)*mObject1.aperiodicityIndex;
ap(1:nr2,1:nc2) = mRate*mObject2.aperiodicityIndex+ap(1:nr2,1:nc2);

f0(mObject1.F0>0) = (1-mRate)*log(mObject1.F0(mObject1.F0>0));
nVoice(mObject1.F0>0) = nVoice(mObject1.F0>0)+(1-mRate);
f0(mObject2.F0>0) = mRate*log(mObject2.F0(mObject2.F0>0))+f0(mObject2.F0>0);
nVoice(mObject2.F0>0) = nVoice(mObject2.F0>0)+mRate;
f0(nVoice>0) = exp(f0(nVoice>0)./nVoice(nVoice>0));

mObject3 = createMobject;
mObject3 = updateFieldOfMobject(mObject3,'spectrogram',nsg);
mObject3 = updateFieldOfMobject(mObject3,'aperiodicityIndex',ap);
mObject3 = updateFieldOfMobject(mObject3,'F0',f0);


function self = reduce(self, waveType, sourcelat, sourcelon, stationlat, stationlon, varargin)
    % s.reduce('waveType', 'surface', 'waveSpeed', 2000, 'f', 2.0, );
    % s.distance and waveSpeed assumed to be in metres (m)
    % (INPUT) s.data assumed to be in nm or Pa
    % (OUTPUT) s.data in cm^2 or Pa.m

    % REQUIRES EXTRA PARAMETERS FOR RSAM OBJECTS
       %reduced = struct('Q', Inf, 'sourcelat', NaN, 'sourcelon', NaN, 'distance', NaN, 'waveType', '', 'isReduced', false, 'f', NaN, 'waveSpeed', NaN, 'stationlat', NaN, 'stationlon', NaN);
       %use = true;
%   REDUCED:    a structure that is set is data are "reduced", i.e. corrected
%               for geometric spreading (and possibly attenuation)
%               Has 4 fields:
%                   REDUCED.Q = the value of Q used to reduce the data
%                   (Inf by default, which indicates no attenuation)
%                   REDUCED.SOURCELAT = the latitude used for reducing the data
%                   REDUCED.SOURCELON = the longitude used for reducing the data
%                   REDUCED.STATIONLAT = the station latitude
%                   REDUCED.STATIONLON = the station longitude
%                   REDUCED.DISTANCE = the distance between source and
%                   station in km
%                   REDUCED.WAVETYPE = the wave type (body or surface)
%                   assumed
%                   REDUCED.F = the frequency used for surface waves
%                   REDUCED.WAVESPEED = the S wave speed
%                   REDUCED.ISREDUCED = True if the data are reduced
%   UNITS:  the units of the data, e.g. nm / sec.
%   USE: use this rsam object in plots?
    p = inputParser;
    p.addParameter('waveSpeed', 2000);
    p.addParamter('f', 2.0);
    p.parse(varargin{:});

    self.reduced.waveSpeed = p.Results.waveSpeed;

    if self.reduced.isReduced
        disp('Data are already reduced');
        return;
    end

    self.reduced.distance = deg2km(distance(sourcelat, sourcelon, stationlat, stationlon)) *1000; % m

    switch self.units
        case 'nm'  % Displacement
            % Do computation in cm
            self.data = self.data / 1e7;
            r = self.reduced.distance * 100; % cm
            ws = waveSpeed * 100; % cm/2
            self.measure = sprintf('%sR%s',self.measure(1),self.measure(2:end));
            switch self.reduced.waveType
                case 'body'
                    self.data = self.data * r; % cm^2
                    self.units = 'cm^2';
                case 'surface'
                    wavelength = ws / p.Results.f; % cm
                    try
                            self.data = self.data .* sqrt(r * wavelength); % cm^2
                    catch
                            debug.print_debug(5, 'mean wavelength instead')
                            self.data = self.data * sqrt(r * mean(wavelength)); % cm^2
                    end
                    self.units = 'cm^2';
                    self.reduced.isReduced = true;
                otherwise
                    error(sprintf('Wave type %s not recognised'), self.reduced.waveType);
            end
        case 'Pa'  % Pressure
            % Do computation in metres
            self.data = self.data * self.reduced.distance; % Pa.m
            self.units = 'Pa m';
            self.reduced.isReduced = true;
            self.measure = sprintf('%sR%s',self.measure(1),self.measure(2:end));
        otherwise
            error(sprintf('Units %s for measure %s not recognised', self.units, self.measure));
    end
    self.reduced.sourcelat = sourcelat;
    self.reduced.sourcelon = sourcelon;
    self.reduced.stationlat = stationlat;
    self.reduced.stationlon = stationlon;

end


function fact_test ( )

%*****************************************************************************80
%
%% FACT_TEST tests the use of the MEX file FACT.C
%
%  Discussion:
%
%    The file fact.c is a C function which computes the factorial.
%
%    This M file "compiles" fact.c, and then shows how it can be called.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 July 2006
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FACT_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Demonstrate a simple use of the MEX compiler,\n' );
  fprintf ( 1, '  which allows MATLAB to call C functions.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Get a directory listing.  The file FACT.C should be there.\n' );

  ls

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Compile the file FACT.C.\n' );

  mex fact.c

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Get a directory listing.  A new file should show up,\n' );
  fprintf ( 1, '  containing the compiled information.\n' );

  ls

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Now use FACT as though it were a MATLAB M-file function.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '   N  (N Factorial)\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 10

    j = fact ( i );

    fprintf ( 1, '  %2d  %10d\n', i, j );

  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FACT_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( )

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


function t_pf_ac(quiet)
%T_PF_AC  Tests for AC power flow solvers.

%   MATPOWER
%   Copyright (c) 2004-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if nargin < 1
    quiet = 0;
end

%%  alg         name                            check       opts
cfg = {
    {'NR',      'Newton (default, power-polar)',[]          []  },
    {'NR-SP',   'Newton (power-polar)',         [],         []  },
    {'NR-SC',   'Newton (power-cartesian)',     [],         []  },
    {'NR-SH',   'Newton (power-hybrid)',        [],         []  },
    {'NR-IP',   'Newton (current-polar)',       [],         []  },
    {'NR-IC',   'Newton (current-cartesian)',   [],         []  },
    {'NR-IH',   'Newton (current-hybrid)',      [],         []  },
    {'FDXB',    'Fast Decoupled (XB)',          [],         []  },
    {'FDBX',    'Fast Decoupled (BX)',          [],         []  },
    {'GS',      'Gauss-Seidel',                 [],         []  },
    {'ZG',      'Implicit Z-bus Gauss',         [],         []  },
};
if have_feature('mp_core')
    cfg{end+1} = {'FSOLVE',  'fsolve (power-polar)',         'fsolve',   []  };
    cfg{end+1} = {'FSOLVE',  'fsolve (power-cartesian)',     'fsolve',   {'pf.v_cartesian', 1}  };
    cfg{end+1} = {'FSOLVE',  'fsolve (current-polar)',       'fsolve',   {'pf.current_balance', 1, 'pf.tol', 1e-10}  };
    cfg{end+1} = {'FSOLVE',  'fsolve (current-cartesian)',   'fsolve',   {'pf.v_cartesian', 1, 'pf.current_balance', 1, 'pf.tol', 1e-10}  };
%     cfg{end+1} = {'FSOLVE',  'fsolve (power-polar)',         'fsolve',   struct('Algorithm', 'trust-region-dogleg')  },
%     cfg{end+1} = {'FSOLVE',  'fsolve (power-polar)',         'fsolve',   struct('Algorithm', 'trust-region-reflective')  },
%     cfg{end+1} = {'FSOLVE',  'fsolve (power-polar)',         'fsolve',   struct('Algorithm', 'levenberg-marquardt', 'TolX', 1e-11) },
end
% %%  alg         name                            check       opts
% cfg = {
%     {'NR',      'Newton (default, power-polar)',[]          []  },
% };

ntests = 48;
t_begin(length(cfg)*ntests + 6, quiet);

casefile = 't_case9_pf';
if quiet
    verbose = 0;
else
    verbose = 1;
end
if have_feature('octave')
    if have_feature('octave', 'vnum') >= 4
        file_in_path_warn_id = 'Octave:data-file-in-path';
    else
        file_in_path_warn_id = 'Octave:load-file-in-path';
    end
    s1 = warning('query', file_in_path_warn_id);
    warning('off', file_in_path_warn_id);
end
mpopt0 = mpoption('out.all', 0, 'pf.tol', 1e-9, 'verbose', 0);
mpopt0 = mpoption(mpopt0, 'verbose', verbose);

%% define named indices into bus, gen, branch matrices
[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;

%% network with islands
mpc0 = loadcase(casefile);
mpc0.gen(1, PG) = 60;
mpc0.gen(1, QG) = 10;
mpc0.gen(1, [PMIN PMAX QMIN QMAX PG QG]) = mpc0.gen(1, [PMIN PMAX QMIN QMAX PG QG]) / 2;
mpc0.gen = [mpc0.gen(1, :); mpc0.gen];
mpc1 = mpc0;
mpc  = mpc0;
nb = size(mpc.bus, 1);
mpc1.bus(:, BUS_I)      = mpc1.bus(:, BUS_I) + nb;
mpc1.branch(:, F_BUS)   = mpc1.branch(:, F_BUS) + nb;
mpc1.branch(:, T_BUS)   = mpc1.branch(:, T_BUS) + nb;
mpc1.gen(:, GEN_BUS)    = mpc1.gen(:, GEN_BUS) + nb;
mpc.bus         = [mpc.bus; mpc1.bus];
mpc.branch      = [mpc.branch; mpc1.branch];
mpc.gen         = [mpc.gen; mpc1.gen];
mpc1 = mpc;

%%-----  AC power flow  -----
%% get solved AC power flow case from MAT-file
load soln9_pf;      %% defines bus_soln, gen_soln, branch_soln
soln_vg = load('soln9_pf_vg');

%% run AC PF
for k = 1:length(cfg)
  if ~isempty(cfg{k}{3}) && ~have_fcn(cfg{k}{3})
    t_skip(ntests, sprintf('%s not available', cfg{k}{3}));
  else
    t = sprintf('AC PF - %s : ', cfg{k}{2});
    mpopt = mpoption(mpopt0, 'pf.alg', cfg{k}{1});
    if ~isempty(cfg{k}{4}) && iscell(cfg{k}{4})
        mpopt = mpoption(mpopt, cfg{k}{4}{:});
    end
    [baseMVA, bus, gen, branch, success, et] = runpf(casefile, mpopt);
    t_ok(success, [t 'success']);
    t_is(bus, bus_soln, 6, [t 'bus']);
    t_is(gen, gen_soln, 6, [t 'gen']);
    t_is(branch, branch_soln, 6, [t 'branch']);

    r = runpf(casefile, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.bus, bus_soln, 6, [t 'bus']);
    t_is(r.gen, gen_soln, 6, [t 'gen']);
    t_is(r.branch, branch_soln, 6, [t 'branch']);

    %% check when Vg ~= 1
    t = sprintf('%s - Vg ~= 1 : ', cfg{k}{1});
    mpopt = mpoption(mpopt, 'verbose', 0);
    mpc = loadcase(casefile);
    mpc.gen(:, VG) = [1.04; 1.025; 1.025];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.bus, soln_vg.bus_soln, 6, [t 'bus']);
    t_is(r.gen, soln_vg.gen_soln, 6, [t 'gen']);
    t_is(r.branch, soln_vg.branch_soln, 6, [t 'branch']);

    %% check Qg distribution, when Qmin = Qmax
    t = sprintf('%s - check Qg : ', cfg{k}{1});
    mpc = loadcase(casefile);
    mpc.gen(1, [QG QMIN QMAX]) = [10 20 20];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1, QG), 24.07, 2, [t 'single gen, Qmin = Qmax']);

    mpc.gen = [mpc.gen(1, :); mpc.gen];
    mpc.gen(1, [QMIN QMAX]) = [10 10];
    mpc.gen(2, [QMIN QMAX]) = [0 50];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [10; 14.07], 2, [t '2 gens, Qmin = Qmax for one']);

    mpc.gen(1, [QMIN QMAX]) = [10 10];
    mpc.gen(2, [QMIN QMAX]) = [-50 -50];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [42.03; -17.97], 2, [t '2 gens, Qmin = Qmax for both']);

    mpc.gen(1, [QMIN QMAX]) = [0 50];
    mpc.gen(2, [QMIN QMAX]) = [0 100];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [8.02; 16.05], 2, [t '2 gens, proportional']);

    mpc.gen(1, [QMIN QMAX]) = [-50 0];
    mpc.gen(2, [QMIN QMAX]) = [50 150];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [-50+8.02; 50+16.05], 2, [t '2 gens, proportional']);

    mpc.gen(1, [QMIN QMAX]) = [-50 Inf];
    mpc.gen(2, [QMIN QMAX]) = [50 150];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [-31.61; 55.68], 2, [t '2 gens, one infinite range']);

    mpc.gen(1, [QMIN QMAX]) = [-50 Inf];
    mpc.gen(2, [QMIN QMAX]) = [50 Inf];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [-33.12; 57.18], 2, [t '2 gens, both infinite range']);

    mpc.gen(1, [QMIN QMAX]) = [-50 Inf];
    mpc.gen(2, [QMIN QMAX]) = [-Inf 150];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [76.07; -52], 2, [t '2 gens, both infinite range']);

    mpc.gen(1, [QMIN QMAX]) = [-Inf Inf];
    mpc.gen(2, [QMIN QMAX]) = [-Inf Inf];
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(1:2, QG), [12.03; 12.03], 2, [t '2 gens, both infinite range']);

    t = sprintf('%s - reactive generation allocation : ', cfg{k}{1});
    mpc = loadcase(casefile);
    %% generator data
    %	bus	Pg	Qg	Qmax	Qmin	Vg	mBase	status	Pmax	Pmin	Pc1	Pc2	Qc1min	Qc1max	Qc2min	Qc2max	ramp_agc	ramp_10	ramp_30	ramp_q	apf
    mpc.gen = [
		1	0	0	300	-300	1	100	1	250	10	0	0	0	0	0	0	0	0	0	0	0;
		2	54	0	0	-5	1	100	1	300	10	0	0	0	0	0	0	0	0	0	0	0;
		2	54	0	5	-5	1	100	1	300	10	0	0	0	0	0	0	0	0	0	0	0;
		2	55	0	25	 10	1	100	1	300	10	0	0	0	0	0	0	0	0	0	0	0;
		30	25	1	300	-300	1	100	1	270	10	0	0	0	0	0	0	0	0	0	0	0;
		30	30	2	300	-300	1	100	1	270	10	0	0	0	0	0	0	0	0	0	0	0;
		30	30	-3	300	-300	1	100	1	270	10	0	0	0	0	0	0	0	0	0	0	0;
    ];
    mpc.bus(3, BUS_TYPE) = PQ;
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.gen(2:4, QG), [-5; -5; 10] + [1; 2; 3]*1.989129794, 7, [t 'PV bus']);
    t_is(r.gen(5:7, QG), [1; 2; -3], 8, [t 'PQ bus']);

    %% network with islands
    t = sprintf('%s - network w/islands : AC PF : ', cfg{k}{1});
    mpc = mpc1;
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.bus( 1:9,  VA), bus_soln(:, VA), 7, [t 'voltage angles 1']);
    t_is(r.bus(10:18, VA), bus_soln(:, VA), 7, [t 'voltage angles 2']);
    Pg = [gen_soln(1, PG)-30; 30; gen_soln(2:3, PG)];
    t_is(r.gen(1:4, PG), Pg, 6, [t 'active power generation 1']);
    t_is(r.gen(5:8, PG), Pg, 6, [t 'active power generation 2']);

    t = sprintf('%s - all buses isolated : ', cfg{k}{1});
    mpc.bus(:, BUS_TYPE) = NONE;
    try
        r = runpf(mpc, mpopt);
        t_is(r.success, 0, 12, [t 'success = 0']);
    catch
        t_ok(0, [t 'unexpected fatal error']);
    end

    %% case 14 with Q limits
    t = sprintf('%s - pf.enforce_q_lims == 0 : ', cfg{k}{1});
    mpc = loadcase('case14');
    mpc.gen(1, QMIN) = -10;
    mpc.gen(:, QMAX) = [10; 30; 29; 15; 15];
    bt0 = mpc.bus(:, BUS_TYPE);
    bt = bt0;
    mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 0);
    r = runpf(mpc, mpopt);
    t_ok(r.success, [t 'success']);
    t_is(r.bus(:, BUS_TYPE), bt, 12, [t 'bus type']);
    t_is(r.gen(:, QG), [-16.549300542; 43.557100134; 25.075348495; 12.730944405; 17.623451366], 6, [t 'Qg']);

    t = sprintf('%s - pf.enforce_q_lims == 1 : ', cfg{k}{1});
    mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 1);
    r = runpf(mpc, mpopt);
    bt = bt0;
    bt([1 2 3 8]) = [PQ PQ REF PQ];
    t_is(r.success, 0, 12, [t 'success = 0']);
    t_is(r.bus(:, BUS_TYPE), bt, 12, [t 'bus type']);
    t_is(r.gen(:, QG), [-10; 30; 31.608422873; 16.420423190; 15], 4, [t 'Qg']);

    t = sprintf('%s - pf.enforce_q_lims == 2 : ', cfg{k}{1});
    mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 2);
    r = runpf(mpc, mpopt);
    bt = bt0;
    bt([1 2 3 6 8]) = [REF PQ PQ PQ PQ];
    t_ok(r.success, [t 'success']);
    t_is(r.bus(:, BUS_TYPE), bt, 12, [t 'bus type']);
    t_is(r.gen(:, QG), [-6.30936644; 30; 29; 15; 15], 5, [t 'Qg']);
  end
end

t = sprintf('%s - pf.enforce_q_lims == 1 : ', 'NR-SP');
mpopt = mpoption(mpopt, 'pf.alg', 'NR-SP', 'pf.tol', 1e-9);
mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 1);
r = runpf('case14', mpopt);
t_ok(r.success, [t 'success']);
t_is(r.iterations, 5, 12, [t 'iterations']);
t_is(r.bus(1, VA), 0, 12, [t 'ref bus Va = 0']);

t = sprintf('%s - pf.enforce_q_lims == 1 : ', 'NR-IC');
mpopt = mpoption(mpopt, 'pf.alg', 'NR-SP', 'pf.tol', 1e-9);
mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 1);
r = runpf('case14', mpopt);
t_ok(r.success, [t 'success']);
t_is(r.iterations, 5, 12, [t 'iterations']);
t_is(r.bus(1, VA), 0, 12, [t 'ref bus Va = 0']);

t_end;

if have_feature('octave')
    warning(s1.state, file_in_path_warn_id);
end


% SP_TO_VTK: Export to VTK format for plotting.
%
%  sp_to_vtk (u, space, geometry, npts, filename, fieldname, [options], [lambda_lame, mu_lame])
%  sp_to_vtk (u, space, geometry, pts, filename, fieldname, [options], [lambda_lame, mu_lame])
%
% INPUT:
%
%     u:           vector of dof weights
%     space:       object representing the space of discrete functions (see sp_scalar)
%     geometry:    geometry structure (see geo_load)
%     npts:        number of points along each parametric direction where to evaluate
%     pts:         cell array with the coordinates along each parametric direction of the points where to evaluate
%     filename:    name of the output file.
%     fieldnames:  how to name the saved variables in the vtk file
%     options:     cell array with the fields to plot
%                   accepted options are 'value' (default), 'gradient',
%                   and for vectors also 'curl', 'divergence', 'stress'
%     lambda_lame: function handle to the first Lame coefficient (only needed to compute 'stress')
%     mu_lame:     function handle for the second Lame coefficient (only needed to compute 'stress')
%
% OUTPUT:
%
%    none
%
% Copyright (C) 2009, 2010 Carlo de Falco
% Copyright (C) 2011, 2012, 2015 Rafael Vazquez
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.

%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.

function sp_to_vtk (u, space, geometry, npts, filename, fieldname, varargin)

  [eu, F] = sp_eval (u, space, geometry, npts, varargin{:});

  msh_to_vtk (F, eu, filename, fieldname);

end


function sF = mrdivide(sF,s)
% overload the / operator, i.e. one can now write @S2Fun / 2  in order
% to scale an S2Fun.
%
% Syntax
%   sF = sF / 2
%
% Input
%  sF - @S2Fun
%  s  - constant, vector
%
% Output
%  sF - @S2Fun
%

if ~isnumeric(s)
  error('Second argument has to be numeric. Use ./ instead.')
end

sF = times(sF,inv(s));

end


function [cm3] = ml2cm3(ml)
% Convert volume from milliliters to cubic centimeters.
% Chad Greene 2012
cm3 = ml;


function x=SeamPut(x,SeamVector)
% SEAMPUT takes as input a RGB or grayscale image and SeamVector array to
% find the pixels contained in the seam, and to adds a seam of interpolated
% pixels to the image. Each column of SeamVector must be a single seam.
%
% Author: Danny Luong
%         http://danluong.com
%
% Last updated: 12/20/07

[rows cols dim]=size(x);
[SVrows SVcols SVdim]=size(SeamVector);

if rows~=SVrows
    error('SeamVector and image dimension mismatch');
end

for k=1:SVcols
    for i=1:dim
        for j=1:rows
            if SeamVector(j,k)==1
                PutImg(j,:,i)=[x(j,1,i) x(j,1:cols,i)];
            elseif SeamVector(j,k)==cols
                PutImg(j,:,i)=[x(j,1:cols,i) x(j,cols,i)];
            else
                PutImg(j,:,i)=[x(j,1:SeamVector(j,k),i) 1/2*(x(j,SeamVector(j,k),i)+x(j,SeamVector(j,k)+1,i)) x(j,SeamVector(j,k)+1:cols,i)];
            end
        end
    end
    x=PutImg;
    clear PutImg
    [rows cols dim]=size(x);
end


function mtrTrackVis2PDB(volFile, trkFile, pdbFile)

% File format conversion from the .trk file format (TrackVis) to pdb files
%
% Parameters
% ----------
% volFile: A full-path to a nifti file, from which the qform will be read
% trkFile: The trk file to be converted.
% pdbFile: The output.
%
% Returns
% -------
% Nothing.

% Load vol file to get AcPc xform
vol = niftiRead(volFile);
xformTo = vol.qto_xyz;
xformFrom = abs(vol.qto_ijk);
xformFrom(1:3,4)=0;
xformToAcPc = xformTo*xformFrom;

% Get mm dimensions of image
dim_mm = vol.dim(:).*abs(diag(vol.qto_xyz(1:3,1:3)));
clear vol;

% Load trks file
fg = read_trk_to_fg(trkFile);

% Remove really short fibers (<10 points)
%fg = dtiCleanFibers(fg, [], [], 11)

fg = dtiXformFiberCoords(fg,xformToAcPc);
fg = dtiClearQuenchStats(fg);
fg = dtiCreateQuenchStats(fg,'Length','Length', 1);
mtrExportFibers(fg,pdbFile,eye(4));

return;