deal.II version GIT relicensing-2173-gae8fc9d14b 2024-11-24 06:40:00+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
step-78.h
Go to the documentation of this file.
1) const
598 *   {
599 *   #ifdef MMS
600 *   return -Utilities::fixed_power<2, double>(this->get_time()) + 6;
601 *   #else
602 *   return 0.;
603 *   #endif
604 *   }
605 *  
606 *  
607 *  
608 * @endcode
609 *
610 * Then, we handle the right boundary condition.
611 *
612 * @code
613 *   template <int dim>
614 *   class RightBoundaryValues : public Function<dim>
615 *   {
616 *   public:
617 *   RightBoundaryValues(const double strike_price, const double interest_rate);
618 *  
619 *   virtual double value(const Point<dim> &p,
620 *   const unsigned int component = 0) const override;
621 *  
622 *   private:
623 *   const double strike_price;
624 *   const double interest_rate;
625 *   };
626 *  
627 *  
628 *   template <int dim>
629 *   RightBoundaryValues<dim>::RightBoundaryValues(const double strike_price,
630 *   const double interest_rate)
631 *   : strike_price(strike_price)
632 *   , interest_rate(interest_rate)
633 *   {}
634 *  
635 *  
636 *   template <int dim>
637 *   double RightBoundaryValues<dim>::value(const Point<dim> &p,
638 *   const unsigned int component) const
639 *   {
640 *   #ifdef MMS
641 *   return -Utilities::fixed_power<2, double>(p[component]) -
642 *   Utilities::fixed_power<2, double>(this->get_time()) + 6;
643 *   #else
644 *   return (p[component] - strike_price) *
645 *   exp((-interest_rate) * (this->get_time()));
646 *   #endif
647 *   }
648 *  
649 *  
650 *  
651 * @endcode
652 *
653 * Finally, we handle the right hand side.
654 *
655 * @code
656 *   template <int dim>
657 *   class RightHandSide : public Function<dim>
658 *   {
659 *   public:
660 *   RightHandSide(const double asset_volatility, const double interest_rate);
661 *  
662 *   virtual double value(const Point<dim> &p,
663 *   const unsigned int component = 0) const override;
664 *  
665 *   private:
666 *   const double asset_volatility;
667 *   const double interest_rate;
668 *   };
669 *  
670 *  
671 *   template <int dim>
672 *   RightHandSide<dim>::RightHandSide(const double asset_volatility,
673 *   const double interest_rate)
674 *   : asset_volatility(asset_volatility)
675 *   , interest_rate(interest_rate)
676 *   {}
677 *  
678 *  
679 *   template <int dim>
680 *   double RightHandSide<dim>::value(const Point<dim> &p,
681 *   const unsigned int component) const
682 *   {
683 *   #ifdef MMS
684 *   return 2 * (this->get_time()) -
685 *   Utilities::fixed_power<2, double>(asset_volatility * p[component]) -
686 *   2 * interest_rate * Utilities::fixed_power<2, double>(p[component]) -
687 *   interest_rate *
688 *   (-Utilities::fixed_power<2, double>(p[component]) -
689 *   Utilities::fixed_power<2, double>(this->get_time()) + 6);
690 *   #else
691 *   (void)p;
692 *   (void)component;
693 *   return 0.0;
694 *   #endif
695 *   }
696 *  
697 *  
698 *  
699 * @endcode
700 *
701 *
702 * <a name="step_78-ThecodeBlackScholescodeClass"></a>
703 * <h3>The <code>BlackScholes</code> Class</h3>
704 *
705
706 *
707 * The next piece is the declaration of the main class of this program. This
708 * is very similar to the @ref step_26 "step-26" tutorial, with some modifications. New
709 * matrices had to be added to calculate the A and B matrices, as well as the
710 * @f$V_{diff}@f$ vector mentioned in the introduction. We also define the
711 * parameters used in the problem.
712 *
713
714 *
715 * - <code>maximum_stock_price</code>: The imposed upper bound on the spatial
716 * domain. This is the maximum allowed stock price.
717 * - <code>maturity_time</code>: The upper bound on the time domain. This is
718 * when the option expires.\n
719 * - <code>asset_volatility</code>: The volatility of the stock price.\n
720 * - <code>interest_rate</code>: The risk free interest rate.\n
721 * - <code>strike_price</code>: The agreed upon price that the buyer will
722 * have the option of purchasing the stocks at the expiration time.
723 *
724
725 *
726 * Some slight differences between this program and @ref step_26 "step-26" are the creation
727 * of the <code>a_matrix</code> and the <code>b_matrix</code>, which is
728 * described in the introduction. We then also need to store the current time,
729 * the size of the time step, and the number of the current time step.
730 * Next, we will store the output into a <code>DataOutStack</code>
731 * variable because we will be layering the solution at each time on top of
732 * one another to create the solution manifold. Then, we have a variable that
733 * stores the current cycle and number of cycles that we will run when
734 * calculating the solution. The cycle is one full solution calculation given
735 * a mesh. We refine the mesh once in between each cycle to exhibit the
736 * convergence properties of our program. Finally, we store the convergence
737 * data into a convergence table.
738 *
739
740 *
741 * As far as member functions are concerned, we have a function that
742 * calculates the convergence information for each cycle, called
743 * <code>process_solution</code>. This is just like what is done in @ref step_7 "step-7".
744 *
745 * @code
746 *   template <int dim>
747 *   class BlackScholes
748 *   {
749 *   public:
750 *   BlackScholes();
751 *  
752 *   void run();
753 *  
754 *   private:
755 *   void setup_system();
756 *   void solve_time_step();
757 *   void refine_grid();
758 *   void process_solution();
759 *   void add_results_for_output();
760 *   void write_convergence_table();
761 *  
762 *   const double maximum_stock_price;
763 *   const double maturity_time;
764 *   const double asset_volatility;
765 *   const double interest_rate;
766 *   const double strike_price;
767 *  
769 *   const FE_Q<dim> fe;
770 *   DoFHandler<dim> dof_handler;
771 *  
772 *   AffineConstraints<double> constraints;
773 *  
774 *   SparsityPattern sparsity_pattern;
776 *   SparseMatrix<double> laplace_matrix;
777 *   SparseMatrix<double> a_matrix;
778 *   SparseMatrix<double> b_matrix;
779 *   SparseMatrix<double> system_matrix;
780 *  
781 *   Vector<double> solution;
782 *   Vector<double> system_rhs;
783 *  
784 *   double time;
785 *   double time_step;
786 *  
787 *   const double theta;
788 *   const unsigned int n_cycles;
789 *   const unsigned int n_time_steps;
790 *  
791 *   DataOutStack<dim> data_out_stack;
792 *   std::vector<std::string> solution_names;
793 *  
794 *   ConvergenceTable convergence_table;
795 *   };
796 *  
797 * @endcode
798 *
799 *
800 * <a name="step_78-ThecodeBlackScholescodeImplementation"></a>
801 * <h3>The <code>BlackScholes</code> Implementation</h3>
802 *
803
804 *
805 * Now, we get to the implementation of the main class. We will set the values
806 * for the various parameters used in the problem. These were chosen because
807 * they are fairly normal values for these parameters. Although the stock
808 * price has no upper bound in reality (it is in fact infinite), we impose
809 * an upper bound that is twice the strike price. This is a somewhat arbitrary
810 * choice to be twice the strike price, but it is large enough to see the
811 * interesting parts of the solution.
812 *
813 * @code
814 *   template <int dim>
815 *   BlackScholes<dim>::BlackScholes()
816 *   : maximum_stock_price(1.)
817 *   , maturity_time(1.)
818 *   , asset_volatility(.2)
819 *   , interest_rate(0.05)
820 *   , strike_price(0.5)
821 *   , fe(1)
822 *   , dof_handler(triangulation)
823 *   , time(0.0)
824 *   , theta(0.5)
825 *   , n_cycles(4)
826 *   , n_time_steps(5000)
827 *   {
828 *   Assert(dim == 1, ExcNotImplemented());
829 *   }
830 *  
831 * @endcode
832 *
833 *
834 * <a name="step_78-codeBlackScholessetup_systemcode"></a>
835 * <h4><code>BlackScholes::setup_system</code></h4>
836 *
837
838 *
839 * The next function sets up the DoFHandler object, computes
840 * the constraints, and sets the linear algebra objects to their correct
841 * sizes. We also compute the @ref GlossMassMatrix "mass matrix" here by calling a function from the
842 * library. We will compute the other 3 matrices next, because these need to
843 * be computed 'by hand'.
844 *
845
846 *
847 * Note, that the time step is initialized here because the maturity time was
848 * needed to compute the time step.
849 *
850 * @code
851 *   template <int dim>
852 *   void BlackScholes<dim>::setup_system()
853 *   {
854 *   dof_handler.distribute_dofs(fe);
855 *  
856 *   time_step = maturity_time / n_time_steps;
857 *  
858 *   constraints.clear();
859 *   DoFTools::make_hanging_node_constraints(dof_handler, constraints);
860 *   constraints.close();
861 *   DynamicSparsityPattern dsp(dof_handler.n_dofs());
862 *   DoFTools::make_sparsity_pattern(dof_handler,
863 *   dsp,
864 *   constraints,
865 *   /*keep_constrained_dofs = */ true);
866 *   sparsity_pattern.copy_from(dsp);
867 *  
868 *   mass_matrix.reinit(sparsity_pattern);
869 *   laplace_matrix.reinit(sparsity_pattern);
870 *   a_matrix.reinit(sparsity_pattern);
871 *   b_matrix.reinit(sparsity_pattern);
872 *   system_matrix.reinit(sparsity_pattern);
873 *  
874 *   MatrixCreator::create_mass_matrix(dof_handler,
875 *   QGauss<dim>(fe.degree + 1),
876 *   mass_matrix);
877 *  
878 * @endcode
879 *
880 * Below is the code to create the Laplace matrix with non-constant
881 * coefficients. This corresponds to the matrix D in the introduction. This
882 * non-constant coefficient is represented in the
883 * <code>current_coefficient</code> variable.
884 *
885 * @code
886 *   const unsigned int dofs_per_cell = fe.dofs_per_cell;
887 *   FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);
888 *   const QGauss<dim> quadrature_formula(fe.degree + 1);
889 *   FEValues<dim> fe_values(fe,
890 *   quadrature_formula,
893 *   std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
894 *   for (const auto &cell : dof_handler.active_cell_iterators())
895 *   {
896 *   cell_matrix = 0.;
897 *   fe_values.reinit(cell);
898 *   for (const unsigned int q_index : fe_values.quadrature_point_indices())
899 *   {
900 *   const double current_coefficient =
901 *   fe_values.quadrature_point(q_index).square();
902 *   for (const unsigned int i : fe_values.dof_indices())
903 *   {
904 *   for (const unsigned int j : fe_values.dof_indices())
905 *   cell_matrix(i, j) +=
906 *   (current_coefficient * // (x_q)^2
907 *   fe_values.shape_grad(i, q_index) * // grad phi_i(x_q)
908 *   fe_values.shape_grad(j, q_index) * // grad phi_j(x_q)
909 *   fe_values.JxW(q_index)); // dx
910 *   }
911 *   }
912 *   cell->get_dof_indices(local_dof_indices);
913 *   for (const unsigned int i : fe_values.dof_indices())
914 *   {
915 *   for (const unsigned int j : fe_values.dof_indices())
916 *   laplace_matrix.add(local_dof_indices[i],
917 *   local_dof_indices[j],
918 *   cell_matrix(i, j));
919 *   }
920 *   }
921 *  
922 * @endcode
923 *
924 * Now we will create the A matrix. Below is the code to create the matrix A
925 * as discussed in the introduction. The non constant coefficient is again
926 * represented in the <code>current_coefficient</code> variable.
927 *
928 * @code
929 *   for (const auto &cell : dof_handler.active_cell_iterators())
930 *   {
931 *   cell_matrix = 0.;
932 *   fe_values.reinit(cell);
933 *   for (const unsigned int q_index : fe_values.quadrature_point_indices())
934 *   {
935 *   const Tensor<1, dim> current_coefficient =
936 *   fe_values.quadrature_point(q_index);
937 *   for (const unsigned int i : fe_values.dof_indices())
938 *   {
939 *   for (const unsigned int j : fe_values.dof_indices())
940 *   {
941 *   cell_matrix(i, j) +=
942 *   (current_coefficient * // x_q
943 *   fe_values.shape_grad(i, q_index) * // grad phi_i(x_q)
944 *   fe_values.shape_value(j, q_index) * // phi_j(x_q)
945 *   fe_values.JxW(q_index)); // dx
946 *   }
947 *   }
948 *   }
949 *   cell->get_dof_indices(local_dof_indices);
950 *   for (const unsigned int i : fe_values.dof_indices())
951 *   {
952 *   for (const unsigned int j : fe_values.dof_indices())
953 *   a_matrix.add(local_dof_indices[i],
954 *   local_dof_indices[j],
955 *   cell_matrix(i, j));
956 *   }
957 *   }
958 *  
959 * @endcode
960 *
961 * Finally we will create the matrix B. Below is the code to create the
962 * matrix B as discussed in the introduction. The non constant coefficient
963 * is again represented in the <code>current_coefficient</code> variable.
964 *
965 * @code
966 *   for (const auto &cell : dof_handler.active_cell_iterators())
967 *   {
968 *   cell_matrix = 0.;
969 *   fe_values.reinit(cell);
970 *   for (const unsigned int q_index : fe_values.quadrature_point_indices())
971 *   {
972 *   const Tensor<1, dim> current_coefficient =
973 *   fe_values.quadrature_point(q_index);
974 *   for (const unsigned int i : fe_values.dof_indices())
975 *   {
976 *   for (const unsigned int j : fe_values.dof_indices())
977 *   cell_matrix(i, j) +=
978 *   (current_coefficient * // x_q
979 *   fe_values.shape_value(i, q_index) * // phi_i(x_q)
980 *   fe_values.shape_grad(j, q_index) * // grad phi_j(x_q)
981 *   fe_values.JxW(q_index)); // dx
982 *   }
983 *   }
984 *   cell->get_dof_indices(local_dof_indices);
985 *   for (const unsigned int i : fe_values.dof_indices())
986 *   {
987 *   for (const unsigned int j : fe_values.dof_indices())
988 *   b_matrix.add(local_dof_indices[i],
989 *   local_dof_indices[j],
990 *   cell_matrix(i, j));
991 *   }
992 *   }
993 *  
994 *   solution.reinit(dof_handler.n_dofs());
995 *   system_rhs.reinit(dof_handler.n_dofs());
996 *   }
997 *  
998 * @endcode
999 *
1000 *
1001 * <a name="step_78-codeBlackScholessolve_time_stepcode"></a>
1002 * <h4><code>BlackScholes::solve_time_step</code></h4>
1003 *
1004
1005 *
1006 * The next function is the one that solves the actual linear system for a
1007 * single time step. The only interesting thing here is that the matrices
1008 * we have built are symmetric positive definite, so we can use the
1009 * conjugate gradient method.
1010 *
1011 * @code
1012 *   template <int dim>
1013 *   void BlackScholes<dim>::solve_time_step()
1014 *   {
1015 *   SolverControl solver_control(1000, 1e-12);
1016 *   SolverCG<Vector<double>> cg(solver_control);
1017 *   PreconditionSSOR<SparseMatrix<double>> preconditioner;
1018 *   preconditioner.initialize(system_matrix, 1.0);
1019 *   cg.solve(system_matrix, solution, system_rhs, preconditioner);
1020 *   constraints.distribute(solution);
1021 *   }
1022 *  
1023 * @endcode
1024 *
1025 *
1026 * <a name="step_78-codeBlackScholesadd_results_for_outputcode"></a>
1027 * <h4><code>BlackScholes::add_results_for_output</code></h4>
1028 *
1029
1030 *
1031 * This is simply the function to stitch the solution pieces together. For
1032 * this, we create a new layer at each time, and then add the solution vector
1033 * for that timestep. The function then stitches this together with the old
1034 * solutions using 'build_patches'.
1035 *
1036 * @code
1037 *   template <int dim>
1038 *   void BlackScholes<dim>::add_results_for_output()
1039 *   {
1040 *   data_out_stack.new_parameter_value(time, time_step);
1041 *   data_out_stack.attach_dof_handler(dof_handler);
1042 *   data_out_stack.add_data_vector(solution, solution_names);
1043 *   data_out_stack.build_patches(2);
1044 *   data_out_stack.finish_parameter_value();
1045 *   }
1046 *  
1047 * @endcode
1048 *
1049 *
1050 * <a name="step_78-codeBlackScholesrefine_gridcode"></a>
1051 * <h4><code>BlackScholes::refine_grid</code></h4>
1052 *
1053
1054 *
1055 * It is somewhat unnecessary to have a function for the global refinement
1056 * that we do. The reason for the function is to allow for the possibility of
1057 * an adaptive refinement later.
1058 *
1059 * @code
1060 *   template <int dim>
1061 *   void BlackScholes<dim>::refine_grid()
1062 *   {
1063 *   triangulation.refine_global(1);
1064 *   }
1065 *  
1066 * @endcode
1067 *
1068 *
1069 * <a name="step_78-codeBlackScholesprocess_solutioncode"></a>
1070 * <h4><code>BlackScholes::process_solution</code></h4>
1071 *
1072
1073 *
1074 * This is where we calculate the convergence and error data to evaluate the
1075 * effectiveness of the program. Here, we calculate the @f$L^2@f$, @f$H^1@f$ and
1076 * @f$L^{\infty}@f$ norms.
1077 *
1078 * @code
1079 *   template <int dim>
1080 *   void BlackScholes<dim>::process_solution()
1081 *   {
1082 *   Solution<dim> sol(maturity_time);
1083 *   sol.set_time(time);
1084 *   Vector<float> difference_per_cell(triangulation.n_active_cells());
1085 *   VectorTools::integrate_difference(dof_handler,
1086 *   solution,
1087 *   sol,
1088 *   difference_per_cell,
1089 *   QGauss<dim>(fe.degree + 1),
1090 *   VectorTools::L2_norm);
1091 *   const double L2_error =
1092 *   VectorTools::compute_global_error(triangulation,
1093 *   difference_per_cell,
1094 *   VectorTools::L2_norm);
1095 *   VectorTools::integrate_difference(dof_handler,
1096 *   solution,
1097 *   sol,
1098 *   difference_per_cell,
1099 *   QGauss<dim>(fe.degree + 1),
1100 *   VectorTools::H1_seminorm);
1101 *   const double H1_error =
1102 *   VectorTools::compute_global_error(triangulation,
1103 *   difference_per_cell,
1104 *   VectorTools::H1_seminorm);
1105 *   const QTrapezoid<1> q_trapezoid;
1106 *   const QIterated<dim> q_iterated(q_trapezoid, fe.degree * 2 + 1);
1107 *   VectorTools::integrate_difference(dof_handler,
1108 *   solution,
1109 *   sol,
1110 *   difference_per_cell,
1111 *   q_iterated,
1112 *   VectorTools::Linfty_norm);
1113 *   const double Linfty_error =
1114 *   VectorTools::compute_global_error(triangulation,
1115 *   difference_per_cell,
1116 *   VectorTools::Linfty_norm);
1117 *   const unsigned int n_active_cells = triangulation.n_active_cells();
1118 *   const unsigned int n_dofs = dof_handler.n_dofs();
1119 *   convergence_table.add_value("cells", n_active_cells);
1120 *   convergence_table.add_value("dofs", n_dofs);
1121 *   convergence_table.add_value("L2", L2_error);
1122 *   convergence_table.add_value("H1", H1_error);
1123 *   convergence_table.add_value("Linfty", Linfty_error);
1124 *   }
1125 *  
1126 * @endcode
1127 *
1128 *
1129 * <a name="step_78-codeBlackScholeswrite_convergence_tablecode"></a>
1130 * <h4><code>BlackScholes::write_convergence_table</code> </h4>
1131 *
1132
1133 *
1134 * This next part is building the convergence and error tables. By this, we
1135 * need to set the settings for how to output the data that was calculated
1136 * during <code>BlackScholes::process_solution</code>. First, we will create
1137 * the headings and set up the cells properly. During this, we will also
1138 * prescribe the precision of our results. Then we will write the calculated
1139 * errors based on the @f$L^2@f$, @f$H^1@f$, and @f$L^{\infty}@f$ norms to the console and
1140 * to the error LaTeX file.
1141 *
1142 * @code
1143 *   template <int dim>
1144 *   void BlackScholes<dim>::write_convergence_table()
1145 *   {
1146 *   convergence_table.set_precision("L2", 3);
1147 *   convergence_table.set_precision("H1", 3);
1148 *   convergence_table.set_precision("Linfty", 3);
1149 *   convergence_table.set_scientific("L2", true);
1150 *   convergence_table.set_scientific("H1", true);
1151 *   convergence_table.set_scientific("Linfty", true);
1152 *   convergence_table.set_tex_caption("cells", "\\# cells");
1153 *   convergence_table.set_tex_caption("dofs", "\\# dofs");
1154 *   convergence_table.set_tex_caption("L2", "@fL^2@f-error");
1155 *   convergence_table.set_tex_caption("H1", "@fH^1@f-error");
1156 *   convergence_table.set_tex_caption("Linfty", "@fL^\\infty@f-error");
1157 *   convergence_table.set_tex_format("cells", "r");
1158 *   convergence_table.set_tex_format("dofs", "r");
1159 *   std::cout << std::endl;
1160 *   convergence_table.write_text(std::cout);
1161 *   std::string error_filename = "error";
1162 *   error_filename += "-global";
1163 *   error_filename += ".tex";
1164 *   std::ofstream error_table_file(error_filename);
1165 *   convergence_table.write_tex(error_table_file);
1166 *  
1167 * @endcode
1168 *
1169 * Next, we will make the convergence table. We will again write this to
1170 * the console and to the convergence LaTeX file.
1171 *
1172 * @code
1173 *   convergence_table.add_column_to_supercolumn("cells", "n cells");
1174 *   std::vector<std::string> new_order;
1175 *   new_order.emplace_back("n cells");
1176 *   new_order.emplace_back("H1");
1177 *   new_order.emplace_back("L2");
1178 *   convergence_table.set_column_order(new_order);
1179 *   convergence_table.evaluate_convergence_rates(
1180 *   "L2", ConvergenceTable::reduction_rate);
1181 *   convergence_table.evaluate_convergence_rates(
1182 *   "L2", ConvergenceTable::reduction_rate_log2);
1183 *   convergence_table.evaluate_convergence_rates(
1184 *   "H1", ConvergenceTable::reduction_rate);
1185 *   convergence_table.evaluate_convergence_rates(
1186 *   "H1", ConvergenceTable::reduction_rate_log2);
1187 *   std::cout << std::endl;
1188 *   convergence_table.write_text(std::cout);
1189 *   std::string conv_filename = "convergence";
1190 *   conv_filename += "-global";
1191 *   switch (fe.degree)
1192 *   {
1193 *   case 1:
1194 *   conv_filename += "-q1";
1195 *   break;
1196 *   case 2:
1197 *   conv_filename += "-q2";
1198 *   break;
1199 *   default:
1200 *   DEAL_II_NOT_IMPLEMENTED();
1201 *   }
1202 *   conv_filename += ".tex";
1203 *   std::ofstream table_file(conv_filename);
1204 *   convergence_table.write_tex(table_file);
1205 *   }
1206 *  
1207 * @endcode
1208 *
1209 *
1210 * <a name="step_78-codeBlackScholesruncode"></a>
1211 * <h4><code>BlackScholes::run</code></h4>
1212 *
1213
1214 *
1215 * Now we get to the main driver of the program. This is where we do all the
1216 * work of looping through the time steps and calculating the solution vector
1217 * each time. Here at the top, we set the initial refinement value and then
1218 * create a mesh. Then we refine this mesh once. Next, we set up the
1219 * data_out_stack object to store our solution. Finally, we start a for loop
1220 * to loop through the cycles. This lets us recalculate a solution for each
1221 * successive mesh refinement. At the beginning of each iteration, we need to
1222 * reset the time and time step number. We introduce an if statement to
1223 * accomplish this because we don't want to do this on the first iteration.
1224 *
1225 * @code
1226 *   template <int dim>
1227 *   void BlackScholes<dim>::run()
1228 *   {
1229 *   GridGenerator::hyper_cube(triangulation, 0.0, maximum_stock_price, true);
1230 *   triangulation.refine_global(0);
1231 *  
1232 *   solution_names.emplace_back("u");
1233 *   data_out_stack.declare_data_vector(solution_names,
1235 *  
1236 *   Vector<double> vmult_result;
1237 *   Vector<double> forcing_terms;
1238 *  
1239 *   for (unsigned int cycle = 0; cycle < n_cycles; ++cycle)
1240 *   {
1241 *   if (cycle != 0)
1242 *   {
1243 *   refine_grid();
1244 *   time = 0.0;
1245 *   }
1246 *  
1247 *   setup_system();
1248 *  
1249 *   std::cout << std::endl
1250 *   << "===========================================" << std::endl
1251 *   << "Cycle " << cycle << ':' << std::endl
1252 *   << "Number of active cells: "
1253 *   << triangulation.n_active_cells() << std::endl
1254 *   << "Number of degrees of freedom: " << dof_handler.n_dofs()
1255 *   << std::endl
1256 *   << std::endl;
1257 *  
1258 *   VectorTools::interpolate(dof_handler,
1259 *   InitialConditions<dim>(strike_price),
1260 *   solution);
1261 *  
1262 *   if (cycle == (n_cycles - 1))
1263 *   {
1264 *   add_results_for_output();
1265 *   }
1266 *  
1267 * @endcode
1268 *
1269 * Next, we run the main loop which runs until we exceed the maturity
1270 * time. We first compute the right hand side of the equation, which is
1271 * described in the introduction. Recall that it contains the term
1272 * @f$\left[-\frac{1}{4}k_n\sigma^2\mathbf{D}-k_nr\mathbf{M}+k_n\sigma^2
1273 * \mathbf{B}-k_nr\mathbf{A}+\mathbf{M}\right]V^{n-1}@f$. We put these
1274 * terms into the variable system_rhs, with the help of a temporary
1275 * vector:
1276 *
1277 * @code
1278 *   vmult_result.reinit(dof_handler.n_dofs());
1279 *   forcing_terms.reinit(dof_handler.n_dofs());
1280 *   for (unsigned int timestep_number = 0; timestep_number < n_time_steps;
1281 *   ++timestep_number)
1282 *   {
1283 *   time += time_step;
1284 *  
1285 *   if (timestep_number % 1000 == 0)
1286 *   std::cout << "Time step " << timestep_number << " at t=" << time
1287 *   << std::endl;
1288 *  
1289 *   mass_matrix.vmult(system_rhs, solution);
1290 *  
1291 *   laplace_matrix.vmult(vmult_result, solution);
1292 *   system_rhs.add(
1293 *   (-1) * (1 - theta) * time_step *
1294 *   Utilities::fixed_power<2, double>(asset_volatility) * 0.5,
1295 *   vmult_result);
1296 *   mass_matrix.vmult(vmult_result, solution);
1297 *  
1298 *   system_rhs.add((-1) * (1 - theta) * time_step * interest_rate * 2,
1299 *   vmult_result);
1300 *  
1301 *   a_matrix.vmult(vmult_result, solution);
1302 *   system_rhs.add((-1) * time_step * interest_rate, vmult_result);
1303 *  
1304 *   b_matrix.vmult(vmult_result, solution);
1305 *   system_rhs.add(
1306 *   (-1) * Utilities::fixed_power<2, double>(asset_volatility) *
1307 *   time_step * 1,
1308 *   vmult_result);
1309 *  
1310 * @endcode
1311 *
1312 * The second piece is to compute the contributions of the source
1313 * terms. This corresponds to the term @f$-k_n\left[\frac{1}{2}F^{n-1}
1314 * +\frac{1}{2}F^n\right]@f$. The following code calls
1315 * VectorTools::create_right_hand_side to compute the vectors @f$F@f$,
1316 * where we set the time of the right hand side (source) function
1317 * before we evaluate it. The result of this all ends up in the
1318 * forcing_terms variable:
1319 *
1320 * @code
1321 *   RightHandSide<dim> rhs_function(asset_volatility, interest_rate);
1322 *   rhs_function.set_time(time);
1323 *   VectorTools::create_right_hand_side(dof_handler,
1324 *   QGauss<dim>(fe.degree + 1),
1325 *   rhs_function,
1326 *   forcing_terms);
1327 *   forcing_terms *= time_step * theta;
1328 *   system_rhs -= forcing_terms;
1329 *  
1330 *   rhs_function.set_time(time - time_step);
1331 *   VectorTools::create_right_hand_side(dof_handler,
1332 *   QGauss<dim>(fe.degree + 1),
1333 *   rhs_function,
1334 *   forcing_terms);
1335 *   forcing_terms *= time_step * (1 - theta);
1336 *   system_rhs -= forcing_terms;
1337 *  
1338 * @endcode
1339 *
1340 * Next, we add the forcing terms to the ones that come from the
1341 * time stepping, and also build the matrix @f$\left[\mathbf{M}+
1342 * \frac{1}{4}k_n\sigma^2\mathbf{D}+k_nr\mathbf{M}\right]@f$ that we
1343 * have to invert in each time step. The final piece of these
1344 * operations is to eliminate hanging node constrained degrees of
1345 * freedom from the linear system:
1346 *
1347 * @code
1348 *   system_matrix.copy_from(mass_matrix);
1349 *   system_matrix.add(
1350 *   (theta)*time_step *
1351 *   Utilities::fixed_power<2, double>(asset_volatility) * 0.5,
1352 *   laplace_matrix);
1353 *   system_matrix.add((time_step)*interest_rate * theta * (1 + 1),
1354 *   mass_matrix);
1355 *  
1356 *   constraints.condense(system_matrix, system_rhs);
1357 *  
1358 * @endcode
1359 *
1360 * There is one more operation we need to do before we can solve it:
1361 * boundary values. To this end, we create a boundary value object,
1362 * set the proper time to the one of the current time step, and
1363 * evaluate it as we have done many times before. The result is used
1364 * to also set the correct boundary values in the linear system:
1365 *
1366 * @code
1367 *   {
1368 *   RightBoundaryValues<dim> right_boundary_function(strike_price,
1369 *   interest_rate);
1370 *   LeftBoundaryValues<dim> left_boundary_function;
1371 *   right_boundary_function.set_time(time);
1372 *   left_boundary_function.set_time(time);
1373 *   std::map<types::global_dof_index, double> boundary_values;
1375 *   0,
1376 *   left_boundary_function,
1377 *   boundary_values);
1379 *   1,
1380 *   right_boundary_function,
1381 *   boundary_values);
1382 *   MatrixTools::apply_boundary_values(boundary_values,
1383 *   system_matrix,
1384 *   solution,
1385 *   system_rhs);
1386 *   }
1387 *  
1388 * @endcode
1389 *
1390 * With this out of the way, all we have to do is solve the system,
1391 * generate graphical data on the last cycle, and create the
1392 * convergence table data.
1393 *
1394 * @code
1395 *   solve_time_step();
1396 *  
1397 *   if (cycle == (n_cycles - 1))
1398 *   {
1399 *   add_results_for_output();
1400 *   }
1401 *   }
1402 *   #ifdef MMS
1403 *   process_solution();
1404 *   #endif
1405 *   }
1406 *  
1407 *   const std::string filename = "solution.vtk";
1408 *   std::ofstream output(filename);
1409 *   data_out_stack.write_vtk(output);
1410 *  
1411 *   #ifdef MMS
1412 *   write_convergence_table();
1413 *   #endif
1414 *   }
1415 *  
1416 *   } // namespace BlackScholesSolver
1417 *  
1418 * @endcode
1419 *
1420 *
1421 * <a name="step_78-ThecodemaincodeFunction"></a>
1422 * <h3>The <code>main</code> Function</h3>
1423 *
1424
1425 *
1426 * Having made it this far, there is, again, nothing much to discuss for the
1427 * main function of this program: it looks like all such functions since @ref step_6 "step-6".
1428 *
1429 * @code
1430 *   int main()
1431 *   {
1432 *   try
1433 *   {
1434 *   using namespace BlackScholesSolver;
1435 *  
1436 *   BlackScholes<1> black_scholes_solver;
1437 *   black_scholes_solver.run();
1438 *   }
1439 *   catch (std::exception &exc)
1440 *   {
1441 *   std::cerr << std::endl
1442 *   << std::endl
1443 *   << "----------------------------------------------------"
1444 *   << std::endl;
1445 *   std::cerr << "Exception on processing: " << std::endl
1446 *   << exc.what() << std::endl
1447 *   << "Aborting!" << std::endl
1448 *   << "----------------------------------------------------"
1449 *   << std::endl;
1450 *   return 1;
1451 *   }
1452 *   catch (...)
1453 *   {
1454 *   std::cerr << std::endl
1455 *   << std::endl
1456 *   << "----------------------------------------------------"
1457 *   << std::endl;
1458 *   std::cerr << "Unknown exception!" << std::endl
1459 *   << "Aborting!" << std::endl
1460 *   << "----------------------------------------------------"
1461 *   << std::endl;
1462 *   return 1;
1463 *   }
1464 *   return 0;
1465 *   }
1466 * @endcode
1467<a name="step_78-Results"></a><h1>Results</h1>
1468
1469
1470
1471Below is the output of the program:
1472@code
1473===========================================
1474Number of active cells: 1
1475Number of degrees of freedom: 2
1476
1477Time step 0 at t=0.0002
1478[...]
1479
1480Cycle 7:
1481Number of active cells: 128
1482Number of degrees of freedom: 129
1483
1484Time step 0 at t=0.0002
1485Time step 1000 at t=0.2002
1486Time step 2000 at t=0.4002
1487Time step 3000 at t=0.6002
1488Time step 4000 at t=0.8002
1489
1490cells dofs L2 H1 Linfty
1491 1 2 1.667e-01 5.774e-01 2.222e-01
1492 2 3 3.906e-02 2.889e-01 5.380e-02
1493 4 5 9.679e-03 1.444e-01 1.357e-02
1494 8 9 2.405e-03 7.218e-02 3.419e-03
1495 16 17 5.967e-04 3.609e-02 8.597e-04
1496 32 33 1.457e-04 1.804e-02 2.155e-04
1497 64 65 3.307e-05 9.022e-03 5.388e-05
1498 128 129 5.016e-06 4.511e-03 1.342e-05
1499
1500n cells H1 L2
1501 1 5.774e-01 - - 1.667e-01 - -
1502 2 2.889e-01 2.00 1.00 3.906e-02 4.27 2.09
1503 4 1.444e-01 2.00 1.00 9.679e-03 4.04 2.01
1504 8 7.218e-02 2.00 1.00 2.405e-03 4.02 2.01
1505 16 3.609e-02 2.00 1.00 5.967e-04 4.03 2.01
1506 32 1.804e-02 2.00 1.00 1.457e-04 4.10 2.03
1507 64 9.022e-03 2.00 1.00 3.307e-05 4.41 2.14
1508 128 4.511e-03 2.00 1.00 5.016e-06 6.59 2.72
1509@endcode
1510
1511What is more interesting is the output of the convergence tables. They are
1512outputted into the console, as well into a LaTeX file. The convergence tables
1513are shown above. Here, you can see that the solution has a convergence rate
1514of @f$\mathcal{O}(h)@f$ with respect to the @f$H^1@f$-norm, and the solution has a convergence rate
1515of @f$\mathcal{O}(h^2)@f$ with respect to the @f$L^2@f$-norm.
1516
1517
1518Below is the visualization of the solution.
1519
1520<div style="text-align:center;">
1521 <img src="https://www.dealii.org/images/steps/developer/step-78.mms-solution.png"
1522 alt="Solution of the MMS problem.">
1523</div>
1524 *
1525 *
1526<a name="step_78-PlainProg"></a>
1527<h1> The plain program</h1>
1528@include "step-78.cc"
1529*/
void distribute_dofs(const FiniteElement< dim, spacedim > &fe)
Definition fe_q.h:554
virtual RangeNumberType value(const Point< dim > &p, const unsigned int component=0) const
Definition point.h:111
void initialize(const MatrixType &A, const AdditionalData &parameters=AdditionalData())
Point< 2 > second
Definition grid_out.cc:4624
Point< 2 > first
Definition grid_out.cc:4623
#define Assert(cond, exc)
void loop(IteratorType begin, std_cxx20::type_identity_t< IteratorType > end, DOFINFO &dinfo, INFOBOX &info, const std::function< void(std_cxx20::type_identity_t< DOFINFO > &, typename INFOBOX::CellInfo &)> &cell_worker, const std::function< void(std_cxx20::type_identity_t< DOFINFO > &, typename INFOBOX::CellInfo &)> &boundary_worker, const std::function< void(std_cxx20::type_identity_t< DOFINFO > &, std_cxx20::type_identity_t< DOFINFO > &, typename INFOBOX::CellInfo &, typename INFOBOX::CellInfo &)> &face_worker, AssemblerType &assembler, const LoopControl &lctrl=LoopControl())
Definition loop.h:564
void make_hanging_node_constraints(const DoFHandler< dim, spacedim > &dof_handler, AffineConstraints< number > &constraints)
void make_sparsity_pattern(const DoFHandler< dim, spacedim > &dof_handler, SparsityPatternBase &sparsity_pattern, const AffineConstraints< number > &constraints={}, const bool keep_constrained_dofs=true, const types::subdomain_id subdomain_id=numbers::invalid_subdomain_id)
@ update_values
Shape function values.
@ update_JxW_values
Transformed quadrature weights.
@ update_gradients
Shape function gradients.
@ update_quadrature_points
Transformed quadrature points.
std::vector< index_type > data
Definition mpi.cc:735
std::size_t size
Definition mpi.cc:734
void hyper_cube(Triangulation< dim, spacedim > &tria, const double left=0., const double right=1., const bool colorize=false)
void refine(Triangulation< dim, spacedim > &tria, const Vector< Number > &criteria, const double threshold, const unsigned int max_to_mark=numbers::invalid_unsigned_int)
@ matrix
Contents is actually a matrix.
@ symmetric
Matrix is symmetric.
void cell_matrix(FullMatrix< double > &M, const FEValuesBase< dim > &fe, const FEValuesBase< dim > &fetest, const ArrayView< const std::vector< double > > &velocity, const double factor=1.)
Definition advection.h:74
double norm(const FEValuesBase< dim > &fe, const ArrayView< const std::vector< Tensor< 1, dim > > > &Du)
Definition divergence.h:471
void L2(Vector< number > &result, const FEValuesBase< dim > &fe, const std::vector< double > &input, const double factor=1.)
Definition l2.h:159
void mass_matrix(FullMatrix< double > &M, const FEValuesBase< dim > &fe, const double factor=1.)
Definition l2.h:57
void create_mass_matrix(const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof, const Quadrature< dim > &q, MatrixType &matrix, const Function< spacedim, typename MatrixType::value_type > *const a=nullptr, const AffineConstraints< typename MatrixType::value_type > &constraints=AffineConstraints< typename MatrixType::value_type >())
void apply_boundary_values(const std::map< types::global_dof_index, number > &boundary_values, SparseMatrix< number > &matrix, Vector< number > &solution, Vector< number > &right_hand_side, const bool eliminate_columns=true)
Tensor< 2, dim, Number > F(const Tensor< 2, dim, Number > &Grad_u)
VectorType::value_type * end(VectorType &V)
std::string get_time()
void interpolate(const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof, const Function< spacedim, typename VectorType::value_type > &function, VectorType &vec, const ComponentMask &component_mask={}, const unsigned int level=numbers::invalid_unsigned_int)
void interpolate_boundary_values(const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof, const std::map< types::boundary_id, const Function< spacedim, number > * > &function_map, std::map< types::global_dof_index, number > &boundary_values, const ComponentMask &component_mask={})
void create_right_hand_side(const Mapping< dim, spacedim > &mapping, const DoFHandler< dim, spacedim > &dof, const Quadrature< dim > &q, const Function< spacedim, typename VectorType::value_type > &rhs, VectorType &rhs_vector, const AffineConstraints< typename VectorType::value_type > &constraints=AffineConstraints< typename VectorType::value_type >())
void run(const Iterator &begin, const std_cxx20::type_identity_t< Iterator > &end, Worker worker, Copier copier, const ScratchData &sample_scratch_data, const CopyData &sample_copy_data, const unsigned int queue_length, const unsigned int chunk_size)
int(&) functions(const void *v1, const void *v2)
::VectorizedArray< Number, width > exp(const ::VectorizedArray< Number, width > &)
const ::parallel::distributed::Triangulation< dim, spacedim > * triangulation
DEAL_II_HOST constexpr SymmetricTensor< 2, dim, Number > invert(const SymmetricTensor< 2, dim, Number > &)