From 14a297b604fc257c1a6bf799fedf0da768df0093 Mon Sep 17 00:00:00 2001 From: guanjihuan Date: Wed, 9 Jun 2021 04:38:18 +0800 Subject: [PATCH] update --- README.md | 1 + .../1D_graphene.py | 69 ++++ .../2D_graphene.py | 66 ++++ .../1D_Haldane_model.py | 94 +++++ .../2D_Haldane_model.py | 70 ++++ ...tance_calculation_using_Green_functions.py | 101 +++++ ...he_relation_between_eigenstates_and_DOS.py | 43 +++ .../big_mass_in_one_body/step_0.1.py | 114 ++++++ .../step_0.05.py | 110 ++++++ .../step_0.1.py | 110 ++++++ .../step_0.05.py | 113 ++++++ .../step_0.1.py | 113 ++++++ ...ite_integration_with_Monte_Carlo_method.py | 73 ++++ .../Hamiltonian_of_square_lattice_in_kwant.py | 56 +++ .../kwant_example.py | 94 +++++ .../bands_in_quasi_1D_BHZ_systems.py | 84 ++++ .../Metropolis_sampling_example_1.py | 33 ++ .../Metropolis_sampling_example_2.m | 18 + .../Ising_model.py | 97 +++++ ...ulating_magnetic_moments_in_Ising_model.py | 76 ++++ .../create_GIF_with_python.py | 11 + ...lculation of spectral function and QPI.f90 | 160 ++++++++ ...alculation of spectral function and QPI.py | 158 ++++++++ .../bands_of_qusi_1D_square_lattice.py | 48 +++ .../calculation_of_local_currents.py | 130 +++++++ ...ion_of_Chern_number_by_definition_method.m | 50 +++ ...on_of_Chern_number_by_definition_method.py | 70 ++++ ...smooth_gauge_and_calculate_Chern_number.py | 108 ++++++ ...tion_of_Chern_number_by_efficient_method.m | 40 ++ ...ion_of_Chern_number_by_efficient_method.py | 65 ++++ ..._bilayer_graphene_with_label_sequence_1.py | 69 ++++ ..._bilayer_graphene_with_label_sequence_2.py | 83 ++++ ..._a_function_of_Fermi_energy_in_graphene.py | 56 +++ ...ction_of_Fermi_energy_in_square_lattice.py | 52 +++ ...rify_Green_functions_in_Dyson_equations.py | 84 ++++ ...le_model_without considering_Rashba_SOC.py | 104 +++++ .../Chern_number_in_Haldane_model.py | 91 +++++ ...n_Haldane_model_by_integration_method_2.py | 87 +++++ ...n_Haldane_model_by_integration_method_3.py | 95 +++++ .../Winding_number_in_SSH_model.py | 41 ++ .../bands_of_SSH_model.py | 42 ++ .../form_of_direct_assigning.py | 23 ++ .../form_of_tensor_product.py | 21 + .../plot_with_2D_data.py | 30 ++ .../write_2D_data_into_txt_file.py | 31 ++ .../get_eigenvalues_and_plot_1D_bands.py | 35 ++ .../get_eigenvalues_and_plot_2D_bands.py | 47 +++ ...nvalues_and_write_1D_data_into_txt_file.py | 31 ++ ...nvalues_and_write_2D_data_into_txt_file.py | 42 ++ .../python_structure.py | 7 + .../read_txt_file/1D_data.txt | 4 + .../read_txt_file/2D_data.txt | 4 + .../read_txt_file/read_1D_data.py | 47 +++ .../read_txt_file/read_2D_data.py | 69 ++++ ...running_and_write_2D_data_into_txt_file.py | 18 + .../Z2_invariant_in_BHZ_model.m | 68 ++++ .../Z2_invariant_in_BHZ_model.py | 88 +++++ .../spin_Chern_number_in_BHZ_model.py | 98 +++++ .../Fermi_arc_in_Weyl_semimetals.py | 64 ++++ .../bands_of_Weyl_semimetals.py | 67 ++++ ...ture_of_graphene_on_high_symmetric_axes.py | 77 ++++ ...attering_matrix_by_mode_matching_method.py | 240 ++++++++++++ .../time_complexity_dealing_with_matrix.py | 61 +++ ..._cross_section_plane_in_Weyl_semimetals.py | 83 ++++ ..._of_Weyl_semimetal_after_discretization.py | 66 ++++ ...same_gauge_numerically_by_binary_search.py | 114 ++++++ .../function_form.py | 39 ++ .../plot_2D_scatter.py | 34 ++ .../plot_3D_scatter.py | 40 ++ .../plot_3D_surface.py | 44 +++ .../plot_contour.py | 42 ++ .../plot_line.py | 30 ++ ..._using_Dyson_equations_in_cubic_lattice.py | 102 +++++ ...n_equations_in_cubic_lattice_version_II.py | 99 +++++ ...erseion_of_Hamiltonian_of_cubic_lattice.py | 49 +++ ...using_Dyson_equations_in_square_lattice.py | 95 +++++ ...rseion_of_Hamiltonian_of_square_lattice.py | 41 ++ .../Hofstadter_butterfly_in_square_lattice.py | 50 +++ ...graphene_under_broken_inversion_symmery.py | 151 ++++++++ ...nder_broken_inversion_symmery_with_ky=0.py | 114 ++++++ .../python_code_for_data_processing.py | 322 ++++++++++++++++ ...del_of_high_order_topological_insulator.py | 103 +++++ ...pological_insulator_plotting_3D_surface.py | 100 +++++ ...quantum_transport_in_multi_lead_systems.py | 179 +++++++++ .../Wilson_loop_in_SSH_model.py | 68 ++++ ...lson_loop_in_SSH_model_with_better_code.py | 53 +++ ..._Hamiltonian_composed_of_Pauli_matrices.nb | 81 ++++ .../bands_of_type_II_Weyl_semimetals.py | 89 +++++ .../example_Eigenvectors.nb | 73 ++++ .../example_eig.m | 3 + .../example_geev.f90 | 40 ++ .../example_hermitian_matrix.py | 21 + .../example_numpy.linalg.eig.py | 18 + .../example_real_symmetric_matrix.py | 21 + .../example_real_symmetric_matrix2.py | 32 ++ .../Schmidt_orthogonalization.py | 44 +++ .../graphene.py | 40 ++ .../square.py | 35 ++ .../twist_graphene.py | 73 ++++ ..._of_Kronecker_product_of_Pauli_matrices.py | 48 +++ ..._of_Kronecker_product_of_Pauli_matrices.py | 44 +++ .../python_example.py | 76 ++++ .../tensorflow.py | 39 ++ .../neutral_network_with_tensorflow.py | 77 ++++ .../ball_games_with_pygame.py | 359 ++++++++++++++++++ .../stock_date_from_tushare.py | 106 ++++++ .../matlab_example.m | 41 ++ .../2019.10.31_0_fortran_example/Console1.f90 | 164 ++++++++ .../Console1.f90 | 78 ++++ .../markdown_example.md | 33 ++ .../basic_structure.tex | 6 + .../simple_example.tex | 18 + .../2019.12.05_beamer_as_slides/1.jpg | Bin 0 -> 18074 bytes .../2019.12.05_beamer_as_slides/beamer.tex | 50 +++ .../parallel_calculations_with_python.py | 41 ++ .../BeautifulSoup.py | 47 +++ .../download_from_sci_hub_with_python.py | 45 +++ ...ad_references_in_a_pdf_file_with_python.py | 77 ++++ .../get_links_from_a_pdf_file.py | 30 ++ .../run_programs_sequentially.py | 21 + .../find_key_words_in_pdf_files.py | 137 +++++++ .../get_content_in_a_pdf_file.py | 63 +++ .../a.py | 29 ++ .../a.sh | 5 + .../combine.py | 6 + .../results/a0.txt | 16 + .../results/a1.txt | 16 + .../results/a2.txt | 16 + .../results/a3.txt | 16 + .../results/a4.txt | 16 + .../results/a5.txt | 16 + .../results/a6.txt | 4 + .../results/combine.txt | 100 +++++ .../task.sh | 14 + ...ind_directory_with_file_number_not_eq_3.py | 24 ++ .../find_common_words_on_APS.py | 89 +++++ ...service_watching_recent_at_regular_time.py | 59 +++ 137 files changed, 8965 insertions(+) create mode 100755 README.md create mode 100755 academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/1D_graphene.py create mode 100755 academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/2D_graphene.py create mode 100755 academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/1D_Haldane_model.py create mode 100755 academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/2D_Haldane_model.py create mode 100755 academic_codes/2019.11.01_conductance_calculation_using_Green_functions/conductance_calculation_using_Green_functions.py create mode 100755 academic_codes/2019.11.02_numerically_verify_the_relation_between_eigenstates_and_DOS/numerically_verify_the_relation_between_eigenstates_and_DOS.py create mode 100755 academic_codes/2019.11.03_three_body_moving_on_2D_space/big_mass_in_one_body/step_0.1.py create mode 100755 academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.05.py create mode 100755 academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.1.py create mode 100755 academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.05.py create mode 100755 academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.1.py create mode 100755 academic_codes/2019.11.07_definite_integration_with_Monte_Carlo_method/definite_integration_with_Monte_Carlo_method.py create mode 100755 academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/Hamiltonian_of_square_lattice_in_kwant.py create mode 100755 academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/kwant_example.py create mode 100755 academic_codes/2019.11.27_Hamiltonian_of_BHZ_model_and_bands_in_quasi_1D_systems/bands_in_quasi_1D_BHZ_systems.py create mode 100755 academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_1.py create mode 100755 academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_2.m create mode 100755 academic_codes/2019.12.01_1_simulation_of_Ising_model_with_Monte_Carlo_method/Ising_model.py create mode 100755 academic_codes/2019.12.01_1_simulation_of_Ising_model_with_Monte_Carlo_method/get_the_transition_temperature_by_calculating_magnetic_moments_in_Ising_model.py create mode 100755 academic_codes/2019.12.03_create_GIF_with_python/create_GIF_with_python.py create mode 100755 academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.f90 create mode 100755 academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.py create mode 100755 academic_codes/2020.01.03_0_bands_of_qusi_1D_square_lattice/bands_of_qusi_1D_square_lattice.py create mode 100755 academic_codes/2020.01.03_1_calculation_of_local_currents/calculation_of_local_currents.py create mode 100755 academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.m create mode 100755 academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.py create mode 100755 academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/find_smooth_gauge_and_calculate_Chern_number.py create mode 100755 academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.m create mode 100755 academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.py create mode 100755 academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_1.py create mode 100755 academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_2.py create mode 100755 academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_graphene.py create mode 100755 academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_square_lattice.py create mode 100755 academic_codes/2020.06.25_numerically_verify_Green_functions_in_Dyson_equations/numerically_verify_Green_functions_in_Dyson_equations.py create mode 100755 academic_codes/2020.06.26_Hamiltonian_and_bands_of_Kane_Mele_model_without considering_Rashba_SOC/bands_of_quasi_1D_Kane_Mele_model_without considering_Rashba_SOC.py create mode 100755 academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model.py create mode 100755 academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_2.py create mode 100755 academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_3.py create mode 100755 academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/Winding_number_in_SSH_model.py create mode 100755 academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/bands_of_SSH_model.py create mode 100755 academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_direct_assigning.py create mode 100755 academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_tensor_product.py create mode 100755 academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/plot_with_2D_data.py create mode 100755 academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/write_2D_data_into_txt_file.py create mode 100755 academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_1D_bands.py create mode 100755 academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_2D_bands.py create mode 100755 academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_1D_data_into_txt_file.py create mode 100755 academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_2D_data_into_txt_file.py create mode 100755 academic_codes/2020.08.29_several_python_functions/python_structure.py create mode 100755 academic_codes/2020.08.29_several_python_functions/read_txt_file/1D_data.txt create mode 100755 academic_codes/2020.08.29_several_python_functions/read_txt_file/2D_data.txt create mode 100755 academic_codes/2020.08.29_several_python_functions/read_txt_file/read_1D_data.py create mode 100755 academic_codes/2020.08.29_several_python_functions/read_txt_file/read_2D_data.py create mode 100755 academic_codes/2020.08.29_several_python_functions/running_and_write_2D_data_into_txt_file.py create mode 100755 academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.m create mode 100755 academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.py create mode 100755 academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/spin_Chern_number_in_BHZ_model.py create mode 100755 academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/Fermi_arc_in_Weyl_semimetals.py create mode 100755 academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/bands_of_Weyl_semimetals.py create mode 100755 academic_codes/2020.09.30_bandstructure_of_graphene_on_high_symmetric_axes/bandstructure_of_graphene_on_high_symmetric_axes.py create mode 100755 academic_codes/2020.10.02_calculate_scattering_matrix_by_mode_matching_method/calculate_scattering_matrix_by_mode_matching_method.py create mode 100755 academic_codes/2020.10.30_time_complexity_dealing_with_matrix/time_complexity_dealing_with_matrix.py create mode 100755 academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/Chern_number_of_the_cross_section_plane_in_Weyl_semimetals.py create mode 100755 academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/bands_of_Weyl_semimetal_after_discretization.py create mode 100755 academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/find_the_same_gauge_numerically_by_binary_search.py create mode 100755 academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/function_form.py create mode 100755 academic_codes/2020.12.23_plot_with_matplotlib/plot_2D_scatter.py create mode 100755 academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_scatter.py create mode 100755 academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_surface.py create mode 100755 academic_codes/2020.12.23_plot_with_matplotlib/plot_contour.py create mode 100755 academic_codes/2020.12.23_plot_with_matplotlib/plot_line.py create mode 100755 academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice.py create mode 100755 academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice_version_II.py create mode 100755 academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_cubic_lattice.py create mode 100755 academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/DOS_calculation_using_Dyson_equations_in_square_lattice.py create mode 100755 academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_square_lattice.py create mode 100755 academic_codes/2021.01.07_Hofstadter_butterfly_in_square_lattice/Hofstadter_butterfly_in_square_lattice.py create mode 100755 academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery.py create mode 100755 academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery_with_ky=0.py create mode 100755 academic_codes/2021.01.13_python_code_for_data_processing/python_code_for_data_processing.py create mode 100755 academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator.py create mode 100755 academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator_plotting_3D_surface.py create mode 100755 academic_codes/2021.02.08_quantum_transport_in_multi_lead_systems/quantum_transport_in_multi_lead_systems.py create mode 100755 academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model.py create mode 100755 academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model_with_better_code.py create mode 100755 academic_codes/2021.03.08_eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices/eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices.nb create mode 100755 academic_codes/2021.03.10_bands_of_type_II_Weyl_semimetals/bands_of_type_II_Weyl_semimetals.py create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_Eigenvectors.nb create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_eig.m create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_geev.f90 create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_hermitian_matrix.py create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_numpy.linalg.eig.py create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix.py create mode 100755 academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix2.py create mode 100755 academic_codes/2021.03.19_Schmidt_orthogonalization/Schmidt_orthogonalization.py create mode 100755 academic_codes/2021.03.19_plot_twist_graphene_with_python/graphene.py create mode 100755 academic_codes/2021.03.19_plot_twist_graphene_with_python/square.py create mode 100755 academic_codes/2021.03.19_plot_twist_graphene_with_python/twist_graphene.py create mode 100755 academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/eigenvalue_of_Kronecker_product_of_Pauli_matrices.py create mode 100755 academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/test2_eigenvalue_of_Kronecker_product_of_Pauli_matrices.py create mode 100755 language_learning/2019.10.10_python_example/python_example.py create mode 100755 language_learning/2019.10.11_0_tensorflow_example/tensorflow.py create mode 100755 language_learning/2019.10.11_1_neutral_network_with_tensorflow/neutral_network_with_tensorflow.py create mode 100755 language_learning/2019.10.27_0_ball_games_with_pygame/ball_games_with_pygame.py create mode 100755 language_learning/2019.10.27_1_stock_date_from_tushare/stock_date_from_tushare.py create mode 100755 language_learning/2019.10.29_matlab_example/matlab_example.m create mode 100755 language_learning/2019.10.31_0_fortran_example/Console1.f90 create mode 100755 language_learning/2019.10.31_1_parallel_calculations_with_OpenMP/Console1.f90 create mode 100755 language_learning/2019.11.16_markdown_example/markdown_example.md create mode 100755 language_learning/2019.12.04_latex_example/basic_structure.tex create mode 100755 language_learning/2019.12.04_latex_example/simple_example.tex create mode 100755 language_learning/2019.12.05_beamer_as_slides/1.jpg create mode 100755 language_learning/2019.12.05_beamer_as_slides/beamer.tex create mode 100755 language_learning/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python.py create mode 100755 language_learning/2020.10.17_0_web_scraping_with_BeautifulSoup/BeautifulSoup.py create mode 100755 language_learning/2020.10.31_0_download_from_sci_hub_with_python/download_from_sci_hub_with_python.py create mode 100755 language_learning/2020.10.31_1_download_references_in_a_pdf_file_with_python/download_references_in_a_pdf_file_with_python.py create mode 100755 language_learning/2020.10.31_1_download_references_in_a_pdf_file_with_python/get_links_from_a_pdf_file.py create mode 100755 language_learning/2021.01.18_run_programs_sequentially/run_programs_sequentially.py create mode 100755 language_learning/2021.01.23_find_key_words_in_pdf_files_with_pdfminer/find_key_words_in_pdf_files.py create mode 100755 language_learning/2021.01.23_find_key_words_in_pdf_files_with_pdfminer/get_content_in_a_pdf_file.py create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/a.py create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/a.sh create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/combine.py create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a0.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a1.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a2.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a3.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a4.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a5.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/a6.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/results/combine.txt create mode 100755 language_learning/2021.05.10_parallel_calculations_using_sh_files/task.sh create mode 100755 language_learning/2021.05.14_zotero/find_directory_with_file_number_not_eq_3.py create mode 100755 language_learning/2021.06.07_find_common_words_on_APS/find_common_words_on_APS.py create mode 100755 language_learning/2021.06.07_find_common_words_on_APS/service_watching_recent_at_regular_time.py diff --git a/README.md b/README.md new file mode 100755 index 0000000..a099cd3 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +### Website: https://www.guanjihuan.com \ No newline at end of file diff --git a/academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/1D_graphene.py b/academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/1D_graphene.py new file mode 100755 index 0000000..324f378 --- /dev/null +++ b/academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/1D_graphene.py @@ -0,0 +1,69 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/408 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k, N, M, t1): # Haldane哈密顿量(N是条带的宽度参数) + # 初始化为零矩阵 + h00 = np.zeros((4*N, 4*N), dtype=complex) + h01 = np.zeros((4*N, 4*N), dtype=complex) + + # 原胞内的跃迁h00 + for i in range(N): + h00[i*4+0, i*4+0] = M + h00[i*4+1, i*4+1] = -M + h00[i*4+2, i*4+2] = M + h00[i*4+3, i*4+3] = -M + + # 最近邻 + h00[i*4+0, i*4+1] = t1 + h00[i*4+1, i*4+0] = t1 + h00[i*4+1, i*4+2] = t1 + h00[i*4+2, i*4+1] = t1 + h00[i*4+2, i*4+3] = t1 + h00[i*4+3, i*4+2] = t1 + for i in range(N-1): + # 最近邻 + h00[i*4+3, (i+1)*4+0] = t1 + h00[(i+1)*4+0, i*4+3] = t1 + + # 原胞间的跃迁h01 + for i in range(N): + # 最近邻 + h01[i*4+1, i*4+0] = t1 + h01[i*4+2, i*4+3] = t1 + + matrix = h00 + h01*cmath.exp(1j*k) + h01.transpose().conj()*cmath.exp(-1j*k) + return matrix + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, N=40, M=0, t1=1) + k = np.linspace(-pi, pi, 300) + plot_bands_one_dimension(k, hamiltonian0) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/2D_graphene.py b/academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/2D_graphene.py new file mode 100755 index 0000000..9e0b94d --- /dev/null +++ b/academic_codes/2019.10.23_Hamiltonian_and_bands_of_graphene/2D_graphene.py @@ -0,0 +1,66 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/408 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k1, k2, M, t1, a=1/sqrt(3)): # Haldane哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + # 初始化为零矩阵 + h0 = np.zeros((2, 2), dtype=complex) + h1 = np.zeros((2, 2), dtype=complex) + h2 = np.zeros((2, 2), dtype=complex) + + # 质量项(mass term),用于打开带隙 + h0[0, 0] = M + h0[1, 1] = -M + + # 最近邻项 + h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h1[0, 1] = h1[1, 0].conj() + + # # 最近邻项也可写成这种形式 + # h1[1, 0] = t1+t1*cmath.exp(1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)+t1*cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a) + # h1[0, 1] = h1[1, 0].conj() + + matrix = h0 + h1 + return matrix + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, M=0, t1=1, a=1/sqrt(3)) # 使用偏函数,固定一些参数 + k1 = np.linspace(-2*pi, 2*pi, 800) + k2 = np.linspace(-2*pi, 2*pi, 800) + plot_bands_two_dimension(k1, k2, hamiltonian0) + + +def plot_bands_two_dimension(k1, k2, hamiltonian): + from matplotlib import cm + dim = hamiltonian(0, 0).shape[0] + dim1 = k1.shape[0] + dim2 = k2.shape[0] + eigenvalue_k = np.zeros((dim2, dim1, dim)) + i0 = 0 + for k10 in k1: + j0 = 0 + for k20 in k2: + matrix0 = hamiltonian(k10, k20) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[j0, i0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + for dim0 in range(dim): + ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/1D_Haldane_model.py b/academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/1D_Haldane_model.py new file mode 100755 index 0000000..1b6c1ca --- /dev/null +++ b/academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/1D_Haldane_model.py @@ -0,0 +1,94 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/410 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k, N, M, t1, t2, phi): # Haldane哈密顿量(N是条带的宽度参数) + # 初始化为零矩阵 + h00 = np.zeros((4*N, 4*N), dtype=complex) + h01 = np.zeros((4*N, 4*N), dtype=complex) + + # 原胞内的跃迁h00 + for i in range(N): + h00[i*4+0, i*4+0] = M + h00[i*4+1, i*4+1] = -M + h00[i*4+2, i*4+2] = M + h00[i*4+3, i*4+3] = -M + + # 最近邻 + h00[i*4+0, i*4+1] = t1 + h00[i*4+1, i*4+0] = t1 + h00[i*4+1, i*4+2] = t1 + h00[i*4+2, i*4+1] = t1 + h00[i*4+2, i*4+3] = t1 + h00[i*4+3, i*4+2] = t1 + + # 次近邻 + h00[i*4+0, i*4+2] = t2*cmath.exp(-1j*phi) # 逆时针为正,顺时针为负 + h00[i*4+2, i*4+0] = h00[i*4+0, i*4+2].conj() + h00[i*4+1, i*4+3] = t2*cmath.exp(-1j*phi) + h00[i*4+3, i*4+1] = h00[i*4+1, i*4+3].conj() + for i in range(N-1): + # 最近邻 + h00[i*4+3, (i+1)*4+0] = t1 + h00[(i+1)*4+0, i*4+3] = t1 + + # 次近邻 + h00[i*4+2, (i+1)*4+0] = t2*cmath.exp(1j*phi) + h00[(i+1)*4+0, i*4+2] = h00[i*4+2, (i+1)*4+0].conj() + h00[i*4+3, (i+1)*4+1] = t2*cmath.exp(1j*phi) + h00[(i+1)*4+1, i*4+3] = h00[i*4+3, (i+1)*4+1].conj() + + # 原胞间的跃迁h01 + for i in range(N): + # 最近邻 + h01[i*4+1, i*4+0] = t1 + h01[i*4+2, i*4+3] = t1 + + # 次近邻 + h01[i*4+0, i*4+0] = t2*cmath.exp(1j*phi) + h01[i*4+1, i*4+1] = t2*cmath.exp(-1j*phi) + h01[i*4+2, i*4+2] = t2*cmath.exp(1j*phi) + h01[i*4+3, i*4+3] = t2*cmath.exp(-1j*phi) + + h01[i*4+1, i*4+3] = t2*cmath.exp(1j*phi) + h01[i*4+2, i*4+0] = t2*cmath.exp(-1j*phi) + if i != 0: + h01[i*4+1, (i-1)*4+3] = t2*cmath.exp(1j*phi) + for i in range(N-1): + h01[i*4+2, (i+1)*4+0] = t2*cmath.exp(-1j*phi) + + matrix = h00 + h01*cmath.exp(1j*k) + h01.transpose().conj()*cmath.exp(-1j*k) + return matrix + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, N=40, M=2/3, t1=1, t2=1/3, phi=pi/4) + k = np.linspace(-pi, pi, 300) + plot_bands_one_dimension(k, hamiltonian0) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/2D_Haldane_model.py b/academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/2D_Haldane_model.py new file mode 100755 index 0000000..9f84494 --- /dev/null +++ b/academic_codes/2019.10.24_Halmiltonian_and_bands_of_Haldane_model/2D_Haldane_model.py @@ -0,0 +1,70 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/410 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k1, k2, M, t1, t2, phi, a=1/sqrt(3)): # Haldane哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + # 初始化为零矩阵 + h0 = np.zeros((2, 2), dtype=complex) + h1 = np.zeros((2, 2), dtype=complex) + h2 = np.zeros((2, 2), dtype=complex) + + # 质量项(mass term),用于打开带隙 + h0[0, 0] = M + h0[1, 1] = -M + + # 最近邻项 + h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h1[0, 1] = h1[1, 0].conj() + + # 最近邻项也可写成这种形式 + # h1[1, 0] = t1+t1*cmath.exp(1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)-t1*cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a) + # h1[0, 1] = h1[1, 0].conj() + + # 次近邻项 + h2[0, 0] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + h2[1, 1] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + matrix = h0 + h1 + h2 + h2.transpose().conj() + return matrix + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, M=2/3, t1=1, t2=1/3, phi=pi/4, a=1/sqrt(3)) + k1 = np.linspace(-2*pi, 2*pi, 500) + k2 = np.linspace(-2*pi, 2*pi, 500) + plot_bands_two_dimension(k1, k2, hamiltonian0) + + +def plot_bands_two_dimension(k1, k2, hamiltonian): + from matplotlib import cm + dim = hamiltonian(0, 0).shape[0] + dim1 = k1.shape[0] + dim2 = k2.shape[0] + eigenvalue_k = np.zeros((dim2, dim1, dim)) + i0 = 0 + for k10 in k1: + j0 = 0 + for k20 in k2: + matrix0 = hamiltonian(k10, k20) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[j0, i0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + for dim0 in range(dim): + ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.11.01_conductance_calculation_using_Green_functions/conductance_calculation_using_Green_functions.py b/academic_codes/2019.11.01_conductance_calculation_using_Green_functions/conductance_calculation_using_Green_functions.py new file mode 100755 index 0000000..45ed73a --- /dev/null +++ b/academic_codes/2019.11.01_conductance_calculation_using_Green_functions/conductance_calculation_using_Green_functions.py @@ -0,0 +1,101 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/948 +""" + +import numpy as np +import matplotlib.pyplot as plt +import copy +import time + + +def matrix_00(width=10): # 不赋值时默认为10 + h00 = np.zeros((width, width)) + for width0 in range(width-1): + h00[width0, width0+1] = 1 + h00[width0+1, width0] = 1 + return h00 + + +def matrix_01(width=10): # 不赋值时默认为10 + h01 = np.identity(width) + return h01 + + +def main(): + start_time = time.time() + h00 = matrix_00(width=5) + h01 = matrix_01(width=5) + fermi_energy_array = np.arange(-4, 4, .01) + plot_conductance_energy(fermi_energy_array, h00, h01) + end_time = time.time() + print('运行时间=', end_time-start_time) + + +def plot_conductance_energy(fermi_energy_array, h00, h01): # 画电导与费米能关系图 + dim = fermi_energy_array.shape[0] + cond = np.zeros(dim) + i0 = 0 + for fermi_energy0 in fermi_energy_array: + cond0 = np.real(conductance(fermi_energy0 + 1e-12j, h00, h01)) + cond[i0] = cond0 + i0 += 1 + plt.plot(fermi_energy_array, cond, '-k') + plt.show() + + +def transfer_matrix(fermi_energy, h00, h01, dim): # 转移矩阵T。dim是传递矩阵h00和h01的维度 + transfer = np.zeros((2*dim, 2*dim))*(0+0j) # 乘0+0j,把变量转为复数 + transfer[0:dim, 0:dim] = np.dot(np.linalg.inv(h01), fermi_energy*np.identity(dim)-h00) # np.dot()等效于np.matmul() + transfer[0:dim, dim:2*dim] = np.dot(-1*np.linalg.inv(h01), h01.transpose().conj()) + transfer[dim:2*dim, 0:dim] = np.identity(dim) + transfer[dim:2*dim, dim:2*dim] = 0 # a:b代表 a <= x < b,左闭右开 + return transfer # 返回转移矩阵 + + +def green_function_lead(fermi_energy, h00, h01, dim): # 电极的表面格林函数 + transfer = transfer_matrix(fermi_energy, h00, h01, dim) + eigenvalue, eigenvector = np.linalg.eig(transfer) + ind = np.argsort(np.abs(eigenvalue)) + temp = np.zeros((2*dim, 2*dim))*(1+0j) + i0 = 0 + for ind0 in ind: + temp[:, i0] = eigenvector[:, ind0] + i0 += 1 + s1 = temp[dim:2*dim, 0:dim] + s2 = temp[0:dim, 0:dim] + s3 = temp[dim:2*dim, dim:2*dim] + s4 = temp[0:dim, dim:2*dim] + right_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01, s2), np.linalg.inv(s1))) + left_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), s3), np.linalg.inv(s4))) + return right_lead_surface, left_lead_surface # 返回右电极的表面格林函数和左电极的表面格林函数 + + +def self_energy_lead(fermi_energy, h00, h01, dim): # 电极的自能 + right_lead_surface, left_lead_surface = green_function_lead(fermi_energy, h00, h01, dim) + right_self_energy = np.dot(np.dot(h01, right_lead_surface), h01.transpose().conj()) + left_self_energy = np.dot(np.dot(h01.transpose().conj(), left_lead_surface), h01) + return right_self_energy, left_self_energy # 返回右边电极自能和左边电极自能 + + +def conductance(fermi_energy, h00, h01, nx=300): # 计算电导 + dim = h00.shape[0] + right_self_energy, left_self_energy = self_energy_lead(fermi_energy, h00, h01, dim) + for ix in range(nx): + if ix == 0: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-left_self_energy) + green_0n_n = copy.deepcopy(green_nn_n) # 如果直接用等于,两个变量会指向相同的id,改变一个值,另外一个值可能会发生改变,容易出错,所以要用上这个COPY + elif ix != nx-1: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + green_0n_n = np.dot(np.dot(green_0n_n, h01), green_nn_n) + else: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)-right_self_energy) + green_0n_n = np.dot(np.dot(green_0n_n, h01), green_nn_n) + right_self_energy = (right_self_energy - right_self_energy.transpose().conj())*(0+1j) + left_self_energy = (left_self_energy - left_self_energy.transpose().conj())*(0+1j) + transmission = np.trace(np.dot(np.dot(np.dot(left_self_energy, green_0n_n), right_self_energy), green_0n_n.transpose().conj())) + return transmission # 返回电导值 + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.11.02_numerically_verify_the_relation_between_eigenstates_and_DOS/numerically_verify_the_relation_between_eigenstates_and_DOS.py b/academic_codes/2019.11.02_numerically_verify_the_relation_between_eigenstates_and_DOS/numerically_verify_the_relation_between_eigenstates_and_DOS.py new file mode 100755 index 0000000..fc48384 --- /dev/null +++ b/academic_codes/2019.11.02_numerically_verify_the_relation_between_eigenstates_and_DOS/numerically_verify_the_relation_between_eigenstates_and_DOS.py @@ -0,0 +1,43 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/962 +""" + +import numpy as np + + +def hamiltonian(width=2, length=4): # 有一定宽度和长度的方格子 + h00 = np.zeros((width*length, width*length)) + for i0 in range(length): + for j0 in range(width-1): + h00[i0*width+j0, i0*width+j0+1] = 1 + h00[i0*width+j0+1, i0*width+j0] = 1 + for i0 in range(length-1): + for j0 in range(width): + h00[i0*width+j0, (i0+1)*width+j0] = 1 + h00[(i0+1)*width+j0, i0*width+j0] = 1 + return h00 + + +def main(): + h0 = hamiltonian() + dim = h0.shape[0] + n = 4 # 选取第n个能级 + eigenvalue, eigenvector = np.linalg.eig(h0) # 本征值、本征矢 + # print(h0) + # print('哈密顿量的维度:', dim) # 哈密顿量的维度 + # print('本征矢的维度:', eigenvector.shape) # 本征矢的维度 + # print('能级(未排序):', eigenvalue) # 输出本征值。因为体系是受限的,所以是离散的能级 + # print('选取第', n, '个能级,为', eigenvalue[n-1]) # 从1开始算,查看第n个能级是什么(这里本征值未排序) + # print('第', n, '个能级对应的波函数:', eigenvector[:, n-1]) # 查看第n个能级对应的波函数 + print('\n波函数模的平方:\n', np.square(np.abs(eigenvector[:, n-1]))) # 查看第n个能级对应的波函数模的平方 + green = np.linalg.inv((eigenvalue[n-1]+1e-15j)*np.eye(dim)-h0) # 第n个能级对应的格林函数 + total = np.trace(np.imag(green)) # 求该能级格林函数的迹,对应的是总态密度(忽略符号和系数) + print('归一化后的态密度分布:') + for i in range(dim): + print(np.imag(green)[i, i]/total) # 第n个能级单位化后的态密度分布 + print('观察以上两个分布的数值情况,可以发现两者完全相同。') + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.11.03_three_body_moving_on_2D_space/big_mass_in_one_body/step_0.1.py b/academic_codes/2019.11.03_three_body_moving_on_2D_space/big_mass_in_one_body/step_0.1.py new file mode 100755 index 0000000..a4e6b76 --- /dev/null +++ b/academic_codes/2019.11.03_three_body_moving_on_2D_space/big_mass_in_one_body/step_0.1.py @@ -0,0 +1,114 @@ +import numpy as np +import matplotlib.pyplot as plt +import os +os.chdir('D:/data') # 设置路径 + +# 万有引力常数 +G = 1 + +# 三体的质量 +m1 = 10 # 绿色 +m2 = 1000 # 红色 +m3 = 10 # 蓝色 + +# 三体的初始位置 +x1 = 0 # 绿色 +y1 = 500 +x2 = 0 # 红色 +y2 = 0 +x3 = 0 # 蓝色 +y3 = 1000 + +# 三体的初始速度 +v1_x = 1.5 # 绿色 +v1_y = 0 +v2_x = 0 # 红色 +v2_y = 0 +v3_x = 0.8 # 蓝色 +v3_y = 0 + +# 步长 +t = 0.1 + +plt.ion() # 开启交互模式 +observation_max = 100 # 视线范围初始值 +x1_all = [x1] # 轨迹初始值 +y1_all = [y1] +x2_all = [x2] +y2_all = [y2] +x3_all = [x3] +y3_all = [y3] + +i0 = 0 +for i in range(1000000): + distance12 = np.sqrt((x1-x2)**2+(y1-y2)**2) # 物体1和物体2之间的距离 + distance13 = np.sqrt((x1-x3)**2+(y1-y3)**2) # 物体1和物体3之间的距离 + distance23 = np.sqrt((x2-x3)**2+(y2-y3)**2) # 物体2和物体3之间的距离 + + # 对物体1的计算 + a1_2 = G*m2/(distance12**2) # 物体2对物体1的加速度(用上万有引力公式) + a1_3 = G*m3/(distance13**2) # 物体3对物体1的加速度 + a1_x = a1_2*(x2-x1)/distance12 + a1_3*(x3-x1)/distance13 # 物体1受到的水平加速度 + a1_y = a1_2*(y2-y1)/distance12 + a1_3*(y3-y1)/distance13 # 物体1受到的垂直加速度 + v1_x = v1_x + a1_x*t # 物体1的速度 + v1_y = v1_y + a1_y*t # 物体1的速度 + x1 = x1 + v1_x*t # 物体1的水平位置 + y1 = y1 + v1_y*t # 物体1的垂直位置 + x1_all = np.append(x1_all, x1) # 记录轨迹 + y1_all = np.append(y1_all, y1) # 记录轨迹 + + # 对物体2的计算 + a2_1 = G*m1/(distance12**2) + a2_3 = G*m3/(distance23**2) + a2_x = a2_1*(x1-x2)/distance12 + a2_3*(x3-x2)/distance23 + a2_y = a2_1*(y1-y2)/distance12 + a2_3*(y3-y2)/distance23 + v2_x = v2_x + a2_x*t + v2_y = v2_y + a2_y*t + x2 = x2 + v2_x*t + y2 = y2 + v2_y*t + x2_all = np.append(x2_all, x2) + y2_all = np.append(y2_all, y2) + + # 对物体3的计算 + a3_1 = G*m1/(distance13**2) + a3_2 = G*m2/(distance23**2) + a3_x = a3_1*(x1-x3)/distance13 + a3_2*(x2-x3)/distance23 + a3_y = a3_1*(y1-y3)/distance13 + a3_2*(y2-y3)/distance23 + v3_x = v3_x + a3_x*t + v3_y = v3_y + a3_y*t + x3 = x3 + v3_x*t + y3 = y3 + v3_y*t + x3_all = np.append(x3_all, x3) + y3_all = np.append(y3_all, y3) + + # 选择观测坐标 + axis_x = np.mean([x1, x2, x3]) # 观测坐标中心固定在平均值的地方 + axis_y = np.mean([y1, y2, y3]) # 观测坐标中心固定在平均值的地方 + while True: + if np.abs(x1-axis_x) > observation_max or np.abs(x2-axis_x) > observation_max or np.abs(x3-axis_x) > observation_max or\ + np.abs(y1-axis_y) > observation_max or np.abs(y2-axis_y) > observation_max or np.abs(y3-axis_y) > observation_max: + observation_max = observation_max * 2 # 有一个物体超出视线时,视线范围翻倍 + elif np.abs(x1-axis_x) < observation_max/10 and np.abs(x2-axis_x) < observation_max/10 and np.abs(x3-axis_x) < observation_max/10 and\ + np.abs(y1-axis_y) < observation_max/10 and np.abs(y2-axis_y) < observation_max/10 and np.abs(y3-axis_y) < observation_max/10: + observation_max = observation_max / 2 # 所有物体都在的视线的10分之一内,视线范围减半 + else: + break + + plt.axis([axis_x-observation_max, axis_x+observation_max, axis_y-observation_max, axis_y+observation_max]) + + plt.plot(x1, y1, 'og', markersize=m1*100/observation_max) # 默认密度相同,质量越大的,球面积越大。视线范围越宽,球看起来越小。 + plt.plot(x2, y2, 'or', markersize=m2*100/observation_max) + plt.plot(x3, y3, 'ob', markersize=m3*100/observation_max) + plt.plot(x1_all, y1_all, '-g') # 画轨迹 + plt.plot(x2_all, y2_all, '-r') + plt.plot(x3_all, y3_all, '-b') + + + # plt.show() # 显示图像 + # plt.pause(0.00001) # 暂停0.00001,防止画图过快 + + if np.mod(i, 100) == 0: # 当运动明显时,把图画出来 + print(i0) + plt.savefig(str(i0)+'.jpg') # 保存为图片可以用来做动画 + i0 += 1 + plt.clf() # 清空 diff --git a/academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.05.py b/academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.05.py new file mode 100755 index 0000000..af818b3 --- /dev/null +++ b/academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.05.py @@ -0,0 +1,110 @@ +import numpy as np +import matplotlib.pyplot as plt +import os +os.chdir('D:/data') # 设置路径 + +# 万有引力常数 +G = 1 + +# 三体的质量 +m1 = 3 # 绿色 +m2 = 100 # 红色 +m3 = 10 # 蓝色 + +# 三体的初始位置 +x1 = 0 # 绿色 +y1 = -100 +x2 = 0 # 红色 +y2 = 0 +x3 = 0 # 蓝色 +y3 = 50 + +# 三体的初始速度 +v1_x = 1 # 绿色 +v1_y = 0 +v2_x = 0 # 红色 +v2_y = 0 +v3_x = 2 # 蓝色 +v3_y = 0 + +# 步长 +t = 0.05 + +plt.ion() # 开启交互模式 +observation_max = 100 # 观测坐标范围初始值 +x1_all = [x1] # 轨迹初始值 +y1_all = [y1] +x2_all = [x2] +y2_all = [y2] +x3_all = [x3] +y3_all = [y3] + +i0 = 0 +for i in range(100000000000): + distance12 = np.sqrt((x1-x2)**2+(y1-y2)**2) # 物体1和物体2之间的距离 + distance13 = np.sqrt((x1-x3)**2+(y1-y3)**2) # 物体1和物体3之间的距离 + distance23 = np.sqrt((x2-x3)**2+(y2-y3)**2) # 物体2和物体3之间的距离 + # 对物体1的计算 + a1_2 = G*m2/(distance12**2) # 物体2对物体1的加速度(用上万有引力公式) + a1_3 = G*m3/(distance13**2) # 物体3对物体1的加速度 + a1_x = a1_2*(x2-x1)/distance12 + a1_3*(x3-x1)/distance13 # 物体1受到的水平加速度 + a1_y = a1_2*(y2-y1)/distance12 + a1_3*(y3-y1)/distance13 # 物体1受到的垂直加速度 + v1_x = v1_x + a1_x*t # 物体1的速度 + v1_y = v1_y + a1_y*t # 物体1的速度 + x1 = x1 + v1_x*t # 物体1的水平位置 + y1 = y1 + v1_y*t # 物体1的垂直位置 + x1_all = np.append(x1_all, x1) # 记录轨迹 + y1_all = np.append(y1_all, y1) # 记录轨迹 + # 对物体2的计算 + a2_1 = G*m1/(distance12**2) + a2_3 = G*m3/(distance23**2) + a2_x = a2_1*(x1-x2)/distance12 + a2_3*(x3-x2)/distance23 + a2_y = a2_1*(y1-y2)/distance12 + a2_3*(y3-y2)/distance23 + v2_x = v2_x + a2_x*t + v2_y = v2_y + a2_y*t + x2 = x2 + v2_x*t + y2 = y2 + v2_y*t + x2_all = np.append(x2_all, x2) + y2_all = np.append(y2_all, y2) + # 对物体3的计算 + a3_1 = G*m1/(distance13**2) + a3_2 = G*m2/(distance23**2) + a3_x = a3_1*(x1-x3)/distance13 + a3_2*(x2-x3)/distance23 + a3_y = a3_1*(y1-y3)/distance13 + a3_2*(y2-y3)/distance23 + v3_x = v3_x + a3_x*t + v3_y = v3_y + a3_y*t + x3 = x3 + v3_x*t + y3 = y3 + v3_y*t + x3_all = np.append(x3_all, x3) + y3_all = np.append(y3_all, y3) + + # 选择观测坐标 + axis_x = np.mean([x1, x2, x3]) # 观测坐标中心固定在平均值的地方 + axis_y = np.mean([y1, y2, y3]) # 观测坐标中心固定在平均值的地方 + while True: + if np.abs(x1-axis_x) > observation_max or np.abs(x2-axis_x) > observation_max or np.abs(x3-axis_x) > observation_max or\ + np.abs(y1-axis_y) > observation_max or np.abs(y2-axis_y) > observation_max or np.abs(y3-axis_y) > observation_max: + observation_max = observation_max * 2 # 有一个物体超出视线时,视线范围翻倍 + elif np.abs(x1-axis_x) < observation_max/10 and np.abs(x2-axis_x) < observation_max/10 and np.abs(x3-axis_x) < observation_max/10 and\ + np.abs(y1-axis_y) < observation_max/10 and np.abs(y2-axis_y) < observation_max/10 and np.abs(y3-axis_y) < observation_max/10: + observation_max = observation_max / 2 # 所有物体都在的视线的10分之一内,视线范围减半 + else: + break + + plt.axis([axis_x-observation_max, axis_x+observation_max, axis_y-observation_max, axis_y+observation_max]) + + plt.plot(x1, y1, 'og', markersize=m1*100/observation_max) # 默认密度相同,质量越大的,画出来的面积越大。视线范围越宽,球看起来越小。 + plt.plot(x2, y2, 'or', markersize=m2*100/observation_max) + plt.plot(x3, y3, 'ob', markersize=m3*100/observation_max) + plt.plot(x1_all, y1_all, '-g') # 画轨迹 + plt.plot(x2_all, y2_all, '-r') + plt.plot(x3_all, y3_all, '-b') + + # plt.show() # 显示图像 + # plt.pause(0.00001) # 暂停0.00001,防止画图过快 + + if np.mod(i, 200) == 0: + print(i0) + plt.savefig(str(i0)+'.jpg') # 保存为图片可以用来做动画 + i0 += 1 + plt.clf() # 清空 \ No newline at end of file diff --git a/academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.1.py b/academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.1.py new file mode 100755 index 0000000..60e253e --- /dev/null +++ b/academic_codes/2019.11.03_three_body_moving_on_2D_space/relatively_big_mass_in_one_body/step_0.1.py @@ -0,0 +1,110 @@ +import numpy as np +import matplotlib.pyplot as plt +import os +os.chdir('D:/data') # 设置路径 + +# 万有引力常数 +G = 1 + +# 三体的质量 +m1 = 3 # 绿色 +m2 = 100 # 红色 +m3 = 10 # 蓝色 + +# 三体的初始位置 +x1 = 0 # 绿色 +y1 = -100 +x2 = 0 # 红色 +y2 = 0 +x3 = 0 # 蓝色 +y3 = 50 + +# 三体的初始速度 +v1_x = 1 # 绿色 +v1_y = 0 +v2_x = 0 # 红色 +v2_y = 0 +v3_x = 2 # 蓝色 +v3_y = 0 + +# 步长 +t = 0.1 + +plt.ion() # 开启交互模式 +observation_max = 100 # 观测坐标范围初始值 +x1_all = [x1] # 轨迹初始值 +y1_all = [y1] +x2_all = [x2] +y2_all = [y2] +x3_all = [x3] +y3_all = [y3] + +i0 = 0 +for i in range(100000000000): + distance12 = np.sqrt((x1-x2)**2+(y1-y2)**2) # 物体1和物体2之间的距离 + distance13 = np.sqrt((x1-x3)**2+(y1-y3)**2) # 物体1和物体3之间的距离 + distance23 = np.sqrt((x2-x3)**2+(y2-y3)**2) # 物体2和物体3之间的距离 + # 对物体1的计算 + a1_2 = G*m2/(distance12**2) # 物体2对物体1的加速度(用上万有引力公式) + a1_3 = G*m3/(distance13**2) # 物体3对物体1的加速度 + a1_x = a1_2*(x2-x1)/distance12 + a1_3*(x3-x1)/distance13 # 物体1受到的水平加速度 + a1_y = a1_2*(y2-y1)/distance12 + a1_3*(y3-y1)/distance13 # 物体1受到的垂直加速度 + v1_x = v1_x + a1_x*t # 物体1的速度 + v1_y = v1_y + a1_y*t # 物体1的速度 + x1 = x1 + v1_x*t # 物体1的水平位置 + y1 = y1 + v1_y*t # 物体1的垂直位置 + x1_all = np.append(x1_all, x1) # 记录轨迹 + y1_all = np.append(y1_all, y1) # 记录轨迹 + # 对物体2的计算 + a2_1 = G*m1/(distance12**2) + a2_3 = G*m3/(distance23**2) + a2_x = a2_1*(x1-x2)/distance12 + a2_3*(x3-x2)/distance23 + a2_y = a2_1*(y1-y2)/distance12 + a2_3*(y3-y2)/distance23 + v2_x = v2_x + a2_x*t + v2_y = v2_y + a2_y*t + x2 = x2 + v2_x*t + y2 = y2 + v2_y*t + x2_all = np.append(x2_all, x2) + y2_all = np.append(y2_all, y2) + # 对物体3的计算 + a3_1 = G*m1/(distance13**2) + a3_2 = G*m2/(distance23**2) + a3_x = a3_1*(x1-x3)/distance13 + a3_2*(x2-x3)/distance23 + a3_y = a3_1*(y1-y3)/distance13 + a3_2*(y2-y3)/distance23 + v3_x = v3_x + a3_x*t + v3_y = v3_y + a3_y*t + x3 = x3 + v3_x*t + y3 = y3 + v3_y*t + x3_all = np.append(x3_all, x3) + y3_all = np.append(y3_all, y3) + + # 选择观测坐标 + axis_x = np.mean([x1, x2, x3]) # 观测坐标中心固定在平均值的地方 + axis_y = np.mean([y1, y2, y3]) # 观测坐标中心固定在平均值的地方 + while True: + if np.abs(x1-axis_x) > observation_max or np.abs(x2-axis_x) > observation_max or np.abs(x3-axis_x) > observation_max or\ + np.abs(y1-axis_y) > observation_max or np.abs(y2-axis_y) > observation_max or np.abs(y3-axis_y) > observation_max: + observation_max = observation_max * 2 # 有一个物体超出视线时,视线范围翻倍 + elif np.abs(x1-axis_x) < observation_max/10 and np.abs(x2-axis_x) < observation_max/10 and np.abs(x3-axis_x) < observation_max/10 and\ + np.abs(y1-axis_y) < observation_max/10 and np.abs(y2-axis_y) < observation_max/10 and np.abs(y3-axis_y) < observation_max/10: + observation_max = observation_max / 2 # 所有物体都在的视线的10分之一内,视线范围减半 + else: + break + + plt.axis([axis_x-observation_max, axis_x+observation_max, axis_y-observation_max, axis_y+observation_max]) + + plt.plot(x1, y1, 'og', markersize=m1*100/observation_max) # 默认密度相同,质量越大的,画出来的面积越大。视线范围越宽,球看起来越小。 + plt.plot(x2, y2, 'or', markersize=m2*100/observation_max) + plt.plot(x3, y3, 'ob', markersize=m3*100/observation_max) + plt.plot(x1_all, y1_all, '-g') # 画轨迹 + plt.plot(x2_all, y2_all, '-r') + plt.plot(x3_all, y3_all, '-b') + + # plt.show() # 显示图像 + # plt.pause(0.00001) # 暂停0.00001,防止画图过快 + + if np.mod(i, 100) == 0: + print(i0) + plt.savefig(str(i0)+'.jpg') # 保存为图片可以用来做动画 + i0 += 1 + plt.clf() # 清空 \ No newline at end of file diff --git a/academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.05.py b/academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.05.py new file mode 100755 index 0000000..174b16d --- /dev/null +++ b/academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.05.py @@ -0,0 +1,113 @@ +import numpy as np +import matplotlib.pyplot as plt +import os +os.chdir('D:/data') # 设置路径 + +# 万有引力常数 +G = 1 + +# 三体的质量 +m1 = 15 # 绿色 +m2 = 12 # 红色 +m3 = 8 # 蓝色 + +# 三体的初始位置 +x1 = 300 # 绿色 +y1 = 50 +x2 = -100 # 红色 +y2 = -200 +x3 = -100 # 蓝色 +y3 = 150 + +# 三体的初始速度 +v1_x = 0 # 绿色 +v1_y = 0 +v2_x = 0 # 红色 +v2_y = 0 +v3_x = 0 # 蓝色 +v3_y = 0 + +# 步长 +t = 0.05 + +plt.ion() # 开启交互模式 +observation_max = 100 # 视线范围初始值 +x1_all = [x1] # 轨迹初始值 +y1_all = [y1] +x2_all = [x2] +y2_all = [y2] +x3_all = [x3] +y3_all = [y3] + +i0 = 0 +for i in range(1000000): + distance12 = np.sqrt((x1-x2)**2+(y1-y2)**2) # 物体1和物体2之间的距离 + distance13 = np.sqrt((x1-x3)**2+(y1-y3)**2) # 物体1和物体3之间的距离 + distance23 = np.sqrt((x2-x3)**2+(y2-y3)**2) # 物体2和物体3之间的距离 + + # 对物体1的计算 + a1_2 = G*m2/(distance12**2) # 物体2对物体1的加速度(用上万有引力公式) + a1_3 = G*m3/(distance13**2) # 物体3对物体1的加速度 + a1_x = a1_2*(x2-x1)/distance12 + a1_3*(x3-x1)/distance13 # 物体1受到的水平加速度 + a1_y = a1_2*(y2-y1)/distance12 + a1_3*(y3-y1)/distance13 # 物体1受到的垂直加速度 + v1_x = v1_x + a1_x*t # 物体1的速度 + v1_y = v1_y + a1_y*t # 物体1的速度 + x1 = x1 + v1_x*t # 物体1的水平位置 + y1 = y1 + v1_y*t # 物体1的垂直位置 + x1_all = np.append(x1_all, x1) # 记录轨迹 + y1_all = np.append(y1_all, y1) # 记录轨迹 + + # 对物体2的计算 + a2_1 = G*m1/(distance12**2) + a2_3 = G*m3/(distance23**2) + a2_x = a2_1*(x1-x2)/distance12 + a2_3*(x3-x2)/distance23 + a2_y = a2_1*(y1-y2)/distance12 + a2_3*(y3-y2)/distance23 + v2_x = v2_x + a2_x*t + v2_y = v2_y + a2_y*t + x2 = x2 + v2_x*t + y2 = y2 + v2_y*t + x2_all = np.append(x2_all, x2) + y2_all = np.append(y2_all, y2) + + # 对物体3的计算 + a3_1 = G*m1/(distance13**2) + a3_2 = G*m2/(distance23**2) + a3_x = a3_1*(x1-x3)/distance13 + a3_2*(x2-x3)/distance23 + a3_y = a3_1*(y1-y3)/distance13 + a3_2*(y2-y3)/distance23 + v3_x = v3_x + a3_x*t + v3_y = v3_y + a3_y*t + x3 = x3 + v3_x*t + y3 = y3 + v3_y*t + x3_all = np.append(x3_all, x3) + y3_all = np.append(y3_all, y3) + + # 选择观测坐标 + axis_x = np.mean([x1, x2, x3]) # 观测坐标中心固定在平均值的地方 + axis_y = np.mean([y1, y2, y3]) # 观测坐标中心固定在平均值的地方 + while True: + if np.abs(x1-axis_x) > observation_max or np.abs(x2-axis_x) > observation_max or np.abs(x3-axis_x) > observation_max or\ + np.abs(y1-axis_y) > observation_max or np.abs(y2-axis_y) > observation_max or np.abs(y3-axis_y) > observation_max: + observation_max = observation_max * 2 # 有一个物体超出视线时,视线范围翻倍 + elif np.abs(x1-axis_x) < observation_max/10 and np.abs(x2-axis_x) < observation_max/10 and np.abs(x3-axis_x) < observation_max/10 and\ + np.abs(y1-axis_y) < observation_max/10 and np.abs(y2-axis_y) < observation_max/10 and np.abs(y3-axis_y) < observation_max/10: + observation_max = observation_max / 2 # 所有物体都在的视线的10分之一内,视线范围减半 + else: + break + + plt.axis([axis_x-observation_max, axis_x+observation_max, axis_y-observation_max, axis_y+observation_max]) + + plt.plot(x1, y1, 'og', markersize=m1*100/observation_max) # 默认密度相同,质量越大的,球面积越大。视线范围越宽,球看起来越小。 + plt.plot(x2, y2, 'or', markersize=m2*100/observation_max) + plt.plot(x3, y3, 'ob', markersize=m3*100/observation_max) + plt.plot(x1_all, y1_all, '-g') # 画轨迹 + plt.plot(x2_all, y2_all, '-r') + plt.plot(x3_all, y3_all, '-b') + + # plt.show() # 显示图像 + # plt.pause(0.00001) # 暂停0.00001,防止画图过快 + + if np.mod(i, 1000) == 0: # 当运动明显时,把图画出来 + print(i0) + plt.savefig(str(i0)+'.jpg') # 保存为图片可以用来做动画 + i0 += 1 + plt.clf() # 清空 diff --git a/academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.1.py b/academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.1.py new file mode 100755 index 0000000..f3f9fa1 --- /dev/null +++ b/academic_codes/2019.11.03_three_body_moving_on_2D_space/three_body_mass_with_little_difference/step_0.1.py @@ -0,0 +1,113 @@ +import numpy as np +import matplotlib.pyplot as plt +import os +os.chdir('D:/data') # 设置路径 + +# 万有引力常数 +G = 1 + +# 三体的质量 +m1 = 15 # 绿色 +m2 = 12 # 红色 +m3 = 8 # 蓝色 + +# 三体的初始位置 +x1 = 300 # 绿色 +y1 = 50 +x2 = -100 # 红色 +y2 = -200 +x3 = -100 # 蓝色 +y3 = 150 + +# 三体的初始速度 +v1_x = 0 # 绿色 +v1_y = 0 +v2_x = 0 # 红色 +v2_y = 0 +v3_x = 0 # 蓝色 +v3_y = 0 + +# 步长 +t = 0.1 + +plt.ion() # 开启交互模式 +observation_max = 100 # 视线范围初始值 +x1_all = [x1] # 轨迹初始值 +y1_all = [y1] +x2_all = [x2] +y2_all = [y2] +x3_all = [x3] +y3_all = [y3] + +i0 = 0 +for i in range(1000000): + distance12 = np.sqrt((x1-x2)**2+(y1-y2)**2) # 物体1和物体2之间的距离 + distance13 = np.sqrt((x1-x3)**2+(y1-y3)**2) # 物体1和物体3之间的距离 + distance23 = np.sqrt((x2-x3)**2+(y2-y3)**2) # 物体2和物体3之间的距离 + + # 对物体1的计算 + a1_2 = G*m2/(distance12**2) # 物体2对物体1的加速度(用上万有引力公式) + a1_3 = G*m3/(distance13**2) # 物体3对物体1的加速度 + a1_x = a1_2*(x2-x1)/distance12 + a1_3*(x3-x1)/distance13 # 物体1受到的水平加速度 + a1_y = a1_2*(y2-y1)/distance12 + a1_3*(y3-y1)/distance13 # 物体1受到的垂直加速度 + v1_x = v1_x + a1_x*t # 物体1的速度 + v1_y = v1_y + a1_y*t # 物体1的速度 + x1 = x1 + v1_x*t # 物体1的水平位置 + y1 = y1 + v1_y*t # 物体1的垂直位置 + x1_all = np.append(x1_all, x1) # 记录轨迹 + y1_all = np.append(y1_all, y1) # 记录轨迹 + + # 对物体2的计算 + a2_1 = G*m1/(distance12**2) + a2_3 = G*m3/(distance23**2) + a2_x = a2_1*(x1-x2)/distance12 + a2_3*(x3-x2)/distance23 + a2_y = a2_1*(y1-y2)/distance12 + a2_3*(y3-y2)/distance23 + v2_x = v2_x + a2_x*t + v2_y = v2_y + a2_y*t + x2 = x2 + v2_x*t + y2 = y2 + v2_y*t + x2_all = np.append(x2_all, x2) + y2_all = np.append(y2_all, y2) + + # 对物体3的计算 + a3_1 = G*m1/(distance13**2) + a3_2 = G*m2/(distance23**2) + a3_x = a3_1*(x1-x3)/distance13 + a3_2*(x2-x3)/distance23 + a3_y = a3_1*(y1-y3)/distance13 + a3_2*(y2-y3)/distance23 + v3_x = v3_x + a3_x*t + v3_y = v3_y + a3_y*t + x3 = x3 + v3_x*t + y3 = y3 + v3_y*t + x3_all = np.append(x3_all, x3) + y3_all = np.append(y3_all, y3) + + # 选择观测坐标 + axis_x = np.mean([x1, x2, x3]) # 观测坐标中心固定在平均值的地方 + axis_y = np.mean([y1, y2, y3]) # 观测坐标中心固定在平均值的地方 + while True: + if np.abs(x1-axis_x) > observation_max or np.abs(x2-axis_x) > observation_max or np.abs(x3-axis_x) > observation_max or\ + np.abs(y1-axis_y) > observation_max or np.abs(y2-axis_y) > observation_max or np.abs(y3-axis_y) > observation_max: + observation_max = observation_max * 2 # 有一个物体超出视线时,视线范围翻倍 + elif np.abs(x1-axis_x) < observation_max/10 and np.abs(x2-axis_x) < observation_max/10 and np.abs(x3-axis_x) < observation_max/10 and\ + np.abs(y1-axis_y) < observation_max/10 and np.abs(y2-axis_y) < observation_max/10 and np.abs(y3-axis_y) < observation_max/10: + observation_max = observation_max / 2 # 所有物体都在的视线的10分之一内,视线范围减半 + else: + break + + plt.axis([axis_x-observation_max, axis_x+observation_max, axis_y-observation_max, axis_y+observation_max]) + + plt.plot(x1, y1, 'og', markersize=m1*100/observation_max) # 默认密度相同,质量越大的,球面积越大。视线范围越宽,球看起来越小。 + plt.plot(x2, y2, 'or', markersize=m2*100/observation_max) + plt.plot(x3, y3, 'ob', markersize=m3*100/observation_max) + plt.plot(x1_all, y1_all, '-g') # 画轨迹 + plt.plot(x2_all, y2_all, '-r') + plt.plot(x3_all, y3_all, '-b') + + # plt.show() # 显示图像 + # plt.pause(0.00001) # 暂停0.00001,防止画图过快 + + if np.mod(i, 500) == 0: # 当运动明显时,把图画出来 + print(i0) + plt.savefig(str(i0)+'.jpg') # 保存为图片可以用来做动画 + i0 += 1 + plt.clf() # 清空 diff --git a/academic_codes/2019.11.07_definite_integration_with_Monte_Carlo_method/definite_integration_with_Monte_Carlo_method.py b/academic_codes/2019.11.07_definite_integration_with_Monte_Carlo_method/definite_integration_with_Monte_Carlo_method.py new file mode 100755 index 0000000..3c01139 --- /dev/null +++ b/academic_codes/2019.11.07_definite_integration_with_Monte_Carlo_method/definite_integration_with_Monte_Carlo_method.py @@ -0,0 +1,73 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/1145 +""" + +import numpy as np +import random +import time + + +def integral(): # 直接数值积分 + integral_value = 0 + for x in np.arange(0, 1, 1/10**7): + integral_value = integral_value + x**2*(1/10**7) # 对x^2在0和1之间积分 + return integral_value + + +def MC_1(): # 蒙特卡洛求定积分1:投点法 + n = 10**7 + x_min, x_max = 0.0, 1.0 + y_min, y_max = 0.0, 1.0 + count = 0 + for i in range(0, n): + x = random.uniform(x_min, x_max) + y = random.uniform(y_min, y_max) + # x*x > y,表示该点位于曲线的下面。所求的积分值即为曲线下方的面积与正方形面积的比。 + if x * x > y: + count += 1 + integral_value = count / n + return integral_value + + +def MC_2(): # 蒙特卡洛求定积分2:期望法 + n = 10**7 + x_min, x_max = 0.0, 1.0 + integral_value = 0 + for i in range(n): + x = random.uniform(x_min, x_max) + integral_value = integral_value + (1-0)*x**2 + integral_value = integral_value/n + return integral_value + + +print('【计算时间】') +start_clock = time.perf_counter() # 或者用time.clock() +a00 = 1/3 # 理论值 +end_clock = time.perf_counter() +print('理论值(解析):', end_clock-start_clock) +start_clock = time.perf_counter() +a0 = integral() # 直接数值积分 +end_clock = time.perf_counter() +print('直接数值积分:', end_clock-start_clock) +start_clock = time.perf_counter() +a1 = MC_1() # 用蒙特卡洛求积分投点法 +end_clock = time.perf_counter() +print('用蒙特卡洛求积分_投点法:', end_clock-start_clock) +start_clock = time.perf_counter() +a2 = MC_2() +end_clock = time.perf_counter() +print('用蒙特卡洛求积分_期望法:', end_clock-start_clock, '\n') + +print('【计算结果】') +print('理论值(解析):', a00) +print('直接数值积分:', a0) +print('用蒙特卡洛求积分_投点法:', a1) +print('用蒙特卡洛求积分_期望法:', a2, '\n') + +print('【计算误差】') +print('理论值(解析):', 0) +print('直接数值积分:', abs(a0-1/3)) +print('用蒙特卡洛求积分_投点法:', abs(a1-1/3)) +print('用蒙特卡洛求积分_期望法:', abs(a2-1/3)) + diff --git a/academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/Hamiltonian_of_square_lattice_in_kwant.py b/academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/Hamiltonian_of_square_lattice_in_kwant.py new file mode 100755 index 0000000..9331db0 --- /dev/null +++ b/academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/Hamiltonian_of_square_lattice_in_kwant.py @@ -0,0 +1,56 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/2033 +""" + +import kwant +import matplotlib.pyplot as plt + + +def main(): + L = 3 + W = 2 + + lat = kwant.lattice.square(a=1, norbs=1) # 定义lattice + print('\nlat:\n', lat) + + syst = kwant.Builder() # 定义中心区的Builder + print('\nsyst:\n', syst) + + syst_finalized = syst.finalized() + hamiltonian = syst_finalized.hamiltonian_submatrix() # 查看哈密顿量 + print('\nhamiltonian_1(定义):\n', hamiltonian) + + syst[(lat(x, y) for x in range(L) for y in range(W))] = 0 # 晶格初始化为0 + + kwant.plot(syst) # 画出syst的示意图 + + syst_finalized = syst.finalized() + hamiltonian = syst_finalized.hamiltonian_submatrix() # 查看哈密顿量 + print('\nhamiltonian_2(初始化):\n', hamiltonian) + + syst[lat.neighbors()] = 1 # 添加最近邻跃迁 + + kwant.plot(syst) # 画出syst的示意图 + + syst_finalized = syst.finalized() + hamiltonian = syst_finalized.hamiltonian_submatrix() # 查看哈密顿量 + print('\nhamiltonian_3(最近邻赋值):\n', hamiltonian) + + lead = kwant.Builder(kwant.TranslationalSymmetry((-1, 0))) # 定义电极的Builder + lead[(lat(0, j) for j in range(W))] = 0 # 电极晶格初始化 + lead[lat.neighbors()] = 1 # 添加最近邻跃迁 + syst.attach_lead(lead) # 中心区加上左电极 + syst.attach_lead(lead.reversed()) # 用reversed()方法得到右电极 + + # 画出syst的示意图 + kwant.plot(syst) + + # 查看哈密顿量(加了电极后,并不影响syst哈密顿量) + syst_finalized = syst.finalized() + hamiltonian = syst_finalized.hamiltonian_submatrix() + print('\nhamiltonian_4(加了电极后):\n', hamiltonian) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/kwant_example.py b/academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/kwant_example.py new file mode 100755 index 0000000..072cf5f --- /dev/null +++ b/academic_codes/2019.11.19_kwant_a_package_of_calculations_in_quantum_transport/kwant_example.py @@ -0,0 +1,94 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/2033 +""" + +import kwant +import numpy as np +from matplotlib import pyplot + + +def make_system(): + a = 1 # 晶格常数 + lat = kwant.lattice.square(a) # 创建晶格,方格子 + + syst = kwant.Builder() # 建立中心体系 + t = 1.0 # hopping值 + W = 5 # 中心体系宽度 + L = 40 # 中心体系长度 + + # 给中心体系赋值 + for i in range(L): + for j in range(W): + syst[lat(i, j)] = 0 + if j > 0: + syst[lat(i, j), lat(i, j-1)] = -t # hopping in y-direction + if i > 0: + syst[lat(i, j), lat(i-1, j)] = -t # hopping in x-direction + + sym_left_lead = kwant.TranslationalSymmetry((-a, 0)) # 电极的平移对称性,(-a, 0)代表远离中心区的方向,向左 + left_lead = kwant.Builder(sym_left_lead) # 建立左电极体系 + # 给电极体系赋值 + for j in range(W): + left_lead[lat(0, j)] = 0 + if j > 0: + left_lead[lat(0, j), lat(0, j - 1)] = -t + left_lead[lat(1, j), lat(0, j)] = -t # 这里写一个即可,因为平移对称性已经声明了 + syst.attach_lead(left_lead) # 把左电极接在中心区 + + sym_right_lead = kwant.TranslationalSymmetry((a, 0)) + right_lead = kwant.Builder(sym_right_lead) + for j in range(W): + right_lead[lat(0, j)] = 0 + if j > 0: + right_lead[lat(0, j), lat(0, j - 1)] = -t + right_lead[lat(1, j), lat(0, j)] = -t + syst.attach_lead(right_lead) # 把右电极接在中心区 + + kwant.plot(syst) # 把电极-中心区-电极图画出来,通过图像可以看出有没有写错 + syst = syst.finalized() # 结束体系的制作。这个语句不可以省。这个语句是把Builder对象转换成可计算的对象。 + return syst + + +def make_system_with_less_code(): + a = 1 # 晶格常数 + lat = kwant.lattice.square(a) # 创建晶格,方格子 + + syst = kwant.Builder() # 建立中心体系 + t = 1.0 # hopping值 + W = 5 # 中心体系宽度 + L = 40 # 中心体系长度 + + # 中心区 + syst[(lat(x, y) for x in range(L) for y in range(W))] = 0 + syst[lat.neighbors()] = -t # 用neighbors()方法 + + # 电极 + lead = kwant.Builder(kwant.TranslationalSymmetry((-a, 0))) + lead[(lat(0, j) for j in range(W))] = 0 + lead[lat.neighbors()] = -t # 用neighbors()方法 + syst.attach_lead(lead) # 左电极 + syst.attach_lead(lead.reversed()) # 用reversed()方法得到右电极 + + kwant.plot(syst) # 把电极-中心区-电极图画出来,通过图像可以看出有没有写错 + syst = syst.finalized() # 结束体系的制作。这个语句不可以省。这个语句是把Builder对象转换成可计算的对象。 + return syst + + +def main(): + syst = make_system() + # syst = make_system_with_less_code() # 和上面的一样,只是用更少的代码写 + energies = np.linspace(-4, 4, 200) + data = [] + for energy in energies: + smatrix = kwant.smatrix(syst, energy) # compute the transmission probability from lead 0 to lead 1 + data.append(smatrix.transmission(1, 0)) + pyplot.plot(energies, data) + pyplot.xlabel("energy [t]") + pyplot.ylabel("conductance [e^2/h]") + pyplot.show() + # pyplot.savefig('conductance' + '.eps') + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.11.27_Hamiltonian_of_BHZ_model_and_bands_in_quasi_1D_systems/bands_in_quasi_1D_BHZ_systems.py b/academic_codes/2019.11.27_Hamiltonian_of_BHZ_model_and_bands_in_quasi_1D_systems/bands_in_quasi_1D_BHZ_systems.py new file mode 100755 index 0000000..339f236 --- /dev/null +++ b/academic_codes/2019.11.27_Hamiltonian_of_BHZ_model_and_bands_in_quasi_1D_systems/bands_in_quasi_1D_BHZ_systems.py @@ -0,0 +1,84 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/2327 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入sqrt(), pi, exp等 +import cmath # 要处理复数情况,用到cmath.exp() +import functools # 使用偏函数functools.partial() + + +def get_terms(A, B, C, D, M, a): + E_s = C+M-4*(D+B)/(a**2) + E_p = C-M-4*(D-B)/(a**2) + V_ss = (D+B)/(a**2) + V_pp = (D-B)/(a**2) + V_sp = -1j*A/(2*a) + H0 = np.zeros((4, 4))*(1+0j) # 在位能 (on-site energy) + H1 = np.zeros((4, 4))*(1+0j) # x方向的跃迁 (hopping) + H2 = np.zeros((4, 4))*(1+0j) # y方向的跃迁 (hopping) + H0[0, 0] = E_s + H0[1, 1] = E_p + H0[2, 2] = E_s + H0[3, 3] = E_p + + H1[0, 0] = V_ss + H1[1, 1] = V_pp + H1[2, 2] = V_ss + H1[3, 3] = V_pp + H1[0, 1] = V_sp + H1[1, 0] = -np.conj(V_sp) + H1[2, 3] = np.conj(V_sp) + H1[3, 2] = -V_sp + + H2[0, 0] = V_ss + H2[1, 1] = V_pp + H2[2, 2] = V_ss + H2[3, 3] = V_pp + H2[0, 1] = 1j*V_sp + H2[1, 0] = 1j*np.conj(V_sp) + H2[2, 3] = -1j*np.conj(V_sp) + H2[3, 2] = -1j*V_sp + return H0, H1, H2 + + +def BHZ_model(k, A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01, a=1, N=100): # 这边数值是不赋值时的默认参数 + H0, H1, H2 = get_terms(A, B, C, D, M, a) + H00 = np.zeros((4*N, 4*N))*(1+0j) # 元胞内,条带宽度为N + H01 = np.zeros((4*N, 4*N))*(1+0j) # 条带方向元胞间的跃迁 + for i in range(N): + H00[i*4+0:i*4+4, i*4+0:i*4+4] = H0 # a:b代表 a <= x < b + H01[i*4+0:i*4+4, i*4+0:i*4+4] = H1 + for i in range(N-1): + H00[i*4+0:i*4+4, (i+1)*4+0:(i+1)*4+4] = H2 + H00[(i+1)*4+0:(i+1)*4+4, i*4+0:i*4+4] = np.conj(np.transpose(H2)) + H = H00 + H01 * cmath.exp(-1j * k) + H01.transpose().conj() * cmath.exp(1j * k) + return H + + +def main(): + hamiltonian0 = functools.partial(BHZ_model, N=50) # 使用偏函数,固定一些参数 + k = np.linspace(-pi, pi, 300) # 300 + plot_bands_one_dimension(k, hamiltonian0) + + +def plot_bands_one_dimension(k, hamiltonian, filename='bands_1D'): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) # np.zeros()里要用tuple + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') # -. + # plt.savefig(filename + '.jpg') # plt.savefig(filename+'.eps') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_1.py b/academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_1.py new file mode 100755 index 0000000..8c4005d --- /dev/null +++ b/academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_1.py @@ -0,0 +1,33 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/1247 +""" + +import random +import math +import numpy as np +from scipy.stats import norm +import matplotlib.pyplot as plt + + +def function(x): # 期望样品的分布,target distribution function + y = (norm.pdf(x, loc=2, scale=1)+norm.pdf(x, loc=-5, scale=1.5))/2 # loc代表了均值,scale代表标准差 + return y + + +T = 100000 # 取T个样品 +pi = [0 for i in range(T)] # 任意选定一个马尔科夫链初始状态 +for t in np.arange(1, T): + pi_star = np.random.uniform(-10, 10) # a proposed distribution, 例如是均匀分布的,或者是一个依赖pi[t - 1]的分布 + alpha = min(1, (function(pi_star) / function(pi[t - 1]))) # 接收率 + u = random.uniform(0, 1) + if u < alpha: + pi[t] = pi_star # 以alpha的概率接收转移 + else: + pi[t] = pi[t - 1] # 不接收转移 + +pi = np.array(pi) # 转成numpy格式 +print(pi.shape) # 查看抽样样品的维度 +plt.plot(pi, function(pi), '*') # 画出抽样样品期望的分布 # 或用plt.scatter(pi, function(pi)) +plt.hist(pi, bins=100, density=1, facecolor='red', alpha=0.7) # 画出抽样样品的分布 # bins是分布柱子的个数,density是归一化,后面两个参数是管颜色的 +plt.show() diff --git a/academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_2.m b/academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_2.m new file mode 100755 index 0000000..fb8cffc --- /dev/null +++ b/academic_codes/2019.12.01_0_Metropolis_sampling/Metropolis_sampling_example_2.m @@ -0,0 +1,18 @@ +% This code is supported by the website: https://www.guanjihuan.com +% The newest version of this code is on the web page: https://www.guanjihuan.com/archives/1247 + +clc;clear all;clf; +s=100000; % 取的样品数 +f=[1,2,3,3,3,3,6,5,4,3,2,1]; % 期望得到样品的分布函数 +d=zeros(1,s); % 初始状态 +x=1; +for i=1:s + y=unidrnd(12); % 1到12随机整数 + alpha=min(1,f(y)/f(x)); % 接收率 + u=rand; + if u 0 else width - 1 # 用到周期性边界条件 + bottom_i = i + 1 if i < (width - 1) else 0 + left_j = j - 1 if j > 0 else height - 1 + right_j = j + 1 if j < (height - 1) else 0 + environment = [[top_i, j], [bottom_i, j], [i, left_j], [i, right_j]] + energy = 0 + if angle == None: + for num_i in range(4): + energy += -np.cos(S[i, j] - S[environment[num_i][0], environment[num_i][1]]) + else: + for num_i in range(4): + energy += -np.cos(angle - S[environment[num_i][0], environment[num_i][1]]) + return energy + + +def calculateAllEnergy(S): # 计算整个体系的能量 + energy = 0 + for i in range(S.shape[0]): + for j in range(S.shape[1]): + energy += getEnergy(i, j, S) + return energy/2 # 作用两次要减半 + + +def plot(S): # 画图 + X, Y = np.meshgrid(np.arange(0, S.shape[0]), np.arange(0, S.shape[0])) + U = np.cos(S) + V = np.sin(S) + plt.figure() + plt.quiver(X, Y, U, V, units='inches') + plt.show() + + +if __name__ == '__main__': + main() + diff --git a/academic_codes/2019.12.01_1_simulation_of_Ising_model_with_Monte_Carlo_method/get_the_transition_temperature_by_calculating_magnetic_moments_in_Ising_model.py b/academic_codes/2019.12.01_1_simulation_of_Ising_model_with_Monte_Carlo_method/get_the_transition_temperature_by_calculating_magnetic_moments_in_Ising_model.py new file mode 100755 index 0000000..0f29506 --- /dev/null +++ b/academic_codes/2019.12.01_1_simulation_of_Ising_model_with_Monte_Carlo_method/get_the_transition_temperature_by_calculating_magnetic_moments_in_Ising_model.py @@ -0,0 +1,76 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/1249 +""" + +import random +import matplotlib.pyplot as plt +import numpy as np +import copy +import math +import time + + +def main(): + size = 30 # 体系大小 + for T in np.linspace(0.02, 5, 100): + ising, magnetism = get_one_sample(sizeOfSample=size, temperature=T) + print('温度=', T, ' 磁矩=', magnetism, ' 总能量=', calculateAllEnergy(ising)) + plt.plot(T, magnetism, 'o') + plt.show() + + +def get_one_sample(sizeOfSample, temperature): + newS = np.zeros((sizeOfSample, sizeOfSample)) # 初始状态 + magnetism = 0 + for i00 in range(100): + newS = Metropolis(newS, temperature) + magnetism = magnetism + abs(sum(sum(np.cos(newS))))/newS.shape[0]**2 + magnetism = magnetism/100 + return newS, magnetism + + +def Metropolis(S, T): # S是输入的初始状态, T是温度 + k = 1 # 玻尔兹曼常数 + for i in range(S.shape[0]): + for j in range(S.shape[0]): + newAngle = np.random.randint(-1, 1)*np.pi + energyBefore = getEnergy(i=i, j=j, S=S, angle=None) # 获取该格点的能量 + energyLater = getEnergy(i=i, j=j, S=S, angle=newAngle) # 获取格点变成新角度时的能量 + alpha = min(1.0, math.exp(-(energyLater - energyBefore)/(k * T))) # 这个接受率对应的是玻尔兹曼分布 + if random.uniform(0, 1) <= alpha: + S[i, j] = newAngle # 接受新状态 + else: + pass # 保持为上一个状态 + return S + + +def getEnergy(i, j, S, angle=None): # 计算(i,j)位置的能量,为周围四个的相互能之和 + width = S.shape[0] + height = S.shape[1] + top_i = i - 1 if i > 0 else width - 1 # 用到周期性边界条件 + bottom_i = i + 1 if i < (width - 1) else 0 + left_j = j - 1 if j > 0 else height - 1 + right_j = j + 1 if j < (height - 1) else 0 + environment = [[top_i, j], [bottom_i, j], [i, left_j], [i, right_j]] + energy = 0 + if angle == None: + for num_i in range(4): + energy += -np.cos(S[i, j] - S[environment[num_i][0], environment[num_i][1]]) + else: + for num_i in range(4): + energy += -np.cos(angle - S[environment[num_i][0], environment[num_i][1]]) + return energy + + +def calculateAllEnergy(S): # 计算整个体系的能量 + energy = 0 + for i in range(S.shape[0]): + for j in range(S.shape[1]): + energy += getEnergy(i, j, S) + return energy/2 # 作用两次要减半 + + +if __name__ == '__main__': + main() + diff --git a/academic_codes/2019.12.03_create_GIF_with_python/create_GIF_with_python.py b/academic_codes/2019.12.03_create_GIF_with_python/create_GIF_with_python.py new file mode 100755 index 0000000..cf4e55e --- /dev/null +++ b/academic_codes/2019.12.03_create_GIF_with_python/create_GIF_with_python.py @@ -0,0 +1,11 @@ +import imageio +import numpy as np +import os +os.chdir('D:/data') # 设置文件读取和保存位置 + +images = [] +for i in range(1000): + image = str(i)+'.jpg' + im = imageio.imread(image) + images.append(im) +imageio.mimsave("a.gif", images, 'GIF', duration=0.1) # durantion是延迟时间 \ No newline at end of file diff --git a/academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.f90 b/academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.f90 new file mode 100755 index 0000000..5c6ff86 --- /dev/null +++ b/academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.f90 @@ -0,0 +1,160 @@ +! This code is supported by the website: https://www.guanjihuan.com +! The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3785 + +module global + implicit none + double precision sqrt3,Pi + parameter(sqrt3=1.7320508075688773d0,Pi=3.14159265358979324d0) +end module global + + + +program QPI !QPI主程序 + use blas95 + use lapack95,only:GETRF,GETRI + use global + implicit none + integer i,j,info,index_0(4) + double precision omega,kx,ky,Eigenvalues(4),eta,V0,kx1,kx2,ky1,ky2,qx,qy,time_begin,time_end + parameter(eta=0.005) + complex*16 H0(4,4),green_0(4,4),green_1(4,4),green_0_k1(4,4),green_0_k2(4,4),A_spectral,V(4,4),gamma_0(4,4),Temp_0(4,4),T(4,4),g_1,rho_1 + character(len=*):: Flname + parameter(Flname='') !可以写上输出文件路径,也可以不写,输出存在当前文件的路径 + + omega=0.070d0 + open(unit=10,file=Flname//'Spectral function_w=0.07.txt') + open(unit=20,file=Flname//'QPI_intra_nonmag_w=0.07.txt') + call CPU_TIME(time_begin) + + !计算谱函数A(kx,ky) + write(10,"(f20.10,x)",advance='no') 0 + do ky=-Pi,Pi,0.01d0 !谱函数图案的精度 + write(10,"(f20.10,x)",advance='no') ky + enddo + write(10,"(a)",advance='yes') ' ' + do kx=-Pi,Pi,0.01d0 !谱函数图案的精度 + write(10,"(f20.10,x)",advance='no') kx + do ky=-Pi,Pi,0.01d0 !谱函数图案的精度 + call Greenfunction_clean(kx,ky,eta,omega,green_0) + A_spectral=-(green_0(1,1)+green_0(3,3))/Pi + write(10,"(f20.10)",advance='no') imag(A_spectral) + enddo + write(10,"(a)",advance='yes') ' ' + enddo + + !计算QPI(qx,qy) + V0=0.4d0 + V=0.d0 + V(1,1)=V0 + V(2,2)=-V0 + V(3,3)=V0 + V(4,4)=-V0 + gamma_0=0.d0 + do kx=-Pi,Pi,0.01 + do ky=-Pi,Pi,0.01 + call Greenfunction_clean(kx,ky,eta,omega,green_0) + do i=1,4 + do j=1,4 + gamma_0(i,j)=gamma_0(i,j)+green_0(i,j)*0.01*0.01 + enddo + enddo + enddo + enddo + gamma_0=gamma_0/(2*Pi)/(2*Pi) + call gemm(V,gamma_0,Temp_0) + do i=1,4 + Temp_0(i,i)=1-Temp_0(i,i) + enddo + call GETRF( Temp_0,index_0,info ); call GETRI( Temp_0,index_0,info) !求逆 + call gemm(Temp_0,V,T) !矩阵乘积 + write(20,"(f20.10,x)",advance='no') 0 + do qy=-Pi,Pi,0.01 !QPI图案的精度 + write(20,"(f20.10,x)",advance='no') qy + enddo + write(20,"(a)",advance='yes') ' ' + do qx=-Pi,Pi,0.01 !QPI图案的精度 + write(*,"(a)",advance='no') 'qx=' + write(*,*) qx !屏幕输出可以实时查看计算进度 + write(20,"(f20.10)",advance='no') qx + do qy=-Pi,Pi,0.01 !QPI图案的精度 + rho_1=0.d0 + do kx1=-Pi,Pi,0.06 !积分的精度 + kx2=kx1+qx + do ky1=-Pi,Pi,0.06 !积分的精度 + ky2=ky1+qy + call Greenfunction_clean(kx1,ky1,eta,omega,green_0_k1) + call Greenfunction_clean(kx2,ky2,eta,omega,green_0_k2) + call gemm(green_0_k1,T,Temp_0) + call gemm(Temp_0, green_0_k2, green_1) + g_1=green_1(1,1)-dconjg(green_1(1,1))+green_1(3,3)-dconjg(green_1(3,3)) + rho_1=rho_1+g_1*0.06*0.06 + enddo + enddo + rho_1=rho_1/(2*Pi)/(2*Pi)/(2*Pi)*(0.d0,1.d0) + write(20,"(f20.10,x,f20.10)",advance='no') real(rho_1) + enddo + write(20,"(a)",advance='yes') ' ' + enddo + + call CPU_TIME(time_end) + write(*,"(a)",advance='no') 'The running time of this task=' + write (*,*) time_end-time_begin !屏幕输出总的计算时间,单位为秒(按照当前步长的精度,在个人计算机上运算大概需要4个小时) +end program + + + +subroutine Greenfunction_clean(kx,ky,eta,omega,green_0) !干净体系的格林函数 +use blas95 +use lapack95,only:GETRF,GETRI +use global +integer info,index_0(4) +double precision, intent(in):: kx,ky,eta,omega +complex*16 H0(4,4) +complex*16,intent(out):: green_0(4,4) +call Hamiltonian(kx,ky,H0) +green_0=H0 +do i=1,4 + green_0(i,i)=omega+(0.d0,1.d0)*eta-green_0(i,i) +enddo +call GETRF( green_0,index_0,info ); call GETRI( green_0,index_0,info ); +end subroutine Greenfunction_clean + + + +subroutine Hamiltonian(kx,ky,Matrix) !哈密顿量 +use global +implicit none +integer i,j +double precision t1,t2,t3,t4,mu,epsilon_x,epsilon_y,epsilon_xy,delta_1,delta_2,delta_0 +double precision, intent(in):: kx,ky +complex*16,intent(out):: Matrix(4,4) + +t1=-1;t2=1.3;t3=-0.85;t4=-0.85;delta_0=0.1;mu=1.54 +Matrix=(0.d0,0.d0) + +epsilon_x=-2*t1*dcos(kx)-2*t2*dcos(ky)-4*t3*dcos(kx)*dcos(ky) +epsilon_y=-2*t1*dcos(ky)-2*t2*dcos(kx)-4*t3*dcos(kx)*dcos(ky) +epsilon_xy=-4*t4*dsin(kx)*dsin(ky) +delta_1=delta_0*dcos(kx)*dcos(ky) +delta_2=delta_1 + +Matrix(1,1)=epsilon_x-mu +Matrix(2,2)=-epsilon_x+mu +Matrix(3,3)=epsilon_y-mu +Matrix(4,4)=-epsilon_y+mu + +Matrix(1,2)=delta_1 +Matrix(2,1)=delta_1 +Matrix(1,3)=epsilon_xy +Matrix(3,1)=epsilon_xy +Matrix(1,4)=0.d0 +Matrix(4,1)=0.d0 + +Matrix(2,3)=0.d0 +Matrix(3,2)=0.d0 +Matrix(2,4)=-epsilon_xy +Matrix(4,2)=-epsilon_xy + +Matrix(3,4)=delta_2 +Matrix(4,3)=delta_2 +end subroutine Hamiltonian \ No newline at end of file diff --git a/academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.py b/academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.py new file mode 100755 index 0000000..12fdd64 --- /dev/null +++ b/academic_codes/2019.12.30_calculation of spectral function and QPI/calculation of spectral function and QPI.py @@ -0,0 +1,158 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3785 +""" + +import numpy as np +from math import * +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +import time + + +def green_function(fermi_energy, k1, k2, hamiltonian): # 计算格林函数 + matrix0 = hamiltonian(k1, k2) + dim = matrix0.shape[0] + green = np.linalg.inv(fermi_energy * np.identity(dim) - matrix0) + return green + + +def spectral_function(fermi_energy, k1, k2, hamiltonian): # 计算谱函数 + dim1 = k1.shape[0] + dim2 = k2.shape[0] + spectrum = np.zeros((dim1, dim2)) + i0 = 0 + for k10 in k1: + j0 = 0 + for k20 in k2: + green = green_function(fermi_energy, k10, k20, hamiltonian) + spectrum[i0, j0] = (np.imag(green[0,0])+np.imag(green[2,2]))/(-pi) + j0 += 1 + i0 += 1 + # print(spectrum) + print() + print('Spectral function显示的网格点 =', k1.shape[0], '*', k1.shape[0], '; 步长 =', k1[1] - k1[0]) + print() + return spectrum + + +def qpi(fermi_energy, q1, q2, hamiltonian, potential_i): # 计算QPI + dim = hamiltonian(0, 0).shape[0] + ki1 = np.arange(-pi, pi, 0.01) # 计算gamma_0时,k的积分密度 + ki2 = np.arange(-pi, pi, 0.01) + print('gamma_0的积分网格点 =', ki1.shape[0], '*', ki1.shape[0], '; 步长 =', ki1[1] - ki1[0]) + gamma_0 = integral_of_green(fermi_energy, ki1, ki2, hamiltonian)/np.square(2*pi) + t_matrix = np.dot(np.linalg.inv(np.identity(dim)-np.dot(potential_i, gamma_0)), potential_i) + ki1 = np.arange(-pi, pi, 0.06) # 计算induced_local_density时,k的积分密度 + ki2 = np.arange(-pi, pi, 0.06) + print('局域态密度变化的积分网格点 =', ki1.shape[0], '*', ki1.shape[0], '; 步长 =', ki1[1] - ki1[0]) + print('QPI显示的网格点 =', q1.shape[0], '*', q1.shape[0], '; 步长 =', q1[1] - q1[0]) + step_length = ki1[1] - ki1[0] + induced_local_density = np.zeros((q1.shape[0], q2.shape[0]))*(1+0j) + print() + i0 = 0 + for q10 in q1: + print('i0=', i0) + j0 = 0 + for q20 in q2: + for ki10 in ki1: + for ki20 in ki2: + green_01 = green_function(fermi_energy, ki10, ki20, hamiltonian) + green_02 = green_function(fermi_energy, ki10+q10, ki20+q20, hamiltonian) + induced_green = np.dot(np.dot(green_01, t_matrix), green_02) + temp = induced_green[0, 0]-induced_green[0, 0].conj()+induced_green[2, 2]-induced_green[2, 2].conj() + induced_local_density[i0, j0] = induced_local_density[i0, j0]+temp*np.square(step_length) + j0 += 1 + i0 += 1 + write_matrix_k1_k2(q1, q2, np.real(induced_local_density*1j/np.square(2*pi)/(2*pi)), 'QPI') # 数据写入文件(临时写入,会被多次替代) + induced_local_density = np.real(induced_local_density*1j/np.square(2*pi)/(2*pi)) + return induced_local_density + + +def integral_of_green(fermi_energy, ki1, ki2, hamiltonian): # 在计算QPI时需要对格林函数积分 + dim = hamiltonian(0, 0).shape[0] + integral_value = np.zeros((dim, dim))*(1+0j) + step_length = ki1[1]-ki1[0] + for ki10 in ki1: + for ki20 in ki2: + green = green_function(fermi_energy, ki10, ki20, hamiltonian) + integral_value = integral_value+green*np.square(step_length) + return integral_value + + +def write_matrix_k1_k2(x1, x2, value, filename='matrix_k1_k2'): # 把矩阵数据写入文件(格式化输出) + with open(filename+'.txt', 'w') as f: + np.set_printoptions(suppress=True) # 取消输出科学记数法 + f.write('0 ') + for x10 in x1: + f.write(str(x10)+' ') + f.write('\n') + i0 = 0 + for x20 in x2: + f.write(str(x20)) + for j0 in range(x1.shape[0]): + f.write(' '+str(value[i0, j0])+' ') + f.write('\n') + i0 += 1 + + +def plot_contour(x1, x2, value, filename='contour'): # 直接画出contour图像(保存图像) + plt.contourf(x1, x2, value) #, cmap=plt.cm.hot) + plt.savefig(filename+'.eps') + # plt.show() + + +def hamiltonian(kx, ky): # 体系的哈密顿量 + t1 = -1; t2 = 1.3; t3 = -0.85; t4 = -0.85; delta_0 = 0.1; mu = 1.54 + epsilon_x = -2*t1*cos(kx)-2*t2*cos(ky)-4*t3*cos(kx)*cos(ky) + epsilon_y = -2*t1*cos(ky)-2*t2*cos(kx)-4*t3*cos(kx)*cos(ky) + epsilon_xy = -4*t4*sin(kx)*sin(ky) + delta_1 = delta_0*cos(kx)*cos(ky) + delta_2 = delta_0*cos(kx)*cos(ky) + h = np.zeros((4, 4)) + h[0, 0] = epsilon_x-mu + h[1, 1] = -epsilon_x+mu + h[2, 2] = epsilon_y-mu + h[3, 3] = -epsilon_y+mu + + h[0, 1] = delta_1 + h[1, 0] = delta_1 + h[0, 2] = epsilon_xy + h[2, 0] = epsilon_xy + h[0, 3] = 0 + h[3, 0] = 0 + + h[1, 2] = 0 + h[2, 1] = 0 + h[1, 3] = -epsilon_xy + h[3, 1] = -epsilon_xy + + h[2, 3] = delta_2 + h[3, 2] = delta_2 + return h + + +def main(): # 主程序 + start_clock = time.perf_counter() + fermi_energy = 0.07 # 费米能 + energy_broadening_width = 0.005 # 展宽 + k1 = np.arange(-pi, pi, 0.01) # 谱函数的图像精度 + k2 = np.arange(-pi, pi, 0.01) + spectrum = spectral_function(fermi_energy+energy_broadening_width*1j, k1, k2, hamiltonian) # 调用谱函数子程序 + write_matrix_k1_k2(k1, k2, spectrum, 'Spectral_function') # 把谱函数的数据写入文件 + # plot_contour(k1, k2, spectrum, 'Spectral_function') # 直接显示谱函数的图像(保存图像) + + q1 = np.arange(-pi, pi, 0.01) # QPI数的图像精度 + q2 = np.arange(-pi, pi, 0.01) + potential_i = (0.4+0j)*np.identity(hamiltonian(0, 0).shape[0]) # 杂质势 + potential_i[1, 1] = - potential_i[1, 1] # for nonmagnetic + potential_i[3, 3] = - potential_i[3, 3] + induced_local_density = qpi(fermi_energy+energy_broadening_width*1j, q1, q2, hamiltonian, potential_i) # 调用QPI子程序 + write_matrix_k1_k2(q1, q2, induced_local_density, 'QPI') # 把QPI数据写入文件(这里用的方法是计算结束后一次性把数据写入) + # plot_contour(q1, q2, induced_local_density, 'QPI') # 直接显示QPI图像(保存图像) + end_clock = time.perf_counter() + print('CPU执行时间=', end_clock - start_clock) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.01.03_0_bands_of_qusi_1D_square_lattice/bands_of_qusi_1D_square_lattice.py b/academic_codes/2020.01.03_0_bands_of_qusi_1D_square_lattice/bands_of_qusi_1D_square_lattice.py new file mode 100755 index 0000000..2202a58 --- /dev/null +++ b/academic_codes/2020.01.03_0_bands_of_qusi_1D_square_lattice/bands_of_qusi_1D_square_lattice.py @@ -0,0 +1,48 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3895 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k, N, t): # 准一维方格子哈密顿量 + # 初始化为零矩阵 + h00 = np.zeros((N, N), dtype=complex) + h01 = np.zeros((N, N), dtype=complex) + for i in range(N-1): # 原胞内的跃迁h00 + h00[i, i+1] = t + h00[i+1, i] = t + for i in range(N): # 原胞间的跃迁h01 + h01[i, i] = t + matrix = h00 + h01*cmath.exp(1j*k) + h01.transpose().conj()*cmath.exp(-1j*k) + return matrix + + +def main(): + H_k = functools.partial(hamiltonian, N=10, t=1) + k = np.linspace(-pi, pi, 300) + plot_bands_one_dimension(k, H_k) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.01.03_1_calculation_of_local_currents/calculation_of_local_currents.py b/academic_codes/2020.01.03_1_calculation_of_local_currents/calculation_of_local_currents.py new file mode 100755 index 0000000..e0eea1b --- /dev/null +++ b/academic_codes/2020.01.03_1_calculation_of_local_currents/calculation_of_local_currents.py @@ -0,0 +1,130 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3888 +""" + +import numpy as np +import matplotlib.pyplot as plt +import copy +import time + + +def matrix_00(width=10): # 电极元胞内跃迁,width不赋值时默认为10 + h00 = np.zeros((width, width)) + for width0 in range(width-1): + h00[width0, width0+1] = 1 + h00[width0+1, width0] = 1 + return h00 + + +def matrix_01(width=10): # 电极元胞间跃迁,width不赋值时默认为10 + h01 = np.identity(width) + return h01 + + +def matrix_LC(width=10, length=300): # 左电极跳到中心区 + h_LC = np.zeros((width, width*length)) + for width0 in range(width): + h_LC[width0, width0] = 1 + return h_LC + + +def matrix_CR(width=10, length=300): # 中心区跳到右电极 + h_CR = np.zeros((width*length, width)) + for width0 in range(width): + h_CR[width*(length-1)+width0, width0] = 1 + return h_CR + + +def matrix_center(width=10, length=300): # 中心区哈密顿量 + hamiltonian = np.zeros((width*length, width*length)) + for length0 in range(length-1): + for width0 in range(width): + hamiltonian[width*length0+width0, width*(length0+1)+width0] = 1 # 长度方向跃迁 + hamiltonian[width*(length0+1)+width0, width*length0+width0] = 1 + for length0 in range(length): + for width0 in range(width-1): + hamiltonian[width*length0+width0, width*length0+width0+1] = 1 # 宽度方向跃迁 + hamiltonian[width*length0+width0+1, width*length0+width0] = 1 + # 中间加势垒 + for j0 in range(6): + for i0 in range(6): + hamiltonian[width*(np.int(length/2)-3+j0)+np.int(width/2)-3+i0, width*(np.int(length/2)-3+j0)+np.int(width/2)-3+i0]= 1e8 + return hamiltonian + + +def main(): + start_time = time.time() + fermi_energy = 1 + width = 60 + length = 100 + h00 = matrix_00(width) + h01 = matrix_01(width) + G_n = Green_n(fermi_energy+1j*1e-9, h00, h01, width, length) + # 下面是提取数据并画图 + direction_x = np.zeros((width, length)) + direction_y = np.zeros((width, length)) + for length0 in range(length-1): + for width0 in range(width): + direction_x[width0, length0] = G_n[width*length0+width0, width*(length0+1)+width0] + for length0 in range(length): + for width0 in range(width-1): + direction_y[width0, length0] = G_n[width*length0+width0, width*length0+width0+1] + # print(direction_x) + # print(direction_y) + X, Y = np.meshgrid(range(length), range(width)) + plt.quiver(X, Y, direction_x, direction_y) + plt.show() + end_time = time.time() + print('运行时间=', end_time-start_time) + + + +def transfer_matrix(fermi_energy, h00, h01, dim): # 转移矩阵T。dim是传递矩阵h00和h01的维度 + transfer = np.zeros((2*dim, 2*dim))*(0+0j) # 0+0j用来转为复数,不然下面赋值会提示忽略了虚数部分 + transfer[0:dim, 0:dim] = np.dot(np.linalg.inv(h01), fermi_energy*np.identity(dim)-h00) # np.dot()等效于np.matmul() + transfer[0:dim, dim:2*dim] = np.dot(-1*np.linalg.inv(h01), h01.transpose().conj()) + transfer[dim:2*dim, 0:dim] = np.identity(dim) + transfer[dim:2*dim, dim:2*dim] = 0 # a:b代表 a <= x < b + return transfer # 返回转移矩阵 + + +def green_function_lead(fermi_energy, h00, h01, dim): # 电极的表面格林函数 + transfer = transfer_matrix(fermi_energy, h00, h01, dim) + eigenvalue, eigenvector = np.linalg.eig(transfer) + ind = np.argsort(np.abs(eigenvalue)) + temp = np.zeros((2*dim, 2*dim))*(1+0j) + i0 = 0 + for ind0 in ind: + temp[:, i0] = eigenvector[:, ind0] + i0 += 1 + s1 = temp[dim:2*dim, 0:dim] + s2 = temp[0:dim, 0:dim] + s3 = temp[dim:2*dim, dim:2*dim] + s4 = temp[0:dim, dim:2*dim] + right_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01, s2), np.linalg.inv(s1))) + left_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), s3), np.linalg.inv(s4))) + return right_lead_surface, left_lead_surface # 返回右电极的表面格林函数和左电极的表面格林函数 + + +def self_energy_lead(fermi_energy, h00, h01, width, length): # 电极的自能 + h_LC = matrix_LC(width, length) + h_CR = matrix_CR(width, length) + right_lead_surface, left_lead_surface = green_function_lead(fermi_energy, h00, h01, width) + right_self_energy = np.dot(np.dot(h_CR, right_lead_surface), h_CR.transpose().conj()) + left_self_energy = np.dot(np.dot(h_LC.transpose().conj(), left_lead_surface), h_LC) + return right_self_energy, left_self_energy # 返回右电极的自能和左电极的自能 + + +def Green_n(fermi_energy, h00, h01, width, length): # 计算G_n + right_self_energy, left_self_energy = self_energy_lead(fermi_energy, h00, h01, width, length) + hamiltonian = matrix_center(width, length) + green = np.linalg.inv(fermi_energy*np.identity(width*length)-hamiltonian-left_self_energy-right_self_energy) + right_self_energy = (right_self_energy - right_self_energy.transpose().conj())*(0+1j) + left_self_energy = (left_self_energy - left_self_energy.transpose().conj())*(0+1j) + G_n = np.imag(np.dot(np.dot(green, left_self_energy), green.transpose().conj())) + return G_n + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.m b/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.m new file mode 100755 index 0000000..8e6a02f --- /dev/null +++ b/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.m @@ -0,0 +1,50 @@ +% This code is supported by the website: https://www.guanjihuan.com +% The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3932 + +% 陈数定义法 +clear;clc; +n=100; % 积分密度 +delta=1e-9; % 求导的偏离量 +C=0; +for kx=-pi:(1/n):pi + for ky=-pi:(1/n):pi + VV=get_vector(HH(kx,ky)); + Vkx=get_vector(HH(kx+delta,ky)); % 略偏离kx的波函数 + Vky=get_vector(HH(kx,ky+delta)); % 略偏离ky的波函数 + Vkxky=get_vector(HH(kx+delta,ky+delta)); % 略偏离kx,ky的波函数 + if sum((abs(Vkx-VV)))>0.01 % 为了波函数的连续性(这里的不连续只遇到符号问题,所以可以直接这么处理) + Vkx=-Vkx; + end + + if sum((abs(Vky-VV)))>0.01 + Vky=-Vky; + end + + if sum(abs(Vkxky-VV))>0.01 + Vkxky=-Vkxky; + end + % 价带的波函数的berry connection,求导后内积 + Ax=VV'*(Vkx-VV)/delta; % Berry connection Ax + Ay=VV'*(Vky-VV)/delta; % Berry connection Ay + Ax_delta_ky=Vky'*(Vkxky-Vky)/delta; % 略偏离ky的berry connection Ax + Ay_delta_kx=Vkx'*(Vkxky-Vkx)/delta; % 略偏离kx的berry connection Ay + % berry curvature + F=((Ay_delta_kx-Ay)-(Ax_delta_ky-Ax))/delta; + % chern number + C=C+F*(1/n)^2; + end +end +C=C/(2*pi*1i) + +function vector_new = get_vector(H) +[vector,eigenvalue] = eig(H); +[eigenvalue, index]=sort(diag(eigenvalue), 'descend'); +vector_new = vector(:, index(2)); +end + +function H=HH(kx,ky) +H(1,2)=2*cos(kx)-1i*2*cos(ky); +H(2,1)=2*cos(kx)+1i*2*cos(ky); +H(1,1)=-1+2*0.5*sin(kx)+2*0.5*sin(ky)+2*cos(kx+ky); +H(2,2)=-(-1+2*0.5*sin(kx)+2*0.5*sin(ky)+2*cos(kx+ky)); +end \ No newline at end of file diff --git a/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.py b/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.py new file mode 100755 index 0000000..729f666 --- /dev/null +++ b/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/calculation_of_Chern_number_by_definition_method.py @@ -0,0 +1,70 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3932 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import time + + +def hamiltonian(kx, ky): # 量子反常霍尔QAH模型(该参数对应的陈数为2) + t1 = 1.0 + t2 = 1.0 + t3 = 0.5 + m = -1.0 + matrix = np.zeros((2, 2))*(1+0j) + matrix[0, 1] = 2*t1*cos(kx)-1j*2*t1*cos(ky) + matrix[1, 0] = 2*t1*cos(kx)+1j*2*t1*cos(ky) + matrix[0, 0] = m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky) + matrix[1, 1] = -(m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky)) + return matrix + + +def main(): + start_time = time.time() + n = 100 # 积分密度 + delta = 1e-9 # 求导的偏离量 + chern_number = 0 # 陈数初始化 + for kx in np.arange(-pi, pi, 2*pi/n): + for ky in np.arange(-pi, pi, 2*pi/n): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + # print(np.argsort(np.real(eigenvalue))[0]) # 排序索引(从小到大) + # print(eigenvalue) # 排序前的本征值 + # print(np.sort(np.real(eigenvalue))) # 排序后的本征值(从小到大) + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + # 价带的波函数的贝里联络(berry connection) # 求导后内积 + A_x = np.dot(vector.transpose().conj(), (vector_delta_kx-vector)/delta) # 贝里联络Ax(x分量) + A_y = np.dot(vector.transpose().conj(), (vector_delta_ky-vector)/delta) # 贝里联络Ay(y分量) + + A_x_delta_ky = np.dot(vector_delta_ky.transpose().conj(), (vector_delta_kx_ky-vector_delta_ky)/delta) # 略偏离ky的贝里联络Ax + A_y_delta_kx = np.dot(vector_delta_kx.transpose().conj(), (vector_delta_kx_ky-vector_delta_kx)/delta) # 略偏离kx的贝里联络Ay + + # 贝里曲率(berry curvature) + F = (A_y_delta_kx-A_y)/delta-(A_x_delta_ky-A_x)/delta + + # 陈数(chern number) + chern_number = chern_number + F*(2*pi/n)**2 + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/find_smooth_gauge_and_calculate_Chern_number.py b/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/find_smooth_gauge_and_calculate_Chern_number.py new file mode 100755 index 0000000..38696c1 --- /dev/null +++ b/academic_codes/2020.01.05_calculation_of_Chern_number_by_definition_method/find_smooth_gauge_and_calculate_Chern_number.py @@ -0,0 +1,108 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/3932 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import time +import cmath + + +def hamiltonian(kx, ky): # 量子反常霍尔QAH模型(该参数对应的陈数为2) + t1 = 1.0 + t2 = 1.0 + t3 = 0.5 + m = -1.0 + matrix = np.zeros((2, 2))*(1+0j) + matrix[0, 1] = 2*t1*cos(kx)-1j*2*t1*cos(ky) + matrix[1, 0] = 2*t1*cos(kx)+1j*2*t1*cos(ky) + matrix[0, 0] = m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky) + matrix[1, 1] = -(m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky)) + return matrix + + +def main(): + start_time = time.time() + n = 20 # 积分密度 + delta = 1e-9 # 求导的偏离量 + chern_number = 0 # 陈数初始化 + for kx in np.arange(-pi, pi, 2*pi/n): + for ky in np.arange(-pi, pi, 2*pi/n): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + vector_delta_kx = find_vector_with_the_same_gauge(vector_delta_kx, vector) + vector_delta_ky = find_vector_with_the_same_gauge(vector_delta_ky, vector) + vector_delta_kx_ky = find_vector_with_the_same_gauge(vector_delta_kx_ky, vector) + + # 价带的波函数的贝里联络(berry connection) # 求导后内积 + A_x = np.dot(vector.transpose().conj(), (vector_delta_kx-vector)/delta) # 贝里联络Ax(x分量) + A_y = np.dot(vector.transpose().conj(), (vector_delta_ky-vector)/delta) # 贝里联络Ay(y分量) + + A_x_delta_ky = np.dot(vector_delta_ky.transpose().conj(), (vector_delta_kx_ky-vector_delta_ky)/delta) # 略偏离ky的贝里联络Ax + A_y_delta_kx = np.dot(vector_delta_kx.transpose().conj(), (vector_delta_kx_ky-vector_delta_kx)/delta) # 略偏离kx的贝里联络Ay + + # 贝里曲率(berry curvature) + F = (A_y_delta_kx-A_y)/delta-(A_x_delta_ky-A_x)/delta + + # 陈数(chern number) + chern_number = chern_number + F*(2*pi/n)**2 + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + + +def find_vector_with_the_same_gauge(vector_1, vector_0): + # 寻找近似的同一的规范 + phase_1_pre = 0 + phase_2_pre = pi + n_test = 10001 + for i0 in range(n_test): + test_1 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_1_pre) - vector_0)) + test_2 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_2_pre) - vector_0)) + if test_1 < 1e-6: + phase = phase_1_pre + # print('Done with i0=', i0) + break + if i0 == n_test-1: + phase = phase_1_pre + print('Gauge Not Found with i0=', i0) + if test_1 < test_2: + if i0 == 0: + phase_1 = phase_1_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_1_pre + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + if i0 == 0: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre + phase_1_pre = phase_1 + phase_2_pre = phase_2 + vector_1 = vector_1*cmath.exp(1j*phase) + # print('二分查找找到的规范=', phase) + return vector_1 + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.m b/academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.m new file mode 100755 index 0000000..83815b9 --- /dev/null +++ b/academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.m @@ -0,0 +1,40 @@ +% This code is supported by the website: https://www.guanjihuan.com +% The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4179 + +% 陈数高效法 +clear;clc; +n=1000 % 积分密度 +delta=2*pi/n; +C=0; +for kx=-pi:(2*pi/n):pi + for ky=-pi:(2*pi/n):pi + VV=get_vector(HH(kx,ky)); + Vkx=get_vector(HH(kx+delta,ky)); % 略偏离kx的波函数 + Vky=get_vector(HH(kx,ky+delta)); % 略偏离ky的波函数 + Vkxky=get_vector(HH(kx+delta,ky+delta)); % 略偏离kx,ky的波函数 + + Ux = VV'*Vkx/abs(VV'*Vkx); + Uy = VV'*Vky/abs(VV'*Vky); + Ux_y = Vky'*Vkxky/abs(Vky'*Vkxky); + Uy_x = Vkx'*Vkxky/abs(Vkx'*Vkxky); + + % berry curvature + F=log(Ux*Uy_x*(1/Ux_y)*(1/Uy)); + % chern number + C=C+F; + end +end +C=C/(2*pi*1i) + +function vector_new = get_vector(H) +[vector,eigenvalue] = eig(H); +[eigenvalue, index]=sort(diag(eigenvalue), 'descend'); +vector_new = vector(:, index(2)); +end + +function H=HH(kx,ky) +H(1,2)=2*cos(kx)-1i*2*cos(ky); +H(2,1)=2*cos(kx)+1i*2*cos(ky); +H(1,1)=-1+2*0.5*sin(kx)+2*0.5*sin(ky)+2*cos(kx+ky); +H(2,2)=-(-1+2*0.5*sin(kx)+2*0.5*sin(ky)+2*cos(kx+ky)); +end \ No newline at end of file diff --git a/academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.py b/academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.py new file mode 100755 index 0000000..fe31f16 --- /dev/null +++ b/academic_codes/2020.02.26_calculation_of_Chern_number_by_efficient_method/calculation_of_Chern_number_by_efficient_method.py @@ -0,0 +1,65 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4179 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time + + +def hamiltonian(kx, ky): # 量子反常霍尔QAH模型(该参数对应的陈数为2) + t1 = 1.0 + t2 = 1.0 + t3 = 0.5 + m = -1.0 + matrix = np.zeros((2, 2))*(1+0j) + matrix[0, 1] = 2*t1*cos(kx)-1j*2*t1*cos(ky) + matrix[1, 0] = 2*t1*cos(kx)+1j*2*t1*cos(ky) + matrix[0, 0] = m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky) + matrix[1, 1] = -(m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky)) + return matrix + + +def main(): + start_time = time.time() + n = 100 + delta = 2*pi/n + chern_number = 0 # 陈数初始化 + for kx in np.arange(-pi, pi, 2*pi/n): + for ky in np.arange(-pi, pi, 2*pi/n): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) + Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) + Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) + Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) + + F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) + + # 陈数(chern number) + chern_number = chern_number + F + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_1.py b/academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_1.py new file mode 100755 index 0000000..a655c58 --- /dev/null +++ b/academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_1.py @@ -0,0 +1,69 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4322 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k, N): + # 初始化为零矩阵 + h = np.zeros((4*N, 4*N), dtype=complex) + + t=1 + a=1 + t0=0.2 # 层间跃迁 + V=0.2 # 层间的势能差为2V + + for i in range(N): + h[i*4+0, i*4+0] = V + h[i*4+1, i*4+1] = V + h[i*4+2, i*4+2] = -V + h[i*4+3, i*4+3] = -V + + h[i*4+0, i*4+1] = -t*(1+cmath.exp(1j*k*a)) + h[i*4+1, i*4+0] = -t*(1+cmath.exp(-1j*k*a)) + h[i*4+2, i*4+3] = -t*(1+cmath.exp(1j*k*a)) + h[i*4+3, i*4+2] = -t*(1+cmath.exp(-1j*k*a)) + + h[i*4+0, i*4+3] = -t0 + h[i*4+3, i*4+0] = -t0 + + for i in range(N-1): + # 最近邻 + h[i*4+1, (i+1)*4+0] = -t + h[(i+1)*4+0, i*4+1] = -t + + h[i*4+3, (i+1)*4+2] = -t + h[(i+1)*4+2, i*4+3] = -t + return h + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, N=100) + k = np.linspace(-pi, pi, 400) + plot_bands_one_dimension(k, hamiltonian0) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + print(k0) + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_2.py b/academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_2.py new file mode 100755 index 0000000..c9f1b71 --- /dev/null +++ b/academic_codes/2020.03.25_Hamiltonian_and_bands_of_bilayer_graphene/bands_of_bilayer_graphene_with_label_sequence_2.py @@ -0,0 +1,83 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4322 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k, N): + # 初始化为零矩阵 + h = np.zeros((4*N, 4*N), dtype=complex) + h11 = np.zeros((4*N, 4*N), dtype=complex) # 元胞内 + h12 = np.zeros((4*N, 4*N), dtype=complex) # 元胞间 + + t=1 + a=1 + t0=0.2 # 层间跃迁 + V=0.2 # 层间的势能差为2V + + for i in range(N): + h11[i*2+0, i*2+0] = V + h11[i*2+1, i*2+1] = V + + + h11[N*2+i*2+0, N*2+i*2+0] = -V + h11[N*2+i*2+1, N*2+i*2+1] = -V + + + h11[i*2+0, i*2+1] = -t + h11[i*2+1, i*2+0] = -t + + + h11[N*2+i*2+0, N*2+i*2+1] = -t + h11[N*2+i*2+1, N*2+i*2+0] = -t + + h11[i*2+0, N*2+i*2+1] = -t0 + h11[N*2+i*2+1, i*2+0] = -t0 + + + for i in range(N-1): + h11[i*2+1, (i+1)*2+0] = -t + h11[(i+1)*2+0, i*2+1] = -t + + h11[N*2+i*2+1, N*2+(i+1)*2+0] = -t + h11[N*2+(i+1)*2+0, N*2+i*2+1] = -t + + + for i in range(N): + h12[i*2+0, i*2+1] = -t + h12[N*2+i*2+0, N*2+i*2+1] = -t + + h= h11 + h12*cmath.exp(-1j*k*a) + h12.transpose().conj()*cmath.exp(1j*k*a) + return h + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, N=100) + k = np.linspace(-pi, pi, 400) + plot_bands_one_dimension(k, hamiltonian0) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + print(k0) + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_graphene.py b/academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_graphene.py new file mode 100755 index 0000000..6686dcc --- /dev/null +++ b/academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_graphene.py @@ -0,0 +1,56 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4622 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 +plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 + + +def hamiltonian(width=8, length=8): # 石墨烯格子的哈密顿量。这里width要求为4的倍数 + h = np.zeros((width*length, width*length)) + # y方向的跃迁 + for x in range(length): + for y in range(width-1): + h[x*width+y, x*width+y+1] = 1 + h[x*width+y+1, x*width+y] = 1 + + # x方向的跃迁 + for x in range(length-1): + for y in range(width): + if np.mod(y, 4)==0: + h[x*width+y+1, (x+1)*width+y] = 1 + h[(x+1)*width+y, x*width+y+1] = 1 + + h[x*width+y+2, (x+1)*width+y+3] = 1 + h[(x+1)*width+y+3, x*width+y+2] = 1 + + return h + + +def main(): + plot_precision = 0.01 # 画图的精度 + Fermi_energy_array = np.arange(-5, 5, plot_precision) # 计算中取的费米能Fermi_energy组成的数组 + dim_energy = Fermi_energy_array.shape[0] # 需要计算的费米能的个数 + total_DOS_array = np.zeros((dim_energy)) # 计算结果(总态密度total_DOS)放入该数组中 + h = hamiltonian() # 体系的哈密顿量 + dim = h.shape[0] # 哈密顿量的维度 + i0 = 0 + for Fermi_energy in Fermi_energy_array: + print(Fermi_energy) # 查看计算的进展情况 + green = np.linalg.inv((Fermi_energy+0.1j)*np.eye(dim)-h) # 体系的格林函数 + total_DOS = -np.trace(np.imag(green))/pi # 通过格林函数求得总态密度 + total_DOS_array[i0] = total_DOS # 记录每个Fermi_energy对应的总态密度 + i0 += 1 + sum_up = np.sum(total_DOS_array)*plot_precision # 用于图像归一化 + plt.plot(Fermi_energy_array, total_DOS_array/sum_up, '-') # 画DOS(E)图像 + plt.xlabel('费米能') + plt.ylabel('总态密度') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_square_lattice.py b/academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_square_lattice.py new file mode 100755 index 0000000..911a50b --- /dev/null +++ b/academic_codes/2020.06.16_total_DOS_as_a_function_of_Fermi_energy_in_square_lattice_and_graphene/total_DOS_as_a_function_of_Fermi_energy_in_square_lattice.py @@ -0,0 +1,52 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4622 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 +plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 + + +def hamiltonian(width=10, length=10): # 方格子哈密顿量 + h = np.zeros((width*length, width*length)) + # y方向的跃迁 + for x in range(length): + for y in range(width-1): + h[x*width+y, x*width+y+1] = 1 + h[x*width+y+1, x*width+y] = 1 + + # x方向的跃迁 + for x in range(length-1): + for y in range(width): + h[x*width+y, (x+1)*width+y] = 1 + h[(x+1)*width+y, x*width+y] = 1 + + return h + + +def main(): + plot_precision = 0.01 # 画图的精度 + Fermi_energy_array = np.arange(-5, 5, plot_precision) # 计算中取的费米能Fermi_energy组成的数组 + dim_energy = Fermi_energy_array.shape[0] # 需要计算的费米能的个数 + total_DOS_array = np.zeros((dim_energy)) # 计算结果(总态密度total_DOS)放入该数组中 + h = hamiltonian() # 体系的哈密顿量 + dim = h.shape[0] # 哈密顿量的维度 + i0 = 0 + for Fermi_energy in Fermi_energy_array: + print(Fermi_energy) # 查看计算的进展情况 + green = np.linalg.inv((Fermi_energy+0.1j)*np.eye(dim)-h) # 体系的格林函数 + total_DOS = -np.trace(np.imag(green))/pi # 通过格林函数求得总态密度 + total_DOS_array[i0] = total_DOS # 记录每个Fermi_energy对应的总态密度 + i0 += 1 + sum_up = np.sum(total_DOS_array)*plot_precision # 用于图像归一化 + plt.plot(Fermi_energy_array, total_DOS_array/sum_up, '-') # 画DOS(E)图像 + plt.xlabel('费米能') + plt.ylabel('总态密度') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.06.25_numerically_verify_Green_functions_in_Dyson_equations/numerically_verify_Green_functions_in_Dyson_equations.py b/academic_codes/2020.06.25_numerically_verify_Green_functions_in_Dyson_equations/numerically_verify_Green_functions_in_Dyson_equations.py new file mode 100755 index 0000000..4121853 --- /dev/null +++ b/academic_codes/2020.06.25_numerically_verify_Green_functions_in_Dyson_equations/numerically_verify_Green_functions_in_Dyson_equations.py @@ -0,0 +1,84 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4396 +""" + +import numpy as np +import matplotlib.pyplot as plt +import copy +import time + + +def matrix_00(width): # 一个切片(slide)内的哈密顿量 + h00 = np.zeros((width, width)) + for width0 in range(width-1): + h00[width0, width0+1] = 1 + h00[width0+1, width0] = 1 + return h00 + + +def matrix_01(width): # 切片之间的跃迁项(hopping) + h01 = np.identity(width) + return h01 + + +def matrix_whole(width, length): # 方格子整体的哈密顿量,宽度为width,长度为length + hamiltonian = np.zeros((width*length, width*length)) + for x in range(length): + for y in range(width-1): + hamiltonian[x*width+y, x*width+y+1] = 1 + hamiltonian[x*width+y+1, x*width+y] = 1 + for x in range(length-1): + for y in range(width): + hamiltonian[x*width+y, (x+1)*width+y] = 1 + hamiltonian[(x+1)*width+y, x*width+y] = 1 + return hamiltonian + + +def main(): + width =4 # 方格子的宽度 + length = 200 # 方格子的长度 + h00 = matrix_00(width) # 一个切片(slide)内的哈密顿量 + h01 = matrix_01(width) # 切片之间的跃迁项(hopping) + hamiltonian = matrix_whole(width, length) # 方格子整体的哈密顿量,宽度为width,长度为length + fermi_energy = 0.1 # 费米能取为0.1为例。按理来说计算格林函数时,这里需要加上一个无穷小的虚数,但Python中好像不加也不会有什么问题。 + + start_1= time.perf_counter() + green = General_way(fermi_energy, hamiltonian) # 利用通常直接求逆的方法得到整体的格林函数green + end_1 = time.perf_counter() + start_2= time.perf_counter() + green_0n_n = Dyson_way(fermi_energy, h00, h01, length) # 利用Dyson方程得到的格林函数green_0n + end_2 = time.perf_counter() + + # print(green) + print('\n整体格林函数中的一个分块矩阵green_0n:\n', green[0:width, (length-1)*width+0:(length-1)*width+width]) # a:b代表 a <= x < b,左闭右开 + print('Dyson方程得到的格林函数green_0n:\n', green_0n_n) + print('观察以上两个矩阵,可以直接看出两个矩阵完全相同。\n') + + print('General_way执行时间=', end_1-start_1) + print('Dyson_way执行时间=', end_2-start_2) + + +def General_way(fermi_energy, hamiltonian): + dim_hamiltonian = hamiltonian.shape[0] + green = np.linalg.inv((fermi_energy)*np.eye(dim_hamiltonian)-hamiltonian) + return green + + +def Dyson_way(fermi_energy, h00, h01, length): + dim = h00.shape[0] + for ix in range(length): + if ix == 0: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00) # 如果有左电极,还需要减去左电极的自能left_self_energy + green_0n_n = copy.deepcopy(green_nn_n) # 如果直接用等于,两个变量会指向相同的id,改变一个值,另外一个值可能会发生改变,容易出错,所以要用上这个COPY + elif ix != length-1: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + green_0n_n = np.dot(np.dot(green_0n_n, h01), green_nn_n) + else: # 这里和(elif ix != length-1)中的内容完全一样,但如果有右电极,这里是还需要减去右电极的自能right_self_energy + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + green_0n_n = np.dot(np.dot(green_0n_n, h01), green_nn_n) + return green_0n_n + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.06.26_Hamiltonian_and_bands_of_Kane_Mele_model_without considering_Rashba_SOC/bands_of_quasi_1D_Kane_Mele_model_without considering_Rashba_SOC.py b/academic_codes/2020.06.26_Hamiltonian_and_bands_of_Kane_Mele_model_without considering_Rashba_SOC/bands_of_quasi_1D_Kane_Mele_model_without considering_Rashba_SOC.py new file mode 100755 index 0000000..062e399 --- /dev/null +++ b/academic_codes/2020.06.26_Hamiltonian_and_bands_of_Kane_Mele_model_without considering_Rashba_SOC/bands_of_quasi_1D_Kane_Mele_model_without considering_Rashba_SOC.py @@ -0,0 +1,104 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4829 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import functools + + +def hamiltonian(k, N, M, t1, t2, phi): # Kane-Mele model + # 初始化为零矩阵 + h00 = np.zeros((2*4*N, 2*4*N), dtype=complex) # 因为自旋有上有下,所以整个维度要乘2。这里4是元胞内部重复单位的大小,规定元胞大小以4来倍增。 + h01 = np.zeros((2*4*N, 2*4*N), dtype=complex) + + for spin in range(2): + # 原胞内的跃迁h00 + for i in range(N): + # 最近邻 + h00[i*4*2+0*2+spin, i*4*2+1*2+spin] = t1 + h00[i*4*2+1*2+spin, i*4*2+0*2+spin] = t1 + + h00[i*4*2+1*2+spin, i*4*2+2*2+spin] = t1 + h00[i*4*2+2*2+spin, i*4*2+1*2+spin] = t1 + + h00[i*4*2+2*2+spin, i*4*2+3*2+spin] = t1 + h00[i*4*2+3*2+spin, i*4*2+2*2+spin] = t1 + + # 次近邻 + h00[i*4*2+0*2+spin, i*4*2+2*2+spin] = t2*cmath.exp(-1j*phi)*sign_spin(spin) + h00[i*4*2+2*2+spin, i*4*2+0*2+spin] = h00[i*4*2+0*2+spin, i*4*2+2*2+spin].conj() + h00[i*4*2+1*2+spin, i*4*2+3*2+spin] = t2*cmath.exp(-1j*phi)*sign_spin(spin) + h00[i*4*2+3*2+spin, i*4*2+1*2+spin] = h00[i*4*2+1*2+spin, i*4*2+3*2+spin].conj() + + for i in range(N-1): + # 最近邻 + h00[i*4*2+3*2+spin, (i+1)*4*2+0*2+spin] = t1 + h00[(i+1)*4*2+0*2+spin, i*4*2+3*2+spin] = t1 + + # 次近邻 + h00[i*4*2+2*2+spin, (i+1)*4*2+0*2+spin] = t2*cmath.exp(1j*phi)*sign_spin(spin) + h00[(i+1)*4*2+0*2+spin, i*4*2+2*2+spin] = h00[i*4*2+2*2+spin, (i+1)*4*2+0*2+spin].conj() + h00[i*4*2+3*2+spin, (i+1)*4*2+1*2+spin] = t2*cmath.exp(1j*phi)*sign_spin(spin) + h00[(i+1)*4*2+1*2+spin, i*4*2+3*2+spin] = h00[i*4*2+3*2+spin, (i+1)*4*2+1*2+spin].conj() + + # 原胞间的跃迁h01 + for i in range(N): + # 最近邻 + h01[i*4*2+1*2+spin, i*4*2+0*2+spin] = t1 + h01[i*4*2+2*2+spin, i*4*2+3*2+spin] = t1 + + # 次近邻 + h01[i*4*2+0*2+spin, i*4*2+0*2+spin] = t2*cmath.exp(1j*phi)*sign_spin(spin) + h01[i*4*2+1*2+spin, i*4*2+1*2+spin] = t2*cmath.exp(-1j*phi)*sign_spin(spin) + h01[i*4*2+2*2+spin, i*4*2+2*2+spin] = t2*cmath.exp(1j*phi)*sign_spin(spin) + h01[i*4*2+3*2+spin, i*4*2+3*2+spin] = t2*cmath.exp(-1j*phi)*sign_spin(spin) + + h01[i*4*2+1*2+spin, i*4*2+3*2+spin] = t2*cmath.exp(1j*phi)*sign_spin(spin) + h01[i*4*2+2*2+spin, i*4*2+0*2+spin] = t2*cmath.exp(-1j*phi)*sign_spin(spin) + + if i != 0: + h01[i*4*2+1*2+spin, (i-1)*4*2+3*2+spin] = t2*cmath.exp(1j*phi)*sign_spin(spin) + + for i in range(N-1): + h01[i*4*2+2*2+spin, (i+1)*4*2+0*2+spin] = t2*cmath.exp(-1j*phi)*sign_spin(spin) + + matrix = h00 + h01*cmath.exp(1j*k) + h01.transpose().conj()*cmath.exp(-1j*k) + return matrix + + +def sign_spin(spin): + if spin==0: + sign=1 + else: + sign=-1 + return sign + + +def main(): + hamiltonian0 = functools.partial(hamiltonian, N=20, M=0, t1=1, t2=0.03, phi=pi/2) + k = np.linspace(0, 2*pi, 300) + plot_bands_one_dimension(k, hamiltonian0) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.ylim(-1, 1) + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model.py b/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model.py new file mode 100755 index 0000000..a542708 --- /dev/null +++ b/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model.py @@ -0,0 +1,91 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5133 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time +import functools # 使用偏函数functools.partial() + + +def hamiltonian(k1, k2, M, t1, t2, phi, a=1/sqrt(3)): # Haldane哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + # 初始化为零矩阵 + h0 = np.zeros((2, 2))*(1+0j) # 乘(1+0j)是为了把h0转为复数 + h1 = np.zeros((2, 2))*(1+0j) + h2 = np.zeros((2, 2))*(1+0j) + + # 质量项(mass term), 用于打开带隙 + h0[0, 0] = M + h0[1, 1] = -M + + # 最近邻项 + h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h1[0, 1] = h1[1, 0].conj() + + #次近邻项 # 对应陈数为-1 + h2[0, 0] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + h2[1, 1] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + # # 次近邻项 # 对应陈数为1 + # h2[0, 0] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + # h2[1, 1] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + matrix = h0 + h1 + h2 + h2.transpose().conj() + return matrix + + +def main(): + start_clock = time.perf_counter() + delta = 0.005 + chern_number = 0 # 陈数初始化 + + # 几个坐标中常出现的项 + a = 1/sqrt(3) + aa1 = 4*sqrt(3)*pi/9/a + aa2 = 2*sqrt(3)*pi/9/a + bb1 = 2*pi/3/a + + hamiltonian0 = functools.partial(hamiltonian, M=2/3, t1=1, t2=1/3, phi=pi/4, a=a) # 使用偏函数,固定一些参数 + + for kx in np.arange(-aa1, aa1, delta): + print(kx) + for ky in np.arange(-bb1, bb1, delta): + if (-aa2<=kx<=aa2) or (kx>aa2 and -(aa1-kx)*tan(pi/3)<=ky<=(aa1-kx)*tan(pi/3)) or (kx<-aa2 and -(kx-(-aa1))*tan(pi/3)<=ky<=(kx-(-aa1))*tan(pi/3)): # 限制在六角格子布里渊区内 + + H = hamiltonian0(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian0(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian0(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian0(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) + Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) + Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) + Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) + + F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) + + # 陈数(chern number) + chern_number = chern_number + F + + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_clock = time.perf_counter() + print('CPU执行时间(min)=', (end_clock-start_clock)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_2.py b/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_2.py new file mode 100755 index 0000000..eefbcda --- /dev/null +++ b/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_2.py @@ -0,0 +1,87 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5133 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time +import functools # 使用偏函数functools.partial() + + +def hamiltonian(k1, k2, M, t1, t2, phi, a=1/sqrt(3)): # Haldane哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + # 初始化为零矩阵 + h0 = np.zeros((2, 2))*(1+0j) # 乘(1+0j)是为了把h0转为复数 + h1 = np.zeros((2, 2))*(1+0j) + h2 = np.zeros((2, 2))*(1+0j) + + # 质量项(mass term), 用于打开带隙 + h0[0, 0] = M + h0[1, 1] = -M + + # 最近邻项 + h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h1[0, 1] = h1[1, 0].conj() + + #次近邻项 # 对应陈数为-1 + h2[0, 0] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + h2[1, 1] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + # # 次近邻项 # 对应陈数为1 + # h2[0, 0] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + # h2[1, 1] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + matrix = h0 + h1 + h2 + h2.transpose().conj() + return matrix + + +def main(): + start_clock = time.perf_counter() + delta = 0.005 + chern_number = 0 # 陈数初始化 + + # 常出现的项 + a = 1/sqrt(3) + bb1 = 2*sqrt(3)*pi/3/a + bb2 = 2*pi/3/a + + hamiltonian0 = functools.partial(hamiltonian, M=2/3, t1=1, t2=1/3, phi=pi/4, a=a) # 使用偏函数,固定一些参数 + + for kx in np.arange(0 , bb1, delta): + print(kx) + for ky in np.arange(0, 2*bb2, delta): + H = hamiltonian0(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian0(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian0(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian0(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) + Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) + Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) + Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) + + F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) + # 陈数(chern number) + chern_number = chern_number + F + + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_clock = time.perf_counter() + print('CPU执行时间(min)=', (end_clock-start_clock)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_3.py b/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_3.py new file mode 100755 index 0000000..c76d62d --- /dev/null +++ b/academic_codes/2020.07.13_calculation_of_Chern_number_in_Haldane_model/Chern_number_in_Haldane_model_by_integration_method_3.py @@ -0,0 +1,95 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5133 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time +import functools # 使用偏函数functools.partial() + + +def hamiltonian(k1, k2, M, t1, t2, phi, a=1/sqrt(3)): # Haldane哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + # 初始化为零矩阵 + h0 = np.zeros((2, 2))*(1+0j) # 乘(1+0j)是为了把h0转为复数 + h1 = np.zeros((2, 2))*(1+0j) + h2 = np.zeros((2, 2))*(1+0j) + + # 质量项(mass term), 用于打开带隙 + h0[0, 0] = M + h0[1, 1] = -M + + # 最近邻项 + h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h1[0, 1] = h1[1, 0].conj() + + #次近邻项 # 对应陈数为-1 + h2[0, 0] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + h2[1, 1] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + # # 次近邻项 # 对应陈数为1 + # h2[0, 0] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + # h2[1, 1] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*sqrt(3)*k1*a)+cmath.exp(-1j*sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)) + + matrix = h0 + h1 + h2 + h2.transpose().conj() + return matrix + + +def main(): + start_clock = time.perf_counter() + delta = 0.005 + chern_number = 0 # 陈数初始化 + + # 常出现的项 + a = 1/sqrt(3) + bb1 = 2*sqrt(3)*pi/3/a + bb2 = 2*pi/3/a + + hamiltonian0 = functools.partial(hamiltonian, M=2/3, t1=1, t2=1/3, phi=pi/4, a=a) # 使用偏函数,固定一些参数 + + for k1 in np.arange(0 , 1, delta): + print(k1) + for k2 in np.arange(0, 1, delta): + # 坐标变换 + kx = (k1-k2)*bb1 + ky = (k1+k2)*bb2 + + # 这里乘2或除以2是为了保证“步长与积分个数的乘积刚好为布里渊区面积” + delta_x = delta*bb1*2 + delta_y = delta*bb2*2/2 + + H = hamiltonian0(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian0(kx+delta_x, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian0(kx, ky+delta_y) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian0(kx+delta_x, ky+delta_y) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) + Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) + Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) + Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) + + F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) + # 陈数(chern number) + chern_number = chern_number + F + + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_clock = time.perf_counter() + print('CPU执行时间(min)=', (end_clock-start_clock)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/Winding_number_in_SSH_model.py b/academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/Winding_number_in_SSH_model.py new file mode 100755 index 0000000..93c5da1 --- /dev/null +++ b/academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/Winding_number_in_SSH_model.py @@ -0,0 +1,41 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5025 +""" + + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import time + +def hamiltonian(k): # SSH模型 + v=0.6 + w=1 + matrix = np.zeros((2, 2), dtype=complex) + matrix[0,1] = v+w*cmath.exp(-1j*k) + matrix[1,0] = v+w*cmath.exp(1j*k) + return matrix + + +def main(): + start_clock = time.perf_counter() + delta_1 = 1e-9 # 求导的步长(求导的步长可以尽可能短) + delta_2 = 1e-5 # 积分的步长(积分步长和计算时间相关,因此取一个合理值即可) + W = 0 # Winding number初始化 + for k in np.arange(-pi, pi, delta_2): + H = hamiltonian(k) + log0 = cmath.log(H[0, 1]) + + H_delta = hamiltonian(k+delta_1) + log1 = cmath.log(H_delta[0, 1]) + + W = W + (log1-log0)/delta_1*delta_2 # Winding number + print('Winding number = ', W/2/pi/1j) + end_clock = time.perf_counter() + print('CPU执行时间(min)=', (end_clock-start_clock)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/bands_of_SSH_model.py b/academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/bands_of_SSH_model.py new file mode 100755 index 0000000..6e669c6 --- /dev/null +++ b/academic_codes/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/bands_of_SSH_model.py @@ -0,0 +1,42 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5025 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath + + +def hamiltonian(k): # SSH模型 + v=0.6 + w=1 + matrix = np.zeros((2, 2), dtype=complex) + matrix[0,1] = v+w*cmath.exp(-1j*k) + matrix[1,0] = v+w*cmath.exp(1j*k) + return matrix + + +def main(): + k = np.linspace(-pi, pi, 100) + plot_bands_one_dimension(k, hamiltonian) + + +def plot_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_direct_assigning.py b/academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_direct_assigning.py new file mode 100755 index 0000000..88ce253 --- /dev/null +++ b/academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_direct_assigning.py @@ -0,0 +1,23 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5375 +""" + +import numpy as np + +def hamiltonian(width=3, length=3): # 方格子哈密顿量 + h = np.zeros((width*length, width*length)) + # y方向的跃迁 + for x in range(length): + for y in range(width-1): + h[x*width+y, x*width+y+1] = 1 + h[x*width+y+1, x*width+y] = 1 + # x方向的跃迁 + for x in range(length-1): + for y in range(width): + h[x*width+y, (x+1)*width+y] = 1 + h[(x+1)*width+y, x*width+y] = 1 + return h + +h = hamiltonian() +print(h) \ No newline at end of file diff --git a/academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_tensor_product.py b/academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_tensor_product.py new file mode 100755 index 0000000..43b72cd --- /dev/null +++ b/academic_codes/2020.08.10_Hamiltonian_form_of_square_lattice_in_real_space/form_of_tensor_product.py @@ -0,0 +1,21 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5375 +""" + +import numpy as np + +def hamiltonian(width=3, length=3): # 方格子哈密顿量 + hopping_x = np.zeros((length, length)) + hopping_y = np.zeros((width, width)) + for i in range(length-1): + hopping_x[i, i+1] = 1 + hopping_x[i+1, i] = 1 + for i in range(width-1): + hopping_y[i, i+1] = 1 + hopping_y[i+1, i] = 1 + h = np.kron(hopping_x, np.eye(width))+np.kron(np.eye(length), hopping_y) + return h + +h = hamiltonian() +print(h) \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/plot_with_2D_data.py b/academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/plot_with_2D_data.py new file mode 100755 index 0000000..2ebd053 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/plot_with_2D_data.py @@ -0,0 +1,30 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +def main(): + k1 = np.arange(-pi, pi, 0.05) + k2 = np.arange(-pi, pi, 0.05) + value = np.ones((k2.shape[0], k1.shape[0])) + plot_matrix(k1, k2, value) + + +def plot_matrix(k1, k2, matrix): + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + ax.plot_surface(k1, k2, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.xlabel('k1') + plt.ylabel('k2') + ax.set_zlabel('Z') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/write_2D_data_into_txt_file.py b/academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/write_2D_data_into_txt_file.py new file mode 100755 index 0000000..bb0fd48 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/2D_data_plot_and_write/write_2D_data_into_txt_file.py @@ -0,0 +1,31 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +def main(): + k1 = np.arange(-pi, pi, 0.05) + k2 = np.arange(-pi, pi, 0.05) + value = np.ones((k2.shape[0], k1.shape[0])) + write_matrix(k1, k2, value) + + +def write_matrix(k1, k2, matrix): + with open('a.txt', 'w') as f: + # np.set_printoptions(suppress=True) # 取消输出科学记数法 + f.write('0 ') + for k10 in k1: + f.write(str(k10)+' ') + f.write('\n') + i0 = 0 + for k20 in k2: + f.write(str(k20)) + for j0 in range(k1.shape[0]): + f.write(' '+str(matrix[i0, j0])+' ') + f.write('\n') + i0 += 1 + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_1D_bands.py b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_1D_bands.py new file mode 100755 index 0000000..448dbf4 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_1D_bands.py @@ -0,0 +1,35 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +def hamiltonian(k): + pass + + +def main(): + k = np.arange(-pi, pi, 0.05) + plot_bands_one_dimension(k, hamiltonian) + + +def plot_bands_one_dimension(k, hamiltonian): + import matplotlib.pyplot as plt + dim = hamiltonian(0).shape[0] + dim_k = k.shape[0] + eigenvalue_k = np.zeros((dim_k, dim)) + i0 = 0 + for k0 in k: + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(k, eigenvalue_k[:, dim0], '-k') + plt.xlabel('k') + plt.ylabel('E') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_2D_bands.py b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_2D_bands.py new file mode 100755 index 0000000..0aab40a --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_plot_2D_bands.py @@ -0,0 +1,47 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +def hamiltonian(k1, k2): + pass + + +def main(): + k1 = np.arange(-pi, pi, 0.05) + k2 = np.arange(-pi, pi, 0.05) + plot_bands_two_dimension(k1, k2, hamiltonian) + + +def plot_bands_two_dimension(k1, k2, hamiltonian): + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + dim = hamiltonian(0, 0).shape[0] + dim1 = k1.shape[0] + dim2 = k2.shape[0] + eigenvalue_k = np.zeros((dim2, dim1, dim)) + i0 = 0 + for k20 in k2: + j0 = 0 + for k10 in k1: + matrix0 = hamiltonian(k10, k20) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[i0, j0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + for dim0 in range(dim): + ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.xlabel('k1') + plt.ylabel('k2') + ax.set_zlabel('E') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_1D_data_into_txt_file.py b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_1D_data_into_txt_file.py new file mode 100755 index 0000000..46a0198 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_1D_data_into_txt_file.py @@ -0,0 +1,31 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +def hamiltonian(k): + pass + + +def main(): + k = np.arange(-pi, pi, 0.05) + write_bands_one_dimension(k, hamiltonian) + + +def write_bands_one_dimension(k, hamiltonian): + dim = hamiltonian(0).shape[0] + f = open('a.txt','w') + for k0 in k: + f.write(str(k0)+' ') + matrix0 = hamiltonian(k0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue = np.sort(np.real(eigenvalue)) + for dim0 in range(dim): + f.write(str(eigenvalue[dim0])+' ') + f.write('\n') + f.close() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_2D_data_into_txt_file.py b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_2D_data_into_txt_file.py new file mode 100755 index 0000000..761d0a4 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/get_eigenvalues_plot_and_write/get_eigenvalues_and_write_2D_data_into_txt_file.py @@ -0,0 +1,42 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +def hamiltonian(k1, k2): + pass + + +def main(): + k1 = np.arange(-pi, pi, 0.05) + k2 = np.arange(-pi, pi, 0.05) + write_bands_two_dimension(k1, k2, hamiltonian) + + +def write_bands_two_dimension(k1, k2, hamiltonian): + f1 = open('a1.txt', 'w') + f2 = open('a2.txt', 'w') + f1.write('0 ') + f2.write('0 ') + for k10 in k1: + f1.write(str(k10)+' ') + f2.write(str(k10)+' ') + f1.write('\n') + f2.write('\n') + for k20 in k2: + f1.write(str(k20)+' ') + f2.write(str(k20)+' ') + for k10 in k1: + matrix0 = hamiltonian(k10, k20) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue = np.sort(np.real(eigenvalue)) + f1.write(str(eigenvalue[0])+' ') + f2.write(str(eigenvalue[1])+' ') + f1.write('\n') + f2.write('\n') + f1.close() + f2.close() + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/python_structure.py b/academic_codes/2020.08.29_several_python_functions/python_structure.py new file mode 100755 index 0000000..476ea8c --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/python_structure.py @@ -0,0 +1,7 @@ +import numpy as np # 导入numpy库,用来存储和处理大型矩阵,比python自带的嵌套列表更高效。numpy库还包含了许多数学函数库。python+numpy等同于matlab。 + +def main(): # 主函数的内容放在这里。 + pass + +if __name__ == '__main__': # 如果是当前文件直接运行,执行main()函数中的内容;如果是import当前文件,则不执行。同时将main()语句放在最后运行,可以避免书写的函数出现未定义的情况。 + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/read_txt_file/1D_data.txt b/academic_codes/2020.08.29_several_python_functions/read_txt_file/1D_data.txt new file mode 100755 index 0000000..3d1cc66 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/read_txt_file/1D_data.txt @@ -0,0 +1,4 @@ +1 1.2 2.4 +2 5.5 3.2 +3 6.7 7.1 +4 3.6 4.9 \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/read_txt_file/2D_data.txt b/academic_codes/2020.08.29_several_python_functions/read_txt_file/2D_data.txt new file mode 100755 index 0000000..7d30da5 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/read_txt_file/2D_data.txt @@ -0,0 +1,4 @@ +0 1 2 3 4 +1 1.3 2.7 6.7 8.3 +2 4.3 2.9 5.4 7.4 +3 9.1 8.2 2.6 3.1 \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/read_txt_file/read_1D_data.py b/academic_codes/2020.08.29_several_python_functions/read_txt_file/read_1D_data.py new file mode 100755 index 0000000..ea0dafc --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/read_txt_file/read_1D_data.py @@ -0,0 +1,47 @@ +import numpy as np +import matplotlib.pyplot as plt +# import os +# os.chdir('D:/data') # 设置路径 + + +def main(): + x, y = read_one_dimension('1D_data.txt') + for dim0 in range(y.shape[1]): + plt.plot(x, y[:, dim0], '-k') + plt.show() + + +def read_one_dimension(file_name): + f = open(file_name, 'r') + text = f.read() + f.close() + row_list = np.array(text.split('\n')) # 根据“回车”分割成每一行 + # print('文本格式:') + # print(text) + # print('row_list:') + # print(row_list) + # print('column:') + dim_column = np.array(row_list[0].split()).shape[0] # 列数 + x = np.array([]) + y = np.array([]) + for row in row_list: + column = np.array(row.split()) # 每一行根据“空格”继续分割 + # print(column) + if column.shape[0] != 0: # 解决最后一行空白的问题 + x = np.append(x, [float(column[0])], axis=0) # 第一列为x数据 + y_row = np.zeros(dim_column-1) + for dim0 in range(dim_column-1): + y_row[dim0] = float(column[dim0+1]) + if np.array(y).shape[0] == 0: + y = [y_row] + else: + y = np.append(y, [y_row], axis=0) + # print('x:') + # print(x) + # print('y:') + # print(y) + return x, y + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/read_txt_file/read_2D_data.py b/academic_codes/2020.08.29_several_python_functions/read_txt_file/read_2D_data.py new file mode 100755 index 0000000..b9d1d79 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/read_txt_file/read_2D_data.py @@ -0,0 +1,69 @@ +import numpy as np +# import os +# os.chdir('D:/data') # 设置路径 + + +def main(): + x1, x2, matrix = read_two_dimension('2D_data.txt') + plot_matrix(x1, x2, matrix) + + +def read_two_dimension(file_name): + f = open(file_name, 'r') + text = f.read() + f.close() + row_list = np.array(text.split('\n')) # 根据“回车”分割成每一行 + # print('文本格式:') + # print(text) + # print('row_list:') + # print(row_list) + # print('column:') + dim_column = np.array(row_list[0].split()).shape[0] # 列数 + x1 = np.array([]) + x2 = np.array([]) + matrix = np.array([]) + for i0 in range(row_list.shape[0]): + column = np.array(row_list[i0].split()) # 每一行根据“空格”继续分割 + # print(column) + if i0 == 0: + x1_str = column[1::] # x1坐标(去除第一个在角落的值) + x1 = np.zeros(x1_str.shape[0]) + for i00 in range(x1_str.shape[0]): + x1[i00] = float(x1_str[i00]) # 字符串转浮点 + elif column.shape[0] != 0: # 解决最后一行空白的问题 + x2 = np.append(x2, [float(column[0])], axis=0) # 第一列为x数据 + matrix_row = np.zeros(dim_column-1) + for dim0 in range(dim_column-1): + matrix_row[dim0] = float(column[dim0+1]) + if np.array(matrix).shape[0] == 0: + matrix = [matrix_row] + else: + matrix = np.append(matrix, [matrix_row], axis=0) + # print('x1:') + # print(x1) + # print('x2:') + # print(x2) + # print('matrix:') + # print(matrix) + return x1, x2, matrix + + + +def plot_matrix(x1, x2, matrix): + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + fig = plt.figure() + ax = fig.gca(projection='3d') + x1, x2 = np.meshgrid(x1, x2) + ax.plot_surface(x1, x2, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.xlabel('x1') + plt.ylabel('x2') + ax.set_zlabel('z') + plt.show() + + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.08.29_several_python_functions/running_and_write_2D_data_into_txt_file.py b/academic_codes/2020.08.29_several_python_functions/running_and_write_2D_data_into_txt_file.py new file mode 100755 index 0000000..5944a73 --- /dev/null +++ b/academic_codes/2020.08.29_several_python_functions/running_and_write_2D_data_into_txt_file.py @@ -0,0 +1,18 @@ +import numpy as np +from math import * +# import os +# os.chdir('D:/data') # 设置路径 + + +f = open('a.txt', 'w') +f.write('0 ') +for k1 in np.arange(-pi, pi, 0.05): + f.write(str(k1)+' ') +f.write('\n') +for k2 in np.arange(-pi, pi, 0.05): + f.write(str(k2)+' ') + for k1 in np.arange(-pi, pi, 0.05): + data = 1000 # 运算数据 + f.write(str(data)+' ') + f.write('\n') +f.close() \ No newline at end of file diff --git a/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.m b/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.m new file mode 100755 index 0000000..4ae71f4 --- /dev/null +++ b/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.m @@ -0,0 +1,68 @@ +% This code is supported by the website: https://www.guanjihuan.com +% The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5778 + +clear;clc; +delta=0.1; +Z2=0; +for kx=-pi:0.1:0 + for ky=-pi:0.1:pi + [V1,V2]=get_vector(Hamiltonian(kx,ky)); + [Vkx1,Vkx2]=get_vector(Hamiltonian(kx+delta,ky)); % 略偏离kx的波函数 + [Vky1,Vky2]=get_vector(Hamiltonian(kx,ky+delta)); % 略偏离ky的波函数 + [Vkxky1,Vkxky2]=get_vector(Hamiltonian(kx+delta,ky+delta)); % 略偏离kx,ky的波函数 + + Ux = dot_and_det(V1, Vkx1, V2, Vkx2); + Uy = dot_and_det(V1, Vky1, V2, Vky2); + Ux_y = dot_and_det(Vky1, Vkxky1, Vky2, Vkxky2); + Uy_x = dot_and_det(Vkx1, Vkxky1, Vkx2, Vkxky2); + + F=imag(log(Ux*Uy_x*(conj(Ux_y))*(conj(Uy)))); + A=imag(log(Ux))+imag(log(Uy_x))+imag(log(conj(Ux_y)))+imag(log(conj(Uy))); + + Z2 = Z2+(A-F)/(2*pi); + end +end +Z2= mod(Z2, 2) + + +function dd = dot_and_det(a1,b1,a2,b2) % 内积组成的矩阵对应的行列式 +x1=a1'*b1; +x2=a2'*b2; +x3=a1'*b2; +x4=a2'*b1; +dd =x1*x2-x3*x4; +end + + +function [vector_new_1, vector_new_2] = get_vector(H) +[vector,eigenvalue] = eig(H); +[eigenvalue, index]=sort(diag(eigenvalue), 'ascend'); +vector_new_2 = vector(:, index(2)); +vector_new_1 = vector(:, index(1)); +end + + +function H=Hamiltonian(kx,ky) % BHZ模型 +A=0.3645/5; +B=-0.686/25; +C=0; +D=-0.512/25; +M=-0.01; + +H=zeros(4,4); +varepsilon = C-2*D*(2-cos(kx)-cos(ky)); +d3 = -2*B*(2-(M/2/B)-cos(kx)-cos(ky)); +d1_d2 = A*(sin(kx)+1j*sin(ky)); +H(1, 1) = varepsilon+d3; +H(2, 2) = varepsilon-d3; +H(1, 2) = conj(d1_d2); +H(2, 1) = d1_d2 ; + +varepsilon = C-2*D*(2-cos(-kx)-cos(-ky)); +d3 = -2*B*(2-(M/2/B)-cos(-kx)-cos(-ky)); +d1_d2 = A*(sin(-kx)+1j*sin(-ky)); +H(3, 3) = varepsilon+d3; +H(4, 4) = varepsilon-d3; +H(3, 4) = d1_d2 ; +H(4, 3) = conj(d1_d2); +end \ No newline at end of file diff --git a/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.py b/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.py new file mode 100755 index 0000000..160bf5b --- /dev/null +++ b/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.py @@ -0,0 +1,88 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5778 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time + + +def hamiltonian(kx, ky): # BHZ模型 + A=0.3645/5 + B=-0.686/25 + C=0 + D=-0.512/25 + M=-0.01 + matrix = np.zeros((4, 4))*(1+0j) + + varepsilon = C-2*D*(2-cos(kx)-cos(ky)) + d3 = -2*B*(2-(M/2/B)-cos(kx)-cos(ky)) + d1_d2 = A*(sin(kx)+1j*sin(ky)) + matrix[0, 0] = varepsilon+d3 + matrix[1, 1] = varepsilon-d3 + matrix[0, 1] = np.conj(d1_d2) + matrix[1, 0] = d1_d2 + + varepsilon = C-2*D*(2-cos(-kx)-cos(-ky)) + d3 = -2*B*(2-(M/2/B)-cos(-kx)-cos(-ky)) + d1_d2 = A*(sin(-kx)+1j*sin(-ky)) + matrix[2, 2] = varepsilon+d3 + matrix[3, 3] = varepsilon-d3 + matrix[2, 3] = d1_d2 + matrix[3, 2] = np.conj(d1_d2) + return matrix + + +def main(): + start_clock = time.perf_counter() + delta = 0.1 + Z2 = 0 # Z2数 + for kx in np.arange(-pi, 0, delta): + print(kx) + for ky in np.arange(-pi, pi, delta): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数1 + vector2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 价带波函数2 + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数1 + vector_delta_kx2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离kx的波函数2 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数1 + vector_delta_ky2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离ky的波函数2 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数1 + vector_delta_kx_ky2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离kx和ky的波函数2 + + Ux = dot_and_det(vector, vector_delta_kx, vector2, vector_delta_kx2) + Uy = dot_and_det(vector, vector_delta_ky, vector2, vector_delta_ky2) + Ux_y = dot_and_det(vector_delta_ky, vector_delta_kx_ky, vector_delta_ky2, vector_delta_kx_ky2) + Uy_x = dot_and_det(vector_delta_kx, vector_delta_kx_ky, vector_delta_kx2, vector_delta_kx_ky2) + + F = np.imag(cmath.log(Ux*Uy_x*np.conj(Ux_y)*np.conj(Uy))) + A = np.imag(cmath.log(Ux))+np.imag(cmath.log(Uy_x))+np.imag(cmath.log(np.conj(Ux_y)))+np.imag(cmath.log(np.conj(Uy))) + Z2 = Z2 + (A-F)/(2*pi) + print('Z2 = ', Z2) # Z2数 + end_clock = time.perf_counter() + print('CPU执行时间(min)=', (end_clock-start_clock)/60) + + +def dot_and_det(a1, b1, a2, b2): # 内积组成的矩阵对应的行列式 + x1 = np.dot(np.conj(a1), b1) + x2 = np.dot(np.conj(a2), b2) + x3 = np.dot(np.conj(a1), b2) + x4 = np.dot(np.conj(a2), b1) + return x1*x2-x3*x4 + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/spin_Chern_number_in_BHZ_model.py b/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/spin_Chern_number_in_BHZ_model.py new file mode 100755 index 0000000..a79aa3a --- /dev/null +++ b/academic_codes/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/spin_Chern_number_in_BHZ_model.py @@ -0,0 +1,98 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5778 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time + + +def hamiltonian1(kx, ky): # Half BHZ for spin up + A=0.3645/5 + B=-0.686/25 + C=0 + D=-0.512/25 + M=-0.01 + matrix = np.zeros((2, 2))*(1+0j) + varepsilon = C-2*D*(2-cos(kx)-cos(ky)) + d3 = -2*B*(2-(M/2/B)-cos(kx)-cos(ky)) + d1_d2 = A*(sin(kx)+1j*sin(ky)) + + matrix[0, 0] = varepsilon+d3 + matrix[1, 1] = varepsilon-d3 + matrix[0, 1] = np.conj(d1_d2) + matrix[1, 0] = d1_d2 + return matrix + +def hamiltonian2(kx, ky): # Half BHZ for spin down + A=0.3645/5 + B=-0.686/25 + C=0 + D=-0.512/25 + M=-0.01 + matrix = np.zeros((2, 2))*(1+0j) + varepsilon = C-2*D*(2-cos(-kx)-cos(-ky)) + d3 = -2*B*(2-(M/2/B)-cos(-kx)-cos(-ky)) + d1_d2 = A*(sin(-kx)+1j*sin(-ky)) + + matrix[0, 0] = varepsilon+d3 + matrix[1, 1] = varepsilon-d3 + matrix[0, 1] = d1_d2 + matrix[1, 0] = np.conj(d1_d2) + return matrix + + +def main(): + start_clock = time.perf_counter() + delta = 0.1 + for i0 in range(2): + if i0 == 0: + hamiltonian = hamiltonian1 + else: + hamiltonian = hamiltonian2 + chern_number = 0 # 陈数初始化 + for kx in np.arange(-pi, pi, delta): + print(kx) + for ky in np.arange(-pi, pi, delta): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) + Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) + Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) + Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) + + F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) + # 陈数(chern number) + chern_number = chern_number + F + chern_number = chern_number/(2*pi*1j) + if i0 == 0: + chern_number_up = chern_number + else: + chern_number_down = chern_number + spin_chern_number = (chern_number_up-chern_number_down)/2 + print('Chern number for spin up = ', chern_number_up) + print('Chern number for spin down = ', chern_number_down) + print('Spin chern number = ', spin_chern_number) + end_clock = time.perf_counter() + print('CPU执行时间(min)=', (end_clock-start_clock)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/Fermi_arc_in_Weyl_semimetals.py b/academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/Fermi_arc_in_Weyl_semimetals.py new file mode 100755 index 0000000..8ee5b9e --- /dev/null +++ b/academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/Fermi_arc_in_Weyl_semimetals.py @@ -0,0 +1,64 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6077 +""" + +import numpy as np +from math import * +import matplotlib.pyplot as plt + + +def main(): + n = 0.5 + k1 = np.arange(-n*pi, n*pi, n/50) + k2 = np.arange(-n*pi, n*pi, n/50) + plot_bands_two_dimension_direct(k1, k2, hamiltonian) + + +def hamiltonian(kx,kz,ky=0): # surface states of Weyl semimetal + A = 1 + H = A*kx + return H + + +def sigma_x(): + return np.array([[0, 1],[1, 0]]) + + +def sigma_y(): + return np.array([[0, -1j],[1j, 0]]) + + +def sigma_z(): + return np.array([[1, 0],[0, -1]]) + + +def plot_bands_two_dimension_direct(k1, k2, hamiltonian): + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + fig = plt.figure() + ax = fig.gca(projection='3d') + dim1 = k1.shape[0] + dim2 = k2.shape[0] + eigenvalue_k = np.zeros((dim2, dim1)) + i0 = 0 + for k10 in k1: + j0 = 0 + for k20 in k2: + if (k10**2+k20**2 <= 1): + eigenvalue_k[j0, i0] = hamiltonian(k10, k20) + else: + eigenvalue_k[j0, i0] = 'nan' + j0 += 1 + i0 += 1 + k1, k2 = np.meshgrid(k1, k2) + ax.scatter(k1, k2, eigenvalue_k) + plt.xlabel('kx') + plt.ylabel('kz') + ax.set_zlabel('E') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/bands_of_Weyl_semimetals.py b/academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/bands_of_Weyl_semimetals.py new file mode 100755 index 0000000..8ac9553 --- /dev/null +++ b/academic_codes/2020.09.29_Halmiltonian_and_Fermi_arc_in_Weyl_semimetals/bands_of_Weyl_semimetals.py @@ -0,0 +1,67 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6077 +""" + +import numpy as np +from math import * +import matplotlib.pyplot as plt + + +def main(): + n = 0.5 + k1 = np.arange(-n*pi, n*pi, n/20) + k2 = np.arange(-n*pi, n*pi, n/20) + plot_bands_two_dimension(k1, k2, hamiltonian) + + +def hamiltonian(kx,kz,ky=0): # Weyl semimetal + A = 1 + M0 = 1 + M1 = 1 + H = A*(kx*sigma_x()+ky*sigma_y())+(M0-M1*(kx**2+ky**2+kz**2))*sigma_z() + return H + + +def sigma_x(): + return np.array([[0, 1],[1, 0]]) + + +def sigma_y(): + return np.array([[0, -1j],[1j, 0]]) + + +def sigma_z(): + return np.array([[1, 0],[0, -1]]) + + +def plot_bands_two_dimension(k1, k2, hamiltonian): + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + dim = hamiltonian(0, 0).shape[0] + dim1 = k1.shape[0] + dim2 = k2.shape[0] + eigenvalue_k = np.zeros((dim2, dim1, dim)) + i0 = 0 + for k10 in k1: + j0 = 0 + for k20 in k2: + matrix0 = hamiltonian(k10, k20) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[j0, i0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + for dim0 in range(dim): + ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.xlabel('kx') + plt.ylabel('kz') + ax.set_zlabel('E') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.09.30_bandstructure_of_graphene_on_high_symmetric_axes/bandstructure_of_graphene_on_high_symmetric_axes.py b/academic_codes/2020.09.30_bandstructure_of_graphene_on_high_symmetric_axes/bandstructure_of_graphene_on_high_symmetric_axes.py new file mode 100755 index 0000000..5dd2383 --- /dev/null +++ b/academic_codes/2020.09.30_bandstructure_of_graphene_on_high_symmetric_axes/bandstructure_of_graphene_on_high_symmetric_axes.py @@ -0,0 +1,77 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6260 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入sqrt(), pi, exp等 +import cmath # 要处理复数情况,用到cmath.exp() + + +def hamiltonian(k1, k2, M=0, t1=1, a=1/sqrt(3)): # Haldane哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + h0 = np.zeros((2, 2))*(1+0j) + h1 = np.zeros((2, 2))*(1+0j) + h2 = np.zeros((2, 2))*(1+0j) + + # 质量项(mass term), 用于打开带隙 + h0[0, 0] = M + h0[1, 1] = -M + + # 最近邻项 + h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h1[0, 1] = h1[1, 0].conj() + + # # 最近邻项也可写成这种形式 + # h1[1, 0] = t1+t1*cmath.exp(1j*sqrt(3)/2*k1*a-1j*3/2*k2*a)+t1*cmath.exp(-1j*sqrt(3)/2*k1*a-1j*3/2*k2*a) + # h1[0, 1] = h1[1, 0].conj() + + matrix = h0 + h1 + return matrix + + +def main(): + a = 1/sqrt(3) + Gamma0 = np.array([0, 0]) + M0 = np.array([0, 2*pi/3/a]) + K0 = np.array([2*np.sqrt(3)*pi/9/a, 2*pi/3/a]) + + kn = 100 # 每个区域的取点数 + n = 3 # n个区域(K-Gamma,Gamma-M, M-K) + k1_array = np.zeros(kn*n) + k2_array = np.zeros(kn*n) + + # K-Gamma轴 + k1_array[0:kn] = np.linspace(0, K0[0], kn)[::-1] # [::-1]表示反转数组 + k2_array[0:kn] = np.linspace(0, K0[1], kn)[::-1] + + # Gamma-M轴 + k1_array[kn:2*kn] = np.zeros(kn) + k2_array[kn:2*kn] = np.linspace(0, M0[1], kn) + + # M-K轴 + k1_array[2*kn:3*kn] = np.linspace(0, K0[0], kn) + k2_array[2*kn:3*kn] = np.ones(kn)*M0[1] + + i0 = 0 + dim = hamiltonian(0, 0).shape[0] + eigenvalue_k = np.zeros((kn*n, dim)) + fig, ax = plt.subplots() + for kn0 in range(kn*n): + k1 = k1_array[kn0] + k2 = k2_array[kn0] + eigenvalue, eigenvector = np.linalg.eig(hamiltonian(k1, k2)) + eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + for dim0 in range(dim): + plt.plot(range(kn*n), eigenvalue_k[:, dim0], '-k') + plt.ylabel('E') + ax.set_xticks([0, kn, 2*kn, 3*kn]) + ax.set_xticklabels(['K', 'Gamma', 'M', 'K']) + plt.xlim(0, n*kn) + plt.grid(axis='x',c='r',linestyle='--') + plt.show() + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.10.02_calculate_scattering_matrix_by_mode_matching_method/calculate_scattering_matrix_by_mode_matching_method.py b/academic_codes/2020.10.02_calculate_scattering_matrix_by_mode_matching_method/calculate_scattering_matrix_by_mode_matching_method.py new file mode 100755 index 0000000..0002c57 --- /dev/null +++ b/academic_codes/2020.10.02_calculate_scattering_matrix_by_mode_matching_method/calculate_scattering_matrix_by_mode_matching_method.py @@ -0,0 +1,240 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6352 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import copy +import time +# import os +# os.chdir('D:/data') + + +def main(): + start_time = time.time() + h00 = matrix_00() # 方格子模型 + h01 = matrix_01() # 方格子模型 + fermi_energy = 0.1 + write_transmission_matrix(fermi_energy, h00, h01) # 输出无散射的散射矩阵 + end_time = time.time() + print('运行时间=', end_time - start_time, '秒') + + +def matrix_00(width=4): + h00 = np.zeros((width, width)) + for width0 in range(width-1): + h00[width0, width0+1] = 1 + h00[width0+1, width0] = 1 + return h00 + + +def matrix_01(width=4): + h01 = np.identity(width) + return h01 + + +def transfer_matrix(fermi_energy, h00, h01, dim): # 转移矩阵 + transfer = np.zeros((2*dim, 2*dim))*(0+0j) + transfer[0:dim, 0:dim] = np.dot(np.linalg.inv(h01), fermi_energy*np.identity(dim)-h00) + transfer[0:dim, dim:2*dim] = np.dot(-1*np.linalg.inv(h01), h01.transpose().conj()) + transfer[dim:2*dim, 0:dim] = np.identity(dim) + transfer[dim:2*dim, dim:2*dim] = 0 + return transfer + + +def complex_wave_vector(fermi_energy, h00, h01, dim): # 获取通道的复数波矢,并按照波矢的实部Re(k)排序 + transfer = transfer_matrix(fermi_energy, h00, h01, dim) + eigenvalue, eigenvector = np.linalg.eig(transfer) + k_channel = np.log(eigenvalue)/1j + ind = np.argsort(np.real(k_channel)) + k_channel = np.sort(k_channel) + temp = np.zeros((2*dim, 2*dim))*(1+0j) + temp2 = np.zeros((2*dim))*(1+0j) + i0 = 0 + for ind0 in ind: + temp[:, i0] = eigenvector[:, ind0] + temp2[i0] = eigenvalue[ind0] + i0 += 1 + eigenvalue = copy.deepcopy(temp2) + temp = normalization_of_eigenvector(temp[0:dim, :], dim) + velocity = np.zeros((2*dim))*(1+0j) + for dim0 in range(2*dim): + velocity[dim0] = eigenvalue[dim0]*np.dot(np.dot(temp[0:dim, :].transpose().conj(), h01),temp[0:dim, :])[dim0, dim0] + velocity = -2*np.imag(velocity) + eigenvector = copy.deepcopy(temp) + return k_channel, velocity, eigenvalue, eigenvector # 返回通道的对应的波矢、费米速度、本征值、本征态 + + +def normalization_of_eigenvector(eigenvector, dim): # 波函数归一化 + factor = np.zeros(2*dim)*(1+0j) + for dim0 in range(dim): + factor = factor+np.square(np.abs(eigenvector[dim0, :])) + for dim0 in range(2*dim): + eigenvector[:, dim0] = eigenvector[:, dim0]/np.sqrt(factor[dim0]) + return eigenvector + + +def calculation_of_lambda_u_f(fermi_energy, h00, h01, dim): # 对所有通道(包括active和evanescent)进行分类,并计算F + k_channel, velocity, eigenvalue, eigenvector = complex_wave_vector(fermi_energy, h00, h01, dim) + ind_right_active = 0; ind_right_evanescent = 0; ind_left_active = 0; ind_left_evanescent = 0 + k_right = np.zeros(dim)*(1+0j); k_left = np.zeros(dim)*(1+0j) + velocity_right = np.zeros(dim)*(1+0j); velocity_left = np.zeros(dim)*(1+0j) + lambda_right = np.zeros(dim)*(1+0j); lambda_left = np.zeros(dim)*(1+0j) + u_right = np.zeros((dim, dim))*(1+0j); u_left = np.zeros((dim, dim))*(1+0j) + for dim0 in range(2*dim): + if_active = if_active_channel(k_channel[dim0]) + direction = direction_of_channel(velocity[dim0], k_channel[dim0]) + if direction == 1: # 向右运动的通道 + if if_active == 1: # 可传播通道(active channel) + k_right[ind_right_active] = k_channel[dim0] + velocity_right[ind_right_active] = velocity[dim0] + lambda_right[ind_right_active] = eigenvalue[dim0] + u_right[:, ind_right_active] = eigenvector[:, dim0] + ind_right_active += 1 + else: # 衰减通道(evanescent channel) + k_right[dim-1-ind_right_evanescent] = k_channel[dim0] + velocity_right[dim-1-ind_right_evanescent] = velocity[dim0] + lambda_right[dim-1-ind_right_evanescent] = eigenvalue[dim0] + u_right[:, dim-1-ind_right_evanescent] = eigenvector[:, dim0] + ind_right_evanescent += 1 + else: # 向左运动的通道 + if if_active == 1: # 可传播通道(active channel) + k_left[ind_left_active] = k_channel[dim0] + velocity_left[ind_left_active] = velocity[dim0] + lambda_left[ind_left_active] = eigenvalue[dim0] + u_left[:, ind_left_active] = eigenvector[:, dim0] + ind_left_active += 1 + else: # 衰减通道(evanescent channel) + k_left[dim-1-ind_left_evanescent] = k_channel[dim0] + velocity_left[dim-1-ind_left_evanescent] = velocity[dim0] + lambda_left[dim-1-ind_left_evanescent] = eigenvalue[dim0] + u_left[:, dim-1-ind_left_evanescent] = eigenvector[:, dim0] + ind_left_evanescent += 1 + lambda_matrix_right = np.diag(lambda_right) + lambda_matrix_left = np.diag(lambda_left) + f_right = np.dot(np.dot(u_right, lambda_matrix_right), np.linalg.inv(u_right)) + f_left = np.dot(np.dot(u_left, lambda_matrix_left), np.linalg.inv(u_left)) + return k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active + # 分别返回向右和向左的运动的波矢k、费米速度velocity、F值、U值、可向右传播的通道数 + + +def if_active_channel(k_channel): # 判断是可传播通道还是衰减通道 + if np.abs(np.imag(k_channel)) < 1e-7: + if_active = 1 + else: + if_active = 0 + return if_active + + +def direction_of_channel(velocity, k_channel): # 判断通道对应的费米速度方向 + if if_active_channel(k_channel) == 1: + direction = np.sign(velocity) + else: + direction = np.sign(np.imag(k_channel)) + return direction + + +def calculation_of_green_function(fermi_energy, h00, h01, dim, scatter_type=0, scatter_intensity=0.2, scatter_length=20): # 计算格林函数 + k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active = calculation_of_lambda_u_f(fermi_energy, h00, h01, dim) + right_self_energy = np.dot(h01, f_right) + left_self_energy = np.dot(h01.transpose().conj(), np.linalg.inv(f_left)) + nx = 300 + for nx0 in range(nx): + if nx0 == 0: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-left_self_energy) + green_00_n = copy.deepcopy(green_nn_n) + green_0n_n = copy.deepcopy(green_nn_n) + green_n0_n = copy.deepcopy(green_nn_n) + elif nx0 != nx-1: + if scatter_type == 0: # 无散射 + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + elif scatter_type == 1: # 势垒散射 + h00_scatter = h00 + scatter_intensity * np.identity(dim) + if int(nx/2)-int(scatter_length/2) <= nx0 < int(nx/2)+int((scatter_length+1)/2): + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00_scatter - np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + else: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + else: + green_nn_n = np.linalg.inv(fermi_energy*np.identity(dim)-h00-right_self_energy-np.dot(np.dot(h01.transpose().conj(), green_nn_n), h01)) + + green_00_n = green_00_n+np.dot(np.dot(np.dot(np.dot(green_0n_n, h01), green_nn_n), h01.transpose().conj()), green_n0_n) + green_0n_n = np.dot(np.dot(green_0n_n, h01), green_nn_n) + green_n0_n = np.dot(np.dot(green_nn_n, h01.transpose().conj()), green_n0_n) + return green_00_n, green_n0_n, k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active + + +def transmission_with_detailed_modes(fermi_energy, h00, h01, scatter_type=0, scatter_intensity=0.2, scatter_length=20): # 计算散射矩阵 + dim = h00.shape[0] + green_00_n, green_n0_n, k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active = calculation_of_green_function(fermi_energy, h00, h01, dim, scatter_type, scatter_intensity, scatter_length) + temp = np.dot(h01.transpose().conj(), np.linalg.inv(f_right)-np.linalg.inv(f_left)) + transmission_matrix = np.dot(np.dot(np.linalg.inv(u_right), np.dot(green_n0_n, temp)), u_right) + reflection_matrix = np.dot(np.dot(np.linalg.inv(u_left), np.dot(green_00_n, temp)-np.identity(dim)), u_right) + for dim0 in range(dim): + for dim1 in range(dim): + if_active = if_active_channel(k_right[dim0])*if_active_channel(k_right[dim1]) + if if_active == 1: + transmission_matrix[dim0, dim1] = np.sqrt(np.abs(velocity_right[dim0]/velocity_right[dim1])) * transmission_matrix[dim0, dim1] + reflection_matrix[dim0, dim1] = np.sqrt(np.abs(velocity_left[dim0] / velocity_right[dim1]))*reflection_matrix[dim0, dim1] + else: + transmission_matrix[dim0, dim1] = 0 + reflection_matrix[dim0, dim1] = 0 + sum_of_tran_refl_array = np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)+np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0) + for sum_of_tran_refl in sum_of_tran_refl_array: + if sum_of_tran_refl > 1.001: + print('错误警告:散射矩阵的计算结果不归一! Error Alert: scattering matrix is not normalized!') + return transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active + + +def write_transmission_matrix(fermi_energy, h00, h01, scatter_type=0, scatter_intensity=0.2, scatter_length=20): # 输出 + transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active, \ + = transmission_with_detailed_modes(fermi_energy, h00, h01, scatter_type, scatter_intensity, scatter_length) + dim = h00.shape[0] + np.set_printoptions(suppress=True) # 取消科学计数法输出 + print('\n可传播的通道数(向右)active_channel (right) = ', ind_right_active) + print('衰减的通道数(向右) evanescent_channel (right) = ', dim-ind_right_active, '\n') + print('向右可传播的通道数对应的波矢 k_right:\n', np.real(k_right[0:ind_right_active])) + print('向左可传播的通道数对应的波矢 k_left:\n', np.real(k_left[0:ind_right_active]), '\n') + print('向右可传播的通道数对应的费米速度 velocity_right:\n', np.real(velocity_right[0:ind_right_active])) + print('向左可传播的通道数对应的费米速度 velocity_left:\n', np.real(velocity_left[0:ind_right_active]), '\n') + print('透射矩阵 transmission_matrix:\n', np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active]))) + print('反射矩阵 reflection_matrix:\n', np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), '\n') + print('透射矩阵列求和 total transmission of channels =\n', np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)) + print('反射矩阵列求和 total reflection of channels =\n',np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)) + print('透射以及反射矩阵列求和 sum of transmission and reflection of channels =\n', np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0) + np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)) + print('总电导 total conductance = ', np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active]))), '\n') + + # 下面把以上信息写入文件中 + with open('a.txt', 'w') as f: + f.write('Active_channel (right or left) = ' + str(ind_right_active) + '\n') + f.write('Evanescent_channel (right or left) = ' + str(dim - ind_right_active) + '\n\n') + f.write('Channel K Velocity\n') + for ind0 in range(ind_right_active): + f.write(' '+str(ind0 + 1) + ' | '+str(np.real(k_right[ind0]))+' ' + str(np.real(velocity_right[ind0]))+'\n') + f.write('\n') + for ind0 in range(ind_right_active): + f.write(' -' + str(ind0 + 1) + ' | ' + str(np.real(k_left[ind0])) + ' ' + str(np.real(velocity_left[ind0])) + '\n') + f.write('\n\nScattering_matrix:\n ') + for ind0 in range(ind_right_active): + f.write(str(ind0+1)+' ') + f.write('\n') + for ind1 in range(ind_right_active): + f.write(' '+str(ind1+1)+' ') + for ind2 in range(ind_right_active): + f.write('%f' % np.square(np.abs(transmission_matrix[ind1, ind2]))+' ') + f.write('\n') + f.write('\n') + for ind1 in range(ind_right_active): + f.write(' -'+str(ind1+1)+' ') + for ind2 in range(ind_right_active): + f.write('%f' % np.square(np.abs(reflection_matrix[ind1, ind2]))+' ') + f.write('\n') + f.write('\n') + f.write('Total transmission of channels:\n'+str(np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0))+'\n') + f.write('Total conductance = '+str(np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active]))))+'\n') + + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.10.30_time_complexity_dealing_with_matrix/time_complexity_dealing_with_matrix.py b/academic_codes/2020.10.30_time_complexity_dealing_with_matrix/time_complexity_dealing_with_matrix.py new file mode 100755 index 0000000..5412639 --- /dev/null +++ b/academic_codes/2020.10.30_time_complexity_dealing_with_matrix/time_complexity_dealing_with_matrix.py @@ -0,0 +1,61 @@ +import numpy as np +import matplotlib.pyplot as plt +import time + + + +time_1 = np.array([]) +time_2 = np.array([]) +time_3 = np.array([]) +n_all = np.arange(2,5000,200) # 测试的范围 +start_all = time.process_time() +for n in n_all: + print(n) + matrix_1 = np.zeros((n,n)) + matrix_2 = np.zeros((n,n)) + for i0 in range(n): + for j0 in range(n): + matrix_1[i0,j0] = np.random.uniform(-10, 10) + for i0 in range(n): + for j0 in range(n): + matrix_2[i0,j0] = np.random.uniform(-10, 10) + + start = time.process_time() + matrix_3 = np.dot(matrix_1, matrix_2) # 矩阵乘积 + end = time.process_time() + time_1 = np.append(time_1, [end-start], axis=0) + + start = time.process_time() + matrix_4 = np.linalg.inv(matrix_1) # 矩阵求逆 + end = time.process_time() + time_2 = np.append(time_2, [end-start], axis=0) + + start = time.process_time() + eigenvalue, eigenvector = np.linalg.eig(matrix_1) # 求矩阵本征值 + end = time.process_time() + time_3 = np.append(time_3, [end-start], axis=0) + + + +end_all = time.process_time() +print('总共运行时间:', (end_all-start_all)/60, '分') + +plt.subplot(131) +plt.xlabel('n^3/10^9') +plt.ylabel('时间(秒)') +plt.title('矩阵乘积') +plt.plot((n_all/10**3)*(n_all/10**3)*(n_all/10**3), time_1, 'o-') + +plt.subplot(132) +plt.xlabel('n^3/10^9') +plt.title('矩阵求逆') +plt.plot((n_all/10**3)*(n_all/10**3)*(n_all/10**3), time_2, 'o-') + +plt.subplot(133) +plt.xlabel('n^3/10^9') +plt.title('求矩阵本征值') +plt.plot((n_all/10**3)*(n_all/10**3)*(n_all/10**3), time_3, 'o-') + +plt.rcParams['font.sans-serif'] = ['SimHei'] # 在画图中正常显示中文 +plt.rcParams['axes.unicode_minus'] = False # 中文化后,加上这个使正常显示负号 +plt.show() \ No newline at end of file diff --git a/academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/Chern_number_of_the_cross_section_plane_in_Weyl_semimetals.py b/academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/Chern_number_of_the_cross_section_plane_in_Weyl_semimetals.py new file mode 100755 index 0000000..20e470a --- /dev/null +++ b/academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/Chern_number_of_the_cross_section_plane_in_Weyl_semimetals.py @@ -0,0 +1,83 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6896 +""" + +import numpy as np +from math import * +import matplotlib.pyplot as plt +import time +import cmath + + +def hamiltonian(kx,ky,kz): # Weyl semimetal + A = 1 + M0 = 1 + M1 = 1 + H = A*(sin(kx)*sigma_x()+sin(ky)*sigma_y())+(M0-M1*(2*(1-cos(kx))+2*(1-cos(ky))+2*(1-cos(kz))))*sigma_z() + return H + + +def sigma_x(): + return np.array([[0, 1],[1, 0]]) + + +def sigma_y(): + return np.array([[0, -1j],[1j, 0]]) + + +def sigma_z(): + return np.array([[1, 0],[0, -1]]) + + +def main(): + start_time = time.time() + n = 50 + delta = 2*pi/n + kz_array = np.arange(-pi, pi, 0.1) + chern_number_array = np.zeros(kz_array.shape[0]) + i0 = 0 + for kz in kz_array: + print('kz=', kz) + chern_number = 0 # 陈数初始化 + for kx in np.arange(-pi, pi, 2*pi/n): + for ky in np.arange(-pi, pi, 2*pi/n): + H = hamiltonian(kx, ky, kz) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian(kx+delta, ky, kz) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian(kx, ky+delta, kz) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta, kz) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) + Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) + Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) + Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) + + F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) + + # 陈数(chern number) + chern_number = chern_number + F + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number, '\n') + chern_number_array[i0] = np.real(chern_number) + i0 += 1 + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + plt.plot(kz_array, chern_number_array, 'o-') + plt.xlabel('kz') + plt.ylabel('Chern number') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/bands_of_Weyl_semimetal_after_discretization.py b/academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/bands_of_Weyl_semimetal_after_discretization.py new file mode 100755 index 0000000..ddd31bf --- /dev/null +++ b/academic_codes/2020.11.04_Chern_number_of_the_cross_section_plane_in_Weyl_semimetals/bands_of_Weyl_semimetal_after_discretization.py @@ -0,0 +1,66 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6896 +""" + +import numpy as np +from math import * +import matplotlib.pyplot as plt + + +def main(): + k1 = np.arange(-pi, pi, 0.05) + k2 = np.arange(-pi, pi, 0.05) + plot_bands_two_dimension(k1, k2, hamiltonian) + + +def hamiltonian(kx,kz,ky=0): # Weyl semimetal + A = 1 + M0 = 1 + M1 = 1 + H = A*(sin(kx)*sigma_x()+sin(ky)*sigma_y())+(M0-M1*(2*(1-cos(kx))+2*(1-cos(ky))+2*(1-cos(kz))))*sigma_z() + return H + + +def sigma_x(): + return np.array([[0, 1],[1, 0]]) + + +def sigma_y(): + return np.array([[0, -1j],[1j, 0]]) + + +def sigma_z(): + return np.array([[1, 0],[0, -1]]) + + +def plot_bands_two_dimension(k1, k2, hamiltonian): + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + dim = hamiltonian(0, 0).shape[0] + dim1 = k1.shape[0] + dim2 = k2.shape[0] + eigenvalue_k = np.zeros((dim2, dim1, dim)) + i0 = 0 + for k10 in k1: + j0 = 0 + for k20 in k2: + matrix0 = hamiltonian(k10, k20) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_k[j0, i0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + for dim0 in range(dim): + ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + plt.xlabel('kx') + plt.ylabel('kz') + ax.set_zlabel('E') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/find_the_same_gauge_numerically_by_binary_search.py b/academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/find_the_same_gauge_numerically_by_binary_search.py new file mode 100755 index 0000000..7ef9ebd --- /dev/null +++ b/academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/find_the_same_gauge_numerically_by_binary_search.py @@ -0,0 +1,114 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7516 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * # 引入pi, cos等 +import cmath +import time + + +def hamiltonian(kx, ky): # 量子反常霍尔QAH模型(该参数对应的陈数为2) + t1 = 1.0 + t2 = 1.0 + t3 = 0.5 + m = -1.0 + matrix = np.zeros((2, 2))*(1+0j) + matrix[0, 1] = 2*t1*cos(kx)-1j*2*t1*cos(ky) + matrix[1, 0] = 2*t1*cos(kx)+1j*2*t1*cos(ky) + matrix[0, 0] = m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky) + matrix[1, 1] = -(m+2*t3*sin(kx)+2*t3*sin(ky)+2*t2*cos(kx+ky)) + return matrix + + +def main(): + start_time = time.time() + n = 100 # 积分密度 + delta = 1e-9 # 求导的偏离量 + chern_number = 0 # 陈数初始化 + for kx in np.arange(-pi, pi, 2*pi/n): + for ky in np.arange(-pi, pi, 2*pi/n): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 + + # vector = vector*cmath.exp(-1j*1) + # vector_delta_kx = vector_delta_kx*cmath.exp(-1j*1) + # vector_delta_ky = vector_delta_ky*cmath.exp(-1j*1) + # vector_delta_kx_ky = vector_delta_kx_ky*cmath.exp(-1j*(1+1e-8)) + + + rand = np.random.uniform(-pi, pi) + vector_delta_kx_ky = vector_delta_kx_ky*cmath.exp(-1j*rand) + + # 寻找近似的同一的规范 + phase_1_pre = 0 + phase_2_pre = pi + n_test = 10001 + for i0 in range(n_test): + test_1 = np.sum(np.abs(vector_delta_kx_ky*cmath.exp(1j*phase_1_pre) - vector)) + test_2 = np.sum(np.abs(vector_delta_kx_ky*cmath.exp(1j*phase_2_pre) - vector)) + if test_1 < 1e-6: + phase = phase_1_pre + print('Done with i0=', i0) + break + if i0 == n_test-1: + phase = phase_1_pre + print('Not Found with i0=', i0) + if test_1 < test_2: + if i0 == 0: + phase_1 = phase_1_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_1_pre + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + if i0 == 0: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre + phase_1_pre = phase_1 + phase_2_pre = phase_2 + + vector_delta_kx_ky = vector_delta_kx_ky*cmath.exp(1j*phase) + print('随机的规范=', rand) # 可注释掉 + print('二分查找找到的规范=', phase) # 可注释掉 + print() # 可注释掉 + + + # 价带的波函数的贝里联络(berry connection) # 求导后内积 + A_x = np.dot(vector.transpose().conj(), (vector_delta_kx-vector)/delta) # 贝里联络Ax(x分量) + A_y = np.dot(vector.transpose().conj(), (vector_delta_ky-vector)/delta) # 贝里联络Ay(y分量) + + A_x_delta_ky = np.dot(vector_delta_ky.transpose().conj(), (vector_delta_kx_ky-vector_delta_ky)/delta) # 略偏离ky的贝里联络Ax + A_y_delta_kx = np.dot(vector_delta_kx.transpose().conj(), (vector_delta_kx_ky-vector_delta_kx)/delta) # 略偏离kx的贝里联络Ay + + # 贝里曲率(berry curvature) + F = (A_y_delta_kx-A_y)/delta-(A_x_delta_ky-A_x)/delta + + # 陈数(chern number) + chern_number = chern_number + F*(2*pi/n)**2 + chern_number = chern_number/(2*pi*1j) + print('Chern number = ', chern_number) + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/function_form.py b/academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/function_form.py new file mode 100755 index 0000000..9d1acdd --- /dev/null +++ b/academic_codes/2020.11.27_find_the_same_gauge_numerically_by_binary_search/function_form.py @@ -0,0 +1,39 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7516 +""" + +def find_vector_with_the_same_gauge(vector_1, vector_0): + # 寻找近似的同一的规范 + phase_1_pre = 0 + phase_2_pre = pi + n_test = 10001 + for i0 in range(n_test): + test_1 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_1_pre) - vector_0)) + test_2 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_2_pre) - vector_0)) + if test_1 < 1e-6: + phase = phase_1_pre + # print('Done with i0=', i0) + break + if i0 == n_test-1: + phase = phase_1_pre + print('Gauge Not Found with i0=', i0) + if test_1 < test_2: + if i0 == 0: + phase_1 = phase_1_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_1_pre + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + if i0 == 0: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre + phase_1_pre = phase_1 + phase_2_pre = phase_2 + vector_1 = vector_1*cmath.exp(1j*phase) + # print('二分查找找到的规范=', phase) + return vector_1 \ No newline at end of file diff --git a/academic_codes/2020.12.23_plot_with_matplotlib/plot_2D_scatter.py b/academic_codes/2020.12.23_plot_with_matplotlib/plot_2D_scatter.py new file mode 100755 index 0000000..3147c93 --- /dev/null +++ b/academic_codes/2020.12.23_plot_with_matplotlib/plot_2D_scatter.py @@ -0,0 +1,34 @@ +import numpy as np +# import os +# os.chdir('D:/data') # 设置文件保存的位置 + + +def main(): + x = [4, 3, 5, 7] + y = [6, 1, 3, 2] + value = [3, 1, 10, 2] + Plot_2D_Scatter(x, y, value, title='Plot 2D Scatter') + + +def Plot_2D_Scatter(x, y, value, xlabel='x', ylabel='y', title='title', filename='a'): + from matplotlib.axes._axes import _log as matplotlib_axes_logger + matplotlib_axes_logger.setLevel('ERROR') # 只显示error级别的通知 + import matplotlib.pyplot as plt + fig = plt.figure() + ax = fig.add_subplot(111) + plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2) + for i in range(np.array(x).shape[0]): + ax.scatter(x[i], y[i], marker='o', s=100*value[i], c=(1,0,0)) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + # plt.savefig(filename+'.jpg', dpi=300) + plt.show() + plt.close('all') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_scatter.py b/academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_scatter.py new file mode 100755 index 0000000..9aa5b8f --- /dev/null +++ b/academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_scatter.py @@ -0,0 +1,40 @@ +import numpy as np +# import os +# os.chdir('D:/data') # 设置文件保存的位置 + + +def main(): + x = [1, 3, 5, 7] + y = [2, 4, 6, 8] + z = [2, 8, 6, 1] + value = [3, 1, 10, 2] + Plot_3D_Scatter(x, y, z, value, title='Plot 3D Scatter') + + +def Plot_3D_Scatter(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='title', filename='a'): + from matplotlib.axes._axes import _log as matplotlib_axes_logger + matplotlib_axes_logger.setLevel('ERROR') # 只显示error级别的通知 + import matplotlib.pyplot as plt + from matplotlib.ticker import LinearLocator + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + plt.subplots_adjust(bottom=0.1, right=0.8) + for i in range(np.array(x).shape[0]): + ax.scatter(x[i], y[i], z[i], marker='o', s=int(100*value[i]), c=(1,0,0)) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') + # ax.set_zlim(0, 20) + # ax.zaxis.set_major_locator(LinearLocator(6)) # 设置z轴主刻度的个数 + # ax.zaxis.set_major_formatter('{x:.0f}') # 设置z轴主刻度的格式 + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + # plt.savefig(filename+'.jpg', dpi=300) + plt.show() + plt.close('all') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_surface.py b/academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_surface.py new file mode 100755 index 0000000..dd926f0 --- /dev/null +++ b/academic_codes/2020.12.23_plot_with_matplotlib/plot_3D_surface.py @@ -0,0 +1,44 @@ +import numpy as np +# import os +# os.chdir('D:/data') # 设置文件保存的位置 + + +def main(): + x = np.arange(-5, 5, 0.25) + y = np.arange(-5, 5, 0.25) + X, Y = np.meshgrid(x, y) + R = np.sqrt(X**2 + Y**2) + Z = np.sin(R) + Plot_3D_Surface(x,y,Z) + + +def Plot_3D_Surface(x,y,matrix,filename='a.jpg', titlename='Plot 3D Surface'): + import matplotlib.pyplot as plt + from matplotlib import cm + from matplotlib.ticker import LinearLocator + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + plt.subplots_adjust(bottom=0.1, right=0.65) # 调整位置 + x, y = np.meshgrid(x, y) + surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Plot the surface. + ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + ax.set_zlabel('z', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + # ax.set_zlim(-1, 1) # 设置z轴的范围 + ax.zaxis.set_major_locator(LinearLocator(5)) # 设置z轴主刻度的个数 + ax.zaxis.set_major_formatter('{x:.2f}') # 设置z轴主刻度的格式 + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + cax = plt.axes([0.75, 0.15, 0.05, 0.75]) # color bar的位置 [左,下,宽度, 高度] + cbar = fig.colorbar(surf, cax=cax) # color bar + cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小 + for l in cbar.ax.yaxis.get_ticklabels(): # 设置color bar刻度的字体 + l.set_family('Times New Roman') + # plt.savefig(filename, dpi=800) # 保存图片文件 + plt.show() + plt.close('all') # 关闭所有plt,防止循环画图时占用内存 + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.23_plot_with_matplotlib/plot_contour.py b/academic_codes/2020.12.23_plot_with_matplotlib/plot_contour.py new file mode 100755 index 0000000..a638b18 --- /dev/null +++ b/academic_codes/2020.12.23_plot_with_matplotlib/plot_contour.py @@ -0,0 +1,42 @@ +import numpy as np +# import os +# os.chdir('D:/data') # 设置文件保存的位置 + + +def main(): + x = np.arange(-5, 5, 0.25) + y = np.arange(-5, 5, 0.25) + X, Y = np.meshgrid(x, y) + R = np.sqrt(X**2 + Y**2) + Z = np.sin(R) + Plot_Contour(x,y,Z) + + +def Plot_Contour(x,y,matrix,filename='a.jpg', titlename='Plot Contour'): + import matplotlib.pyplot as plt + from matplotlib import cm + from matplotlib.ticker import LinearLocator + fig, ax = plt.subplots() + plt.subplots_adjust(bottom=0.15, right=0.7) # 调整位置 + x, y = np.meshgrid(x, y) + contour = ax.contourf(x,y,matrix,cmap='jet') + ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + # plt.xlabel('x') + # plt.ylabel('y') + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + cax = plt.axes([0.75, 0.15, 0.08, 0.73]) # color bar的位置 [左,下,宽度, 高度] + cbar = fig.colorbar(contour, cax=cax) # color bar + cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小 + for l in cbar.ax.yaxis.get_ticklabels(): # 设置color bar刻度的字体 + l.set_family('Times New Roman') + # plt.savefig(filename, dpi=800) # 保存图片文件 + plt.show() + plt.close('all') # 关闭所有plt,防止循环画图时占用内存 + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.23_plot_with_matplotlib/plot_line.py b/academic_codes/2020.12.23_plot_with_matplotlib/plot_line.py new file mode 100755 index 0000000..b28db22 --- /dev/null +++ b/academic_codes/2020.12.23_plot_with_matplotlib/plot_line.py @@ -0,0 +1,30 @@ +import numpy as np +# import os +# os.chdir('D:/data') # 设置文件保存的位置 + + +def main(): + x = np.arange(0.0, 2.0, 0.01) + y = 1 + np.sin(2 * np.pi * x) + Plot_Line(x,y) + + +def Plot_Line(x,y,filename='a.jpg', titlename='Plot Line'): + import matplotlib.pyplot as plt + fig, ax = plt.subplots() + plt.subplots_adjust(bottom=0.20, left=0.16) + ax.plot(x, y, '-o') + ax.grid() + ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签 + ax.tick_params(labelsize=20) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + # plt.savefig(filename, dpi=800) # 保存图片文件 + plt.show() + plt.close('all') # 关闭所有plt,防止循环画图时占用内存 + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice.py b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice.py new file mode 100755 index 0000000..dfcdc87 --- /dev/null +++ b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice.py @@ -0,0 +1,102 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7650 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * + + +def matrix_00(width, length): + h00 = np.zeros((width*length, width*length)) + for x in range(length): + for y in range(width-1): + h00[x*width+y, x*width+y+1] = 1 + h00[x*width+y+1, x*width+y] = 1 + for x in range(length-1): + for y in range(width): + h00[x*width+y, (x+1)*width+y] = 1 + h00[(x+1)*width+y, x*width+y] = 1 + return h00 + + +def matrix_01(width, length): + h01 = np.identity(width*length) + return h01 + + +def main(): + height = 2 # z + width = 3 # y + length = 4 # x + eta = 1e-2 + E = 0 + h00 = matrix_00(width, length) + h01 = matrix_01(width, length) + G_ii_n_array = G_ii_n_with_Dyson_equation(width, length, height, E, eta, h00, h01) + for i0 in range(height): + print('z=', i0+1, ':') + for j0 in range(width): + print(' y=', j0+1, ':') + for k0 in range(length): + print(' x=', k0+1, ' ', -np.imag(G_ii_n_array[i0, k0*width+j0, k0*width+j0])/pi) # 态密度 + + +def G_ii_n_with_Dyson_equation(width, length, height, E, eta, h00, h01): + dim = length*width + G_ii_n_array = np.zeros((height, dim, dim), dtype=complex) + G_11_1 = np.linalg.inv((E+eta*1j)*np.identity(dim)-h00) + for i in range(height): # i为格林函数的右下指标 + # 初始化开始 + G_nn_n_minus = G_11_1 + G_in_n_minus = G_11_1 + G_ni_n_minus = G_11_1 + G_ii_n_minus = G_11_1 + for i0 in range(i): + G_nn_n = Green_nn_n(E, eta, h00, h01, G_nn_n_minus) + G_nn_n_minus = G_nn_n + if i!=0: + G_in_n_minus = G_nn_n + G_ni_n_minus = G_nn_n + G_ii_n_minus = G_nn_n + # 初始化结束 + for j0 in range(height-1-i): # j0为格林函数的右上指标,表示当前体系大小,即G^{(j0)} + G_nn_n = Green_nn_n(E, eta, h00, h01, G_nn_n_minus) + G_nn_n_minus = G_nn_n + + G_ii_n = Green_ii_n(G_ii_n_minus, G_in_n_minus, h01, G_nn_n, G_ni_n_minus) # 需要求的对角分块矩阵 + G_ii_n_minus = G_ii_n + + G_in_n = Green_in_n(G_in_n_minus, h01, G_nn_n) + G_in_n_minus = G_in_n + + G_ni_n = Green_ni_n(G_nn_n, h01, G_ni_n_minus) + G_ni_n_minus = G_ni_n + G_ii_n_array[i, :, :] = G_ii_n_minus + return G_ii_n_array + + +def Green_nn_n(E, eta, H00, V, G_nn_n_minus): # n>=2 + dim = H00.shape[0] + G_nn_n = np.linalg.inv((E+eta*1j)*np.identity(dim)-H00-np.dot(np.dot(V.transpose().conj(), G_nn_n_minus), V)) + return G_nn_n + + +def Green_in_n(G_in_n_minus, V, G_nn_n): # n>=2 + G_in_n = np.dot(np.dot(G_in_n_minus, V), G_nn_n) + return G_in_n + + +def Green_ni_n(G_nn_n, V, G_ni_n_minus): # n>=2 + G_ni_n = np.dot(np.dot(G_nn_n, V.transpose().conj()), G_ni_n_minus) + return G_ni_n + + +def Green_ii_n(G_ii_n_minus, G_in_n_minus, V, G_nn_n, G_ni_n_minus): # n>=i + G_ii_n = G_ii_n_minus+np.dot(np.dot(np.dot(np.dot(G_in_n_minus, V), G_nn_n), V.transpose().conj()),G_ni_n_minus) + return G_ii_n + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice_version_II.py b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice_version_II.py new file mode 100755 index 0000000..964cb75 --- /dev/null +++ b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/DOS_calculation_using_Dyson_equations_in_cubic_lattice_version_II.py @@ -0,0 +1,99 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7650 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * + + +def matrix_00(width, length): + h00 = np.zeros((width*length, width*length)) + for x in range(length): + for y in range(width-1): + h00[x*width+y, x*width+y+1] = 1 + h00[x*width+y+1, x*width+y] = 1 + for x in range(length-1): + for y in range(width): + h00[x*width+y, (x+1)*width+y] = 1 + h00[(x+1)*width+y, x*width+y] = 1 + return h00 + + +def matrix_01(width, length): + h01 = np.identity(width*length) + return h01 + + +def main(): + height = 2 # z + width = 3 # y + length = 4 # x + eta = 1e-2 + E = 0 + h00 = matrix_00(width, length) + h01 = matrix_01(width, length) + G_ii_n_with_Dyson_equation_version_II(width, length, height, E, eta, h00, h01) + + +def G_ii_n_with_Dyson_equation_version_II(width, length, height, E, eta, h00, h01): + dim = length*width + G_11_1 = np.linalg.inv((E+eta*1j)*np.identity(dim)-h00) + for i in range(height): # i为格林函数的右下指标 + # 初始化开始 + G_nn_n_minus = G_11_1 + G_in_n_minus = G_11_1 + G_ni_n_minus = G_11_1 + G_ii_n_minus = G_11_1 + for i0 in range(i): + G_nn_n = Green_nn_n(E, eta, h00, h01, G_nn_n_minus) + G_nn_n_minus = G_nn_n + if i!=0: + G_in_n_minus = G_nn_n + G_ni_n_minus = G_nn_n + G_ii_n_minus = G_nn_n + # 初始化结束 + for j0 in range(height-1-i): # j0为格林函数的右上指标,表示当前体系大小,即G^{(j0)} + G_nn_n = Green_nn_n(E, eta, h00, h01, G_nn_n_minus) + G_nn_n_minus = G_nn_n + + G_ii_n = Green_ii_n(G_ii_n_minus, G_in_n_minus, h01, G_nn_n, G_ni_n_minus) # 需要求的对角分块矩阵 + G_ii_n_minus = G_ii_n + + G_in_n = Green_in_n(G_in_n_minus, h01, G_nn_n) + G_in_n_minus = G_in_n + + G_ni_n = Green_ni_n(G_nn_n, h01, G_ni_n_minus) + G_ni_n_minus = G_ni_n + # 输出 + print('z=', i+1, ':') + for j0 in range(width): + print(' y=', j0+1, ':') + for k0 in range(length): + print(' x=', k0+1, ' ', -np.imag(G_ii_n_minus[k0*width+j0, k0*width+j0])/pi) # 态密度 + + +def Green_nn_n(E, eta, H00, V, G_nn_n_minus): # n>=2 + dim = H00.shape[0] + G_nn_n = np.linalg.inv((E+eta*1j)*np.identity(dim)-H00-np.dot(np.dot(V.transpose().conj(), G_nn_n_minus), V)) + return G_nn_n + + +def Green_in_n(G_in_n_minus, V, G_nn_n): # n>=2 + G_in_n = np.dot(np.dot(G_in_n_minus, V), G_nn_n) + return G_in_n + + +def Green_ni_n(G_nn_n, V, G_ni_n_minus): # n>=2 + G_ni_n = np.dot(np.dot(G_nn_n, V.transpose().conj()), G_ni_n_minus) + return G_ni_n + + +def Green_ii_n(G_ii_n_minus, G_in_n_minus, V, G_nn_n, G_ni_n_minus): # n>=i + G_ii_n = G_ii_n_minus+np.dot(np.dot(np.dot(np.dot(G_in_n_minus, V), G_nn_n), V.transpose().conj()),G_ni_n_minus) + return G_ii_n + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_cubic_lattice.py b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_cubic_lattice.py new file mode 100755 index 0000000..25acba5 --- /dev/null +++ b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/cubic_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_cubic_lattice.py @@ -0,0 +1,49 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7650 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * + + +def hamiltonian(width, length, height): + h = np.zeros((width*length*height, width*length*height)) + for i0 in range(length): + for j0 in range(width): + for k0 in range(height-1): + h[k0*width*length+i0*width+j0, (k0+1)*width*length+i0*width+j0] = 1 + h[(k0+1)*width*length+i0*width+j0, k0*width*length+i0*width+j0] = 1 + for i0 in range(length): + for j0 in range(width-1): + for k0 in range(height): + h[k0*width*length+i0*width+j0, k0*width*length+i0*width+j0+1] = 1 + h[k0*width*length+i0*width+j0+1, k0*width*length+i0*width+j0] = 1 + for i0 in range(length-1): + for j0 in range(width): + for k0 in range(height): + h[k0*width*length+i0*width+j0, k0*width*length+(i0+1)*width+j0] = 1 + h[k0*width*length+(i0+1)*width+j0, k0*width*length+i0*width+j0] = 1 + return h + + +def main(): + height = 2 # z + width = 3 # y + length = 4 # x + h = hamiltonian(width, length, height) + E = 0 + green = np.linalg.inv((E+1e-2j)*np.eye(width*length*height)-h) + for k0 in range(height): + print('z=', k0+1, ':') + for j0 in range(width): + print(' y=', j0+1, ':') + for i0 in range(length): + print(' x=', i0+1, ' ', -np.imag(green[k0*width*length+i0*width+j0, k0*width*length+i0*width+j0])/pi) # 态密度 + + +if __name__ == "__main__": + main() + + \ No newline at end of file diff --git a/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/DOS_calculation_using_Dyson_equations_in_square_lattice.py b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/DOS_calculation_using_Dyson_equations_in_square_lattice.py new file mode 100755 index 0000000..9eeee35 --- /dev/null +++ b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/DOS_calculation_using_Dyson_equations_in_square_lattice.py @@ -0,0 +1,95 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7650 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * + + +def matrix_00(width): + h00 = np.zeros((width, width)) + for width0 in range(width-1): + h00[width0, width0+1] = 1 + h00[width0+1, width0] = 1 + return h00 + + +def matrix_01(width): + h01 = np.identity(width) + return h01 + + +def main(): + width = 2 + length = 3 + eta = 1e-2 + E = 0 + h00 = matrix_00(width) + h01 = matrix_01(width) + G_ii_n_array = G_ii_n_with_Dyson_equation(width, length, E, eta, h00, h01) + for i0 in range(length): + # print('G_{'+str(i0+1)+','+str(i0+1)+'}^{('+str(length)+')}:') + # print(G_ii_n_array[i0, :, :],'\n') + print('x=', i0+1, ':') + for j0 in range(width): + print(' y=', j0+1, ' ', -np.imag(G_ii_n_array[i0, j0, j0])/pi) # 态密度 + + +def G_ii_n_with_Dyson_equation(width, length, E, eta, h00, h01): + G_ii_n_array = np.zeros((length, width, width), complex) + G_11_1 = np.linalg.inv((E+eta*1j)*np.identity(width)-h00) + for i in range(length): # i为格林函数的右下指标 + # 初始化开始 + G_nn_n_minus = G_11_1 + G_in_n_minus = G_11_1 + G_ni_n_minus = G_11_1 + G_ii_n_minus = G_11_1 + for i0 in range(i): + G_nn_n = Green_nn_n(E, eta, h00, h01, G_nn_n_minus) + G_nn_n_minus = G_nn_n + if i!=0: + G_in_n_minus = G_nn_n + G_ni_n_minus = G_nn_n + G_ii_n_minus = G_nn_n + # 初始化结束 + for j0 in range(length-1-i): # j0为格林函数的右上指标,表示当前体系大小,即G^{(j0)} + G_nn_n = Green_nn_n(E, eta, h00, h01, G_nn_n_minus) + G_nn_n_minus = G_nn_n + + G_ii_n = Green_ii_n(G_ii_n_minus, G_in_n_minus, h01, G_nn_n, G_ni_n_minus) # 需要求的对角分块矩阵 + G_ii_n_minus = G_ii_n + + G_in_n = Green_in_n(G_in_n_minus, h01, G_nn_n) + G_in_n_minus = G_in_n + + G_ni_n = Green_ni_n(G_nn_n, h01, G_ni_n_minus) + G_ni_n_minus = G_ni_n + G_ii_n_array[i, :, :] = G_ii_n_minus + return G_ii_n_array + + +def Green_nn_n(E, eta, H00, V, G_nn_n_minus): # n>=2 + dim = H00.shape[0] + G_nn_n = np.linalg.inv((E+eta*1j)*np.identity(dim)-H00-np.dot(np.dot(V.transpose().conj(), G_nn_n_minus), V)) + return G_nn_n + + +def Green_in_n(G_in_n_minus, V, G_nn_n): # n>=2 + G_in_n = np.dot(np.dot(G_in_n_minus, V), G_nn_n) + return G_in_n + + +def Green_ni_n(G_nn_n, V, G_ni_n_minus): # n>=2 + G_ni_n = np.dot(np.dot(G_nn_n, V.transpose().conj()), G_ni_n_minus) + return G_ni_n + + +def Green_ii_n(G_ii_n_minus, G_in_n_minus, V, G_nn_n, G_ni_n_minus): # n>=i + G_ii_n = G_ii_n_minus+np.dot(np.dot(np.dot(np.dot(G_in_n_minus, V), G_nn_n), V.transpose().conj()),G_ni_n_minus) + return G_ii_n + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_square_lattice.py b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_square_lattice.py new file mode 100755 index 0000000..185bc4a --- /dev/null +++ b/academic_codes/2020.12.31_DOS_calculation_using_Dyson_equations/square_lattice/get_DOS_by_direct_inverseion_of_Hamiltonian_of_square_lattice.py @@ -0,0 +1,41 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/7650 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * + + +def hamiltonian(width, length): + h = np.zeros((width*length, width*length)) + for i0 in range(length): + for j0 in range(width-1): + h[i0*width+j0, i0*width+j0+1] = 1 + h[i0*width+j0+1, i0*width+j0] = 1 + for i0 in range(length-1): + for j0 in range(width): + h[i0*width+j0, (i0+1)*width+j0] = 1 + h[(i0+1)*width+j0, i0*width+j0] = 1 + return h + + +def main(): + width = 2 + length = 3 + h = hamiltonian(width, length) + E = 0 + green = np.linalg.inv((E+1e-2j)*np.eye(width*length)-h) + for i0 in range(length): + # print('G_{'+str(i0+1)+','+str(i0+1)+'}^{('+str(length)+')}:') + # print(green[i0*width+0: i0*width+width, i0*width+0: i0*width+width], '\n') + print('x=', i0+1, ':') + for j0 in range(width): + print(' y=', j0+1, ' ', -np.imag(green[i0*width+j0, i0*width+j0])/pi) + + +if __name__ == "__main__": + main() + + \ No newline at end of file diff --git a/academic_codes/2021.01.07_Hofstadter_butterfly_in_square_lattice/Hofstadter_butterfly_in_square_lattice.py b/academic_codes/2021.01.07_Hofstadter_butterfly_in_square_lattice/Hofstadter_butterfly_in_square_lattice.py new file mode 100755 index 0000000..8e41772 --- /dev/null +++ b/academic_codes/2021.01.07_Hofstadter_butterfly_in_square_lattice/Hofstadter_butterfly_in_square_lattice.py @@ -0,0 +1,50 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8491 +""" + +import numpy as np +import cmath +import matplotlib.pyplot as plt + + +def main(): + for n in np.arange(1, 11): + print('n=', n) + width = n + length = n + B_array = np.arange(0, 1, 0.001) + eigenvalue_all = np.zeros((B_array.shape[0], width*length)) + i0 = 0 + for B in B_array: + # print(B) + h = hamiltonian(width, length, B) + eigenvalue, eigenvector = np.linalg.eig(h) + eigenvalue_all[i0, :] = np.real(eigenvalue) + i0 += 1 + plt.plot(B_array, eigenvalue_all, '.r', markersize=0.5) + plt.title('width=length='+str(n)) + plt.xlabel('B*a^2/phi_0') + plt.ylabel('E') + plt.savefig('width=length='+str(n)+'.jpg', dpi=300) + plt.close('all') # 关闭所有plt,防止循环画图时占用内存 + # plt.show() + + +def hamiltonian(width, length, B): # 方格子哈密顿量 + h = np.zeros((width*length, width*length))*(1+0j) + # y方向的跃迁 + for x in range(length): + for y in range(width-1): + h[x*width+y, x*width+y+1] = 1 + h[x*width+y+1, x*width+y] = 1 + # x方向的跃迁 + for x in range(length-1): + for y in range(width): + h[x*width+y, (x+1)*width+y] = 1*cmath.exp(-2*np.pi*1j*B*y) + h[(x+1)*width+y, x*width+y] = 1*cmath.exp(2*np.pi*1j*B*y) + return h + + +if __name__ == "__main__": + main() diff --git a/academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery.py b/academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery.py new file mode 100755 index 0000000..f7ef002 --- /dev/null +++ b/academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery.py @@ -0,0 +1,151 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8536 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import time + + +def hamiltonian(k1, k2, t1=2.82*sqrt(3)/2, a=1/sqrt(3)): # 石墨烯哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + h = np.zeros((2, 2))*(1+0j) + h[0, 0] = 0.28/2 + h[1, 1] = -0.28/2 + h[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h[0, 1] = h[1, 0].conj() + return h + + +def main(): + start_time = time.time() + n = 400 # 取点密度 + delta = 1e-10 # 求导的偏离量 + kx_array = np.linspace(-2*pi, 2*pi, n) + ky_array = np.linspace(-2*pi, 2*pi, n) + for band in range(2): + F_all = np.zeros((ky_array.shape[0], ky_array.shape[0])) # 贝里曲率 + j0 = 0 + for kx in kx_array: + print(kx) + i0 = 0 + for ky in ky_array: + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 价带波函数 + # print(np.argsort(np.real(eigenvalue))[0]) # 排序索引(从小到大) + # print(eigenvalue) # 排序前的本征值 + # print(np.sort(np.real(eigenvalue))) # 排序后的本征值(从小到大) + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 略偏离kx的波函数 + # vector_delta_kx = find_vector_with_the_same_gauge(vector_delta_kx, vector) # 如果波函数不连续需要使用这个 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 略偏离ky的波函数 + # vector_delta_ky = find_vector_with_the_same_gauge(vector_delta_ky, vector) # 如果波函数不连续需要使用这个 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 略偏离kx和ky的波函数 + # vector_delta_kx_ky = find_vector_with_the_same_gauge(vector_delta_kx_ky, vector) # 如果波函数不连续需要使用这个 + + # 价带的波函数的贝里联络(berry connection) # 求导后内积 + A_x = np.dot(vector.transpose().conj(), (vector_delta_kx-vector)/delta) # 贝里联络Ax(x分量) + A_y = np.dot(vector.transpose().conj(), (vector_delta_ky-vector)/delta) # 贝里联络Ay(y分量) + + A_x_delta_ky = np.dot(vector_delta_ky.transpose().conj(), (vector_delta_kx_ky-vector_delta_ky)/delta) # 略偏离ky的贝里联络Ax + A_y_delta_kx = np.dot(vector_delta_kx.transpose().conj(), (vector_delta_kx_ky-vector_delta_kx)/delta) # 略偏离kx的贝里联络Ay + + # 贝里曲率(berry curvature) + F = ((A_y_delta_kx-A_y)/delta-(A_x_delta_ky-A_x)/delta)*1j + # print(F) + F_all[i0, j0] = np.real(F) + i0 += 1 + j0 += 1 + plot_matrix(kx_array/pi, ky_array/pi, F_all, band) + write_matrix(kx_array/pi, ky_array/pi, F_all, band) + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + + +def find_vector_with_the_same_gauge(vector_1, vector_0): + # 寻找近似的同一的规范 + phase_1_pre = 0 + phase_2_pre = pi + n_test = 10001 + for i0 in range(n_test): + test_1 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_1_pre) - vector_0)) + test_2 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_2_pre) - vector_0)) + if test_1 < 1e-9: + phase = phase_1_pre + # print('Done with i0=', i0) + break + if i0 == n_test-1: + phase = phase_1_pre + print('Gauge Not Found with i0=', i0) + if test_1 < test_2: + if i0 == 0: + phase_1 = phase_1_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_1_pre + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + if i0 == 0: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre + phase_1_pre = phase_1 + phase_2_pre = phase_2 + + vector_1 = vector_1*cmath.exp(1j*phase) + # print('二分查找找到的规范=', phase) + return vector_1 + + +def plot_matrix(k1, k2, matrix, band): + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d import Axes3D + from matplotlib import cm + from matplotlib.ticker import LinearLocator, FormatStrFormatter + fig = plt.figure() + ax = fig.gca(projection='3d') + k1, k2 = np.meshgrid(k1, k2) + ax.plot_surface(k1, k2, matrix, cmap="rainbow", linewidth=0, antialiased=False) + plt.xlabel('kx') + plt.ylabel('ky') + ax.set_zlabel('Berry curvature') + if band==0: + plt.title('Valence Band') + else: + plt.title('Conductance Band') + plt.show() + + +def write_matrix(k1, k2, matrix, band): + import os + os.chdir('D:/data') # 设置路径 + with open('band='+str(band)+'.txt', 'w') as f: + # np.set_printoptions(suppress=True) # 取消输出科学记数法 + f.write('0 ') + for k10 in k1: + f.write(str(k10)+' ') + f.write('\n') + i0 = 0 + for k20 in k2: + f.write(str(k20)) + for j0 in range(k1.shape[0]): + f.write(' '+str(matrix[i0, j0])+' ') + f.write('\n') + i0 += 1 + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery_with_ky=0.py b/academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery_with_ky=0.py new file mode 100755 index 0000000..5f8cbff --- /dev/null +++ b/academic_codes/2021.01.10_Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery/Berry_curvature_distribution_of_graphene_under_broken_inversion_symmery_with_ky=0.py @@ -0,0 +1,114 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8536 +""" + +import numpy as np +import matplotlib.pyplot as plt +from math import * +import cmath +import time + + +def hamiltonian(k1, k2, t1=2.82*sqrt(3)/2, a=1/sqrt(3)): # 石墨烯哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) + h = np.zeros((2, 2))*(1+0j) + h[0, 0] = 0.28/2 + h[1, 1] = -0.28/2 + h[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) + h[0, 1] = h[1, 0].conj() + return h + + +def main(): + start_time = time.time() + n = 2000 # 取点密度 + delta = 1e-9 # 求导的偏离量 + for band in range(2): + F_all = [] # 贝里曲率 + for kx in np.linspace(-2*pi, 2*pi, n): + for ky in [0]: # 这里只考虑ky=0对称轴上的情况 # np.linspace(-pi, pi, n): + H = hamiltonian(kx, ky) + eigenvalue, eigenvector = np.linalg.eig(H) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 价带波函数 + # print(np.argsort(np.real(eigenvalue))[0]) # 排序索引(从小到大) + # print(eigenvalue) # 排序前的本征值 + # print(np.sort(np.real(eigenvalue))) # 排序后的本征值(从小到大) + + H_delta_kx = hamiltonian(kx+delta, ky) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) + vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 略偏离kx的波函数 + # vector_delta_kx = find_vector_with_the_same_gauge(vector_delta_kx, vector) # 如果波函数不连续需要使用这个 + + H_delta_ky = hamiltonian(kx, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) + vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 略偏离ky的波函数 + # vector_delta_ky = find_vector_with_the_same_gauge(vector_delta_ky, vector) # 如果波函数不连续需要使用这个 + + H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) + eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) + vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[band]] # 略偏离kx和ky的波函数 + # vector_delta_kx_ky = find_vector_with_the_same_gauge(vector_delta_kx_ky, vector) # 如果波函数不连续需要使用这个 + + # 价带的波函数的贝里联络(berry connection) # 求导后内积 + A_x = np.dot(vector.transpose().conj(), (vector_delta_kx-vector)/delta) # 贝里联络Ax(x分量) + A_y = np.dot(vector.transpose().conj(), (vector_delta_ky-vector)/delta) # 贝里联络Ay(y分量) + + A_x_delta_ky = np.dot(vector_delta_ky.transpose().conj(), (vector_delta_kx_ky-vector_delta_ky)/delta) # 略偏离ky的贝里联络Ax + A_y_delta_kx = np.dot(vector_delta_kx.transpose().conj(), (vector_delta_kx_ky-vector_delta_kx)/delta) # 略偏离kx的贝里联络Ay + + # 贝里曲率(berry curvature) + F = ((A_y_delta_kx-A_y)/delta-(A_x_delta_ky-A_x)/delta)*1j + # print(F) + F_all = np.append(F_all,[F], axis=0) + plt.plot(np.linspace(-2*pi, 2*pi, n)/pi, np.real(F_all)) + plt.xlabel('k_x (pi)') + plt.ylabel('Berry curvature') + if band==0: + plt.title('Valence Band') + else: + plt.title('Conductance Band') + plt.show() + end_time = time.time() + print('运行时间(min)=', (end_time-start_time)/60) + + +def find_vector_with_the_same_gauge(vector_1, vector_0): + # 寻找近似的同一的规范 + phase_1_pre = 0 + phase_2_pre = pi + n_test = 10001 + for i0 in range(n_test): + test_1 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_1_pre) - vector_0)) + test_2 = np.sum(np.abs(vector_1*cmath.exp(1j*phase_2_pre) - vector_0)) + if test_1 < 1e-9: + phase = phase_1_pre + # print('Done with i0=', i0) + break + if i0 == n_test-1: + phase = phase_1_pre + print('Gauge Not Found with i0=', i0) + if test_1 < test_2: + if i0 == 0: + phase_1 = phase_1_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_1_pre + phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2 + else: + if i0 == 0: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre+(phase_2_pre-phase_1_pre)/2 + else: + phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2 + phase_2 = phase_2_pre + phase_1_pre = phase_1 + phase_2_pre = phase_2 + + vector_1 = vector_1*cmath.exp(1j*phase) + # print('二分查找找到的规范=', phase) + return vector_1 + + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.01.13_python_code_for_data_processing/python_code_for_data_processing.py b/academic_codes/2021.01.13_python_code_for_data_processing/python_code_for_data_processing.py new file mode 100755 index 0000000..284c77f --- /dev/null +++ b/academic_codes/2021.01.13_python_code_for_data_processing/python_code_for_data_processing.py @@ -0,0 +1,322 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8734 + +函数调用目录: +1. x, y = read_one_dimensional_data(filename='a') +2. x, y, matrix = read_two_dimensional_data(filename='a') +3. write_one_dimensional_data(x, y, filename='a') +4. write_two_dimensional_data(x, y, matrix, filename='a') +5. plot(x, y, xlabel='x', ylabel='y', title='', filename='a') +6. plot_3d_surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a') +7. plot_contour(x, y, matrix, xlabel='x', ylabel='y', title='', filename='a') +8. plot_2d_scatter(x, y, value, xlabel='x', ylabel='y', title='', filename='a') +9. plot_3d_surface(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='', filename='a') +10. creat_animation(image_names, duration_time=0.5, filename='a') +11. eigenvalue_array = calculate_eigenvalue_with_one_paramete(x, matrix) +12. eigenvalue_array = calculate_eigenvalue_with_two_parameters(x, y, matrix) + +函数对应的功能: +1. 读取filename.txt文件中的一维数据y(x) +2. 读取filename.txt文件中的二维数据matrix(x,y) +3. 把一维数据y(x)写入filename.txt文件 +4. 把二维数据matrix(x,y)写入filename.txt文件 +5. 画y(x)图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +6. 画3d_surface图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +7. 画contour图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +8. 画2d_scatter图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +9. 画3d_scatter图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +10. 制作动画 +11. 在参数x下,计算matrix函数的本征值eigenvalue_array[:, index] +12. 在参数(x,y)下,计算matrix函数的本征值eigenvalue_array[:, :, index] +""" + + +import numpy as np +# import os +# os.chdir('D:/data') + + +def main(): + pass # 读取数据 + 数据处理 + 保存新数据 + + +# 1. 读取filename.txt文件中的一维数据y(x) +def read_one_dimensional_data(filename='a'): + f = open(filename+'.txt', 'r') + text = f.read() + f.close() + row_list = np.array(text.split('\n')) + dim_column = np.array(row_list[0].split()).shape[0] + x = np.array([]) + y = np.array([]) + for row in row_list: + column = np.array(row.split()) + if column.shape[0] != 0: + x = np.append(x, [float(column[0])], axis=0) + y_row = np.zeros(dim_column-1) + for dim0 in range(dim_column-1): + y_row[dim0] = float(column[dim0+1]) + if np.array(y).shape[0] == 0: + y = [y_row] + else: + y = np.append(y, [y_row], axis=0) + return x, y + + +# 2. 读取filename.txt文件中的二维数据matrix(x,y) +def read_two_dimensional_data(filename='a'): + f = open(filename+'.txt', 'r') + text = f.read() + f.close() + row_list = np.array(text.split('\n')) + dim_column = np.array(row_list[0].split()).shape[0] + x = np.array([]) + y = np.array([]) + matrix = np.array([]) + for i0 in range(row_list.shape[0]): + column = np.array(row_list[i0].split()) + if i0 == 0: + x_str = column[1::] + x = np.zeros(x_str.shape[0]) + for i00 in range(x_str.shape[0]): + x[i00] = float(x_str[i00]) + elif column.shape[0] != 0: + y = np.append(y, [float(column[0])], axis=0) + matrix_row = np.zeros(dim_column-1) + for dim0 in range(dim_column-1): + matrix_row[dim0] = float(column[dim0+1]) + if np.array(matrix).shape[0] == 0: + matrix = [matrix_row] + else: + matrix = np.append(matrix, [matrix_row], axis=0) + return x, y, matrix + + +# 3. 把一维数据y(x)写入filename.txt文件 +def write_one_dimensional_data(x, y, filename='a'): + with open(filename+'.txt', 'w') as f: + i0 = 0 + for x0 in x: + f.write(str(x0)+' ') + if len(y.shape) == 1: + f.write(str(y[i0])+'\n') + elif len(y.shape) == 2: + for j0 in range(y.shape[1]): + f.write(str(y[i0, j0])+' ') + f.write('\n') + i0 += 1 + + +# 4. 把二维数据matrix(x,y)写入filename.txt文件 +def write_two_dimensional_data(x, y, matrix, filename='a'): + with open(filename+'.txt', 'w') as f: + f.write('0 ') + for x0 in x: + f.write(str(x0)+' ') + f.write('\n') + i0 = 0 + for y0 in y: + f.write(str(y0)) + j0 = 0 + for x0 in x: + f.write(' '+str(matrix[i0, j0])+' ') + j0 += 1 + f.write('\n') + i0 += 1 + + +# 5. 画y(x)图,并保存到filename.jpg文件。具体画图格式可在函数中修改。 +def plot(x, y, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0): + import matplotlib.pyplot as plt + fig, ax = plt.subplots() + plt.subplots_adjust(bottom=0.20, left=0.18) + ax.plot(x, y, '-o') + ax.grid() + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=20) + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] + if save == 1: + plt.savefig(filename+'.jpg', dpi=300) + if show == 1: + plt.show() + plt.close('all') + + + +# 6. 画3d_surface图,并保存到filename.jpg文件。具体画图格式可在函数中修改。 +def plot_3d_surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a', show=1, save=0): + import matplotlib.pyplot as plt + from matplotlib import cm + from matplotlib.ticker import LinearLocator + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + plt.subplots_adjust(bottom=0.1, right=0.65) + x, y = np.meshgrid(x, y) + if len(matrix.shape) == 2: + surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) + elif len(matrix.shape) == 3: + for i0 in range(matrix.shape[2]): + surf = ax.plot_surface(x, y, matrix[:,:,i0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') + ax.zaxis.set_major_locator(LinearLocator(5)) + ax.zaxis.set_major_formatter('{x:.2f}') + ax.tick_params(labelsize=15) + labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() + [label.set_fontname('Times New Roman') for label in labels] + cax = plt.axes([0.80, 0.15, 0.05, 0.75]) + cbar = fig.colorbar(surf, cax=cax) + cbar.ax.tick_params(labelsize=15) + for l in cbar.ax.yaxis.get_ticklabels(): + l.set_family('Times New Roman') + if save == 1: + plt.savefig(filename+'.jpg', dpi=300) + if show == 1: + plt.show() + plt.close('all') + + + +# 7. 画plot_contour图,并保存到filename.jpg文件。具体画图格式可在函数中修改。 +def plot_contour(x, y, matrix, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0): + import matplotlib.pyplot as plt + from matplotlib import cm + from matplotlib.ticker import LinearLocator + fig, ax = plt.subplots() + plt.subplots_adjust(bottom=0.2, right=0.75, left = 0.16) + x, y = np.meshgrid(x, y) + contour = ax.contourf(x,y,matrix,cmap='jet') + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=15) + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] + cax = plt.axes([0.78, 0.17, 0.08, 0.71]) + cbar = fig.colorbar(contour, cax=cax) + cbar.ax.tick_params(labelsize=15) + for l in cbar.ax.yaxis.get_ticklabels(): + l.set_family('Times New Roman') + if save == 1: + plt.savefig(filename+'.jpg', dpi=300) + if show == 1: + plt.show() + plt.close('all') + + +# 8. 画2d_scatter图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +def plot_2d_scatter(x, y, value, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0): + import matplotlib.pyplot as plt + from matplotlib.axes._axes import _log as matplotlib_axes_logger + matplotlib_axes_logger.setLevel('ERROR') + fig = plt.figure() + ax = fig.add_subplot(111) + plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2) + for i in range(np.array(x).shape[0]): + ax.scatter(x[i], y[i], marker='o', s=100*value[i], c=(1,0,0)) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=15) + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] + if save == 1: + plt.savefig(filename+'.jpg', dpi=300) + if show == 1: + plt.show() + plt.close('all') + + +# 9. 画3d_scatter图,并保存到filename.jpg文件。具体画图格式可在函数中修改! +def plot_3d_scatter(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='', filename='a', show=1, save=0): + import matplotlib.pyplot as plt + from matplotlib.ticker import LinearLocator + from matplotlib.axes._axes import _log as matplotlib_axes_logger + matplotlib_axes_logger.setLevel('ERROR') + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + plt.subplots_adjust(bottom=0.1, right=0.8) + for i in range(np.array(x).shape[0]): + ax.scatter(x[i], y[i], z[i], marker='o', s=int(100*value[i]), c=(1,0,0)) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=15) + labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() + [label.set_fontname('Times New Roman') for label in labels] + if save == 1: + plt.savefig(filename+'.jpg', dpi=300) + if show == 1: + plt.show() + plt.close('all') + + +# 10. 制作动画 +def creat_animation(image_names, duration_time=0.5, filename='a'): + import imageio + images = [] + for name in image_names: + image = name+'.jpg' + im = imageio.imread(image) + images.append(im) + imageio.mimsave(filename+'.gif', images, 'GIF', duration=duration_time) # durantion是延迟时间 + + +# 11. 在参数x下,计算matrix函数的本征值eigenvalue_array[:, index] +def calculate_eigenvalue_with_one_parameter(x, matrix): + dim_x = np.array(x).shape[0] + i0 = 0 + if np.array(matrix(0)).shape==(): + eigenvalue_array = np.zeros((dim_x, 1)) + for x0 in x: + matrix0 = matrix(x0) + eigenvalue_array[i0, 0] = np.real(matrix0) + i0 += 1 + else: + dim = np.array(matrix(0)).shape[0] + eigenvalue_array = np.zeros((dim_x, dim)) + for x0 in x: + matrix0 = matrix(x0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_array[i0, :] = np.sort(np.real(eigenvalue[:])) + i0 += 1 + return eigenvalue_array + + +# 12. 在参数(x,y)下,计算matrix函数的本征值eigenvalue_array[:, :, index] +def calculate_eigenvalue_with_two_parameters(x, y, matrix): + dim_x = np.array(x).shape[0] + dim_y = np.array(y).shape[0] + if np.array(matrix(0,0)).shape==(): + eigenvalue_array = np.zeros((dim_y, dim_x, 1)) + i0 = 0 + for y0 in y: + j0 = 0 + for x0 in x: + matrix0 = matrix(x0, y0) + eigenvalue_array[i0, j0, 0] = np.real(matrix0) + j0 += 1 + i0 += 1 + else: + dim = np.array(matrix(0, 0)).shape[0] + eigenvalue_array = np.zeros((dim_y, dim_x, dim)) + i0 = 0 + for y0 in y: + j0 = 0 + for x0 in x: + matrix0 = matrix(x0, y0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_array[i0, j0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + return eigenvalue_array + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator.py b/academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator.py new file mode 100755 index 0000000..d526f99 --- /dev/null +++ b/academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator.py @@ -0,0 +1,103 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8557 +""" + +import numpy as np +from math import * + + +def hamiltonian(Nx, Ny): + delta = 1e-3 + gamma = 1e-3 + lambda0 = 1 + h = np.zeros((4*Nx*Ny, 4*Nx*Ny)) + # 元胞内部跃迁 + for x in range(Nx): + for y in range(Ny): + h[x*Ny*4+y*4+0, x*Ny*4+y*4+0] = delta + h[x*Ny*4+y*4+1, x*Ny*4+y*4+1] = delta + h[x*Ny*4+y*4+2, x*Ny*4+y*4+2] = -delta + h[x*Ny*4+y*4+3, x*Ny*4+y*4+3] = -delta + + h[x*Ny*4+y*4+0, x*Ny*4+y*4+2] = gamma + h[x*Ny*4+y*4+0, x*Ny*4+y*4+3] = gamma + h[x*Ny*4+y*4+1, x*Ny*4+y*4+2] = -gamma + h[x*Ny*4+y*4+1, x*Ny*4+y*4+3] = gamma + h[x*Ny*4+y*4+2, x*Ny*4+y*4+0] = gamma + h[x*Ny*4+y*4+2, x*Ny*4+y*4+1] = -gamma + h[x*Ny*4+y*4+3, x*Ny*4+y*4+0] = gamma + h[x*Ny*4+y*4+3, x*Ny*4+y*4+1] = gamma + + # y方向上的元胞间跃迁 + for x in range(Nx): + for y in range(Ny-1): + h[x*Ny*4+y*4+0, x*Ny*4+(y+1)*4+3] = lambda0 + h[x*Ny*4+(y+1)*4+1, x*Ny*4+y*4+2] = -lambda0 + h[x*Ny*4+y*4+2, x*Ny*4+(y+1)*4+1] = -lambda0 + h[x*Ny*4+(y+1)*4+3, x*Ny*4+y*4+0] = lambda0 + + # x方向上的元胞间跃迁 + for x in range(Nx-1): + for y in range(Ny): + h[x*Ny*4+y*4+0, (x+1)*Ny*4+y*4+2] = lambda0 + h[(x+1)*Ny*4+y*4+1, x*Ny*4+y*4+3] = lambda0 + h[(x+1)*Ny*4+y*4+2, x*Ny*4+y*4+0] = lambda0 + h[x*Ny*4+y*4+3, (x+1)*Ny*4+y*4+1] = lambda0 + return h + + +def main(): + Nx = 10 + Ny = 10 + fermi_energy = 0 + h = hamiltonian(Nx, Ny) + green = np.linalg.inv((fermi_energy+1e-6j)*np.eye(h.shape[0])-h) + + x_array = [] + y_array = [] + DOS = [] + for x in range(Nx): + for y in range(Ny): + x_array.append(x*2+2) + y_array.append(y*2+2) + DOS.append(-np.imag(green[x*Ny*4+y*4+0, x*Ny*4+y*4+0])/pi) + + x_array.append(x*2+1) + y_array.append(y*2+1) + DOS.append(-np.imag(green[x*Ny*4+y*4+1, x*Ny*4+y*4+1])/pi) + + x_array.append(x*2+1) + y_array.append(y*2+2) + DOS.append(-np.imag(green[x*Ny*4+y*4+2, x*Ny*4+y*4+2])/pi) + + x_array.append(x*2+2) + y_array.append(y*2+1) + DOS.append(-np.imag(green[x*Ny*4+y*4+3, x*Ny*4+y*4+3])/pi) + DOS = DOS/np.sum(DOS) + Plot_2D_Scatter(x_array, y_array, DOS, xlabel='x', ylabel='y', title='BBH Model', filename='BBH Model') + + +def Plot_2D_Scatter(x, y, value, xlabel='x', ylabel='y', title='title', filename='a'): + from matplotlib.axes._axes import _log as matplotlib_axes_logger + matplotlib_axes_logger.setLevel('ERROR') # 只显示error级别的通知 + import matplotlib.pyplot as plt + from matplotlib.ticker import LinearLocator + fig = plt.figure() + ax = fig.add_subplot(111) + plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2) + for i in range(np.array(x).shape[0]): + ax.scatter(x[i], y[i], marker='o', s=1000*value[i], c=(1,0,0)) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + # plt.savefig(filename+'.jpg', dpi=300) + plt.show() + plt.close('all') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator_plotting_3D_surface.py b/academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator_plotting_3D_surface.py new file mode 100755 index 0000000..f49b51a --- /dev/null +++ b/academic_codes/2021.01.23_BBH_model_of_high_order_topological_insulator/BBH_model_of_high_order_topological_insulator_plotting_3D_surface.py @@ -0,0 +1,100 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8557 +""" + +import numpy as np +from math import * + + +def hamiltonian(Nx, Ny): + delta = 1e-3 + gamma = 1e-3 + lambda0 = 1 + h = np.zeros((4*Nx*Ny, 4*Nx*Ny)) + # 元胞内部跃迁 + for x in range(Nx): + for y in range(Ny): + h[x*Ny*4+y*4+0, x*Ny*4+y*4+0] = delta + h[x*Ny*4+y*4+1, x*Ny*4+y*4+1] = delta + h[x*Ny*4+y*4+2, x*Ny*4+y*4+2] = -delta + h[x*Ny*4+y*4+3, x*Ny*4+y*4+3] = -delta + + h[x*Ny*4+y*4+0, x*Ny*4+y*4+2] = gamma + h[x*Ny*4+y*4+0, x*Ny*4+y*4+3] = gamma + h[x*Ny*4+y*4+1, x*Ny*4+y*4+2] = -gamma + h[x*Ny*4+y*4+1, x*Ny*4+y*4+3] = gamma + h[x*Ny*4+y*4+2, x*Ny*4+y*4+0] = gamma + h[x*Ny*4+y*4+2, x*Ny*4+y*4+1] = -gamma + h[x*Ny*4+y*4+3, x*Ny*4+y*4+0] = gamma + h[x*Ny*4+y*4+3, x*Ny*4+y*4+1] = gamma + + # y方向上的元胞间跃迁 + for x in range(Nx): + for y in range(Ny-1): + h[x*Ny*4+y*4+0, x*Ny*4+(y+1)*4+3] = lambda0 + h[x*Ny*4+(y+1)*4+1, x*Ny*4+y*4+2] = -lambda0 + h[x*Ny*4+y*4+2, x*Ny*4+(y+1)*4+1] = -lambda0 + h[x*Ny*4+(y+1)*4+3, x*Ny*4+y*4+0] = lambda0 + + # x方向上的元胞间跃迁 + for x in range(Nx-1): + for y in range(Ny): + h[x*Ny*4+y*4+0, (x+1)*Ny*4+y*4+2] = lambda0 + h[(x+1)*Ny*4+y*4+1, x*Ny*4+y*4+3] = lambda0 + h[(x+1)*Ny*4+y*4+2, x*Ny*4+y*4+0] = lambda0 + h[x*Ny*4+y*4+3, (x+1)*Ny*4+y*4+1] = lambda0 + return h + + +def main(): + Nx = 10 + Ny = 10 + fermi_energy = 0 + h = hamiltonian(Nx, Ny) + green = np.linalg.inv((fermi_energy+1e-6j)*np.eye(h.shape[0])-h) + DOS = np.zeros((Ny*2, Nx*2)) + for x in range(Nx): + for y in range(Ny): + DOS[y*2+1, x*2+1] = -np.imag(green[x*Ny*4+y*4+0, x*Ny*4+y*4+0])/pi + DOS[y*2+0, x*2+0] = -np.imag(green[x*Ny*4+y*4+1, x*Ny*4+y*4+1])/pi + DOS[y*2+1, x*2+0] = -np.imag(green[x*Ny*4+y*4+2, x*Ny*4+y*4+2])/pi + DOS[y*2+0, x*2+1] = -np.imag(green[x*Ny*4+y*4+3, x*Ny*4+y*4+3])/pi + DOS = DOS/np.sum(DOS) + Plot_3D_Surface(np.arange(1, 2*Nx+0.001), np.arange(1, 2*Ny+0.001), DOS, xlabel='x', ylabel='y', zlabel='DOS', title='BBH Model', filename='BBH Model') + + +def Plot_3D_Surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='title', filename='a'): + import matplotlib.pyplot as plt + from matplotlib import cm + from matplotlib.ticker import LinearLocator + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + plt.subplots_adjust(bottom=0.1, right=0.65) + x, y = np.meshgrid(x, y) + if len(matrix.shape) == 2: + surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) + elif len(matrix.shape) == 3: + for i0 in range(matrix.shape[2]): + surf = ax.plot_surface(x, y, matrix[:,:,i0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') + # ax.set_zlim(-1, 1) # 设置z轴的范围 + ax.zaxis.set_major_locator(LinearLocator(2)) # 设置z轴主刻度的个数 + ax.zaxis.set_major_formatter('{x:.2f}') # 设置z轴主刻度的格式 + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + cax = plt.axes([0.80, 0.15, 0.05, 0.75]) # color bar的位置 [左,下,宽度, 高度] + cbar = fig.colorbar(surf, cax=cax) # color bar + cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小 + for l in cbar.ax.yaxis.get_ticklabels(): + l.set_family('Times New Roman') + # plt.savefig(filename+'.jpg', dpi=300) + plt.show() + plt.close('all') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.02.08_quantum_transport_in_multi_lead_systems/quantum_transport_in_multi_lead_systems.py b/academic_codes/2021.02.08_quantum_transport_in_multi_lead_systems/quantum_transport_in_multi_lead_systems.py new file mode 100755 index 0000000..d347823 --- /dev/null +++ b/academic_codes/2021.02.08_quantum_transport_in_multi_lead_systems/quantum_transport_in_multi_lead_systems.py @@ -0,0 +1,179 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/6075 +""" + +import numpy as np +import matplotlib.pyplot as plt +import copy +import time + + +def lead_matrix_00(y): + h00 = np.zeros((y, y)) + for y0 in range(y-1): + h00[y0, y0+1] = 1 + h00[y0+1, y0] = 1 + return h00 + + +def lead_matrix_01(y): + h01 = np.identity(y) + return h01 + + +def scattering_region(x, y): + h = np.zeros((x*y, x*y)) + for x0 in range(x-1): + for y0 in range(y): + h[x0*y+y0, (x0+1)*y+y0] = 1 # x方向的跃迁 + h[(x0+1)*y+y0, x0*y+y0] = 1 + for x0 in range(x): + for y0 in range(y-1): + h[x0*y+y0, x0*y+y0+1] = 1 # y方向的跃迁 + h[x0*y+y0+1, x0*y+y0] = 1 + return h + + +def main(): + start_time = time.time() + width = 5 + length = 50 + fermi_energy_array = np.arange(-4, 4, .01) + + # 中心区的哈密顿量 + H_scattering_region = scattering_region(x=length, y=width) + + # 电极的h00和h01 + lead_h00 = lead_matrix_00(width) + lead_h01 = lead_matrix_01(width) + + transmission_12_array = [] + transmission_13_array = [] + transmission_14_array = [] + transmission_15_array = [] + transmission_16_array = [] + transmission_1_all_array = [] + + for fermi_energy in fermi_energy_array: + print(fermi_energy) + # 表面格林函数 + right_lead_surface, left_lead_surface = surface_green_function_lead(fermi_energy + 1e-9j, lead_h00, lead_h01, dim=width) + + # 由于镜面对称以及xy各项同性,因此这里六个电极的表面格林函数具有相同的形式 + lead_1 = copy.deepcopy(right_lead_surface) # 镜面对称使得lead_1=lead_4 + lead_2 = copy.deepcopy(right_lead_surface) # xy各项同性使得lead_2=lead_4 + lead_3 = copy.deepcopy(right_lead_surface) + lead_4 = copy.deepcopy(right_lead_surface) + lead_5 = copy.deepcopy(right_lead_surface) + lead_6 = copy.deepcopy(right_lead_surface) + + # 几何形状如下所示: + # lead2 lead3 + # lead1(L) lead4(R) + # lead6 lead5 + + # 电极到中心区的跃迁矩阵 + H_from_lead_1_to_center = np.zeros((width, width*length), dtype=complex) + H_from_lead_2_to_center = np.zeros((width, width*length), dtype=complex) + H_from_lead_3_to_center = np.zeros((width, width*length), dtype=complex) + H_from_lead_4_to_center = np.zeros((width, width*length), dtype=complex) + H_from_lead_5_to_center = np.zeros((width, width*length), dtype=complex) + H_from_lead_6_to_center = np.zeros((width, width*length), dtype=complex) + for i0 in range(width): + H_from_lead_1_to_center[i0, i0] = 1 + H_from_lead_2_to_center[i0, width*i0+(width-1)] = 1 + H_from_lead_3_to_center[i0, width*(length-1-i0)+(width-1)] = 1 + H_from_lead_4_to_center[i0, width*(length-1)+i0] = 1 + H_from_lead_5_to_center[i0, width*(length-1-i0)+0] = 1 + H_from_lead_6_to_center[i0, width*i0+0] = 1 + + # 自能 + self_energy_1 = np.dot(np.dot(H_from_lead_1_to_center.transpose().conj(), lead_1), H_from_lead_1_to_center) + self_energy_2 = np.dot(np.dot(H_from_lead_2_to_center.transpose().conj(), lead_2), H_from_lead_2_to_center) + self_energy_3 = np.dot(np.dot(H_from_lead_3_to_center.transpose().conj(), lead_3), H_from_lead_3_to_center) + self_energy_4 = np.dot(np.dot(H_from_lead_4_to_center.transpose().conj(), lead_4), H_from_lead_4_to_center) + self_energy_5 = np.dot(np.dot(H_from_lead_5_to_center.transpose().conj(), lead_5), H_from_lead_5_to_center) + self_energy_6 = np.dot(np.dot(H_from_lead_6_to_center.transpose().conj(), lead_6), H_from_lead_6_to_center) + + # 整体格林函数 + green = np.linalg.inv(fermi_energy*np.eye(width*length)-H_scattering_region-self_energy_1-self_energy_2-self_energy_3-self_energy_4-self_energy_5-self_energy_6) + + # Gamma矩阵 + self_energy_1 = 1j*(self_energy_1-self_energy_1.transpose().conj()) + self_energy_2 = 1j*(self_energy_2-self_energy_2.transpose().conj()) + self_energy_3 = 1j*(self_energy_3-self_energy_3.transpose().conj()) + self_energy_4 = 1j*(self_energy_4-self_energy_4.transpose().conj()) + self_energy_5 = 1j*(self_energy_5-self_energy_5.transpose().conj()) + self_energy_6 = 1j*(self_energy_6-self_energy_6.transpose().conj()) + + # Transmission + transmission_12 = np.trace(np.dot(np.dot(np.dot(self_energy_1, green), self_energy_2), green.transpose().conj())) + transmission_13 = np.trace(np.dot(np.dot(np.dot(self_energy_1, green), self_energy_3), green.transpose().conj())) + transmission_14 = np.trace(np.dot(np.dot(np.dot(self_energy_1, green), self_energy_4), green.transpose().conj())) + transmission_15 = np.trace(np.dot(np.dot(np.dot(self_energy_1, green), self_energy_5), green.transpose().conj())) + transmission_16 = np.trace(np.dot(np.dot(np.dot(self_energy_1, green), self_energy_6), green.transpose().conj())) + + transmission_12_array.append(np.real(transmission_12)) + transmission_13_array.append(np.real(transmission_13)) + transmission_14_array.append(np.real(transmission_14)) + transmission_15_array.append(np.real(transmission_15)) + transmission_16_array.append(np.real(transmission_16)) + transmission_1_all_array.append(np.real(transmission_12+transmission_13+transmission_14+transmission_15+transmission_16)) + + Plot_Line(fermi_energy_array, transmission_12_array, xlabel='Fermi energy', ylabel='Transmission_12', title='', filename='a') + Plot_Line(fermi_energy_array, transmission_13_array, xlabel='Fermi energy', ylabel='Transmission_13', title='', filename='a') + Plot_Line(fermi_energy_array, transmission_14_array, xlabel='Fermi energy', ylabel='Transmission_14', title='', filename='a') + Plot_Line(fermi_energy_array, transmission_15_array, xlabel='Fermi energy', ylabel='Transmission_15', title='', filename='a') + Plot_Line(fermi_energy_array, transmission_16_array, xlabel='Fermi energy', ylabel='Transmission_16', title='', filename='a') + Plot_Line(fermi_energy_array, transmission_1_all_array, xlabel='Fermi energy', ylabel='Transmission_1_all', title='', filename='a') + end_time = time.time() + print('运行时间=', end_time-start_time) + + + +def Plot_Line(x, y, xlabel='x', ylabel='y', title='', filename='a'): + import matplotlib.pyplot as plt + fig, ax = plt.subplots() + plt.subplots_adjust(bottom=0.20, left=0.18) + ax.plot(x, y, '-') + ax.grid() + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.tick_params(labelsize=20) + labels = ax.get_xticklabels() + ax.get_yticklabels() + [label.set_fontname('Times New Roman') for label in labels] + # plt.savefig(filename+'.jpg', dpi=300) + plt.show() + plt.close('all') + +def transfer_matrix(fermi_energy, h00, h01, dim): # 转移矩阵T + transfer = np.zeros((2*dim, 2*dim))*(0+0j) + transfer[0:dim, 0:dim] = np.dot(np.linalg.inv(h01), fermi_energy*np.identity(dim)-h00) + transfer[0:dim, dim:2*dim] = np.dot(-1*np.linalg.inv(h01), h01.transpose().conj()) + transfer[dim:2*dim, 0:dim] = np.identity(dim) + transfer[dim:2*dim, dim:2*dim] = 0 + return transfer # 返回转移矩阵 + + +def surface_green_function_lead(fermi_energy, h00, h01, dim): # 电极的表面格林函数 + transfer = transfer_matrix(fermi_energy, h00, h01, dim) + eigenvalue, eigenvector = np.linalg.eig(transfer) + ind = np.argsort(np.abs(eigenvalue)) + temp = np.zeros((2*dim, 2*dim))*(1+0j) + i0 = 0 + for ind0 in ind: + temp[:, i0] = eigenvector[:, ind0] + i0 += 1 + s1 = temp[dim:2*dim, 0:dim] + s2 = temp[0:dim, 0:dim] + s3 = temp[dim:2*dim, dim:2*dim] + s4 = temp[0:dim, dim:2*dim] + right_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01, s2), np.linalg.inv(s1))) + left_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), s3), np.linalg.inv(s4))) + return right_lead_surface, left_lead_surface # 返回右电极的表面格林函数和左电极的表面格林函数 + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model.py b/academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model.py new file mode 100755 index 0000000..d1c4135 --- /dev/null +++ b/academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model.py @@ -0,0 +1,68 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10064 +""" + +import numpy as np +import cmath +from math import * + + +def hamiltonian(k): + gamma = 0.5 + lambda0 = 1 + delta = 0 + h = np.zeros((2, 2))*(1+0j) + h[0,0] = delta + h[1,1] = -delta + h[0,1] = gamma+lambda0*cmath.exp(-1j*k) + h[1,0] = gamma+lambda0*cmath.exp(1j*k) + return h + + +def main(): + Num_k = 100 + k_array = np.linspace(-pi, pi, Num_k) + vector_array = [] + for k in k_array: + vector = get_occupied_bands_vectors(k, hamiltonian) + vector_array.append(vector) + + # 波函数固定一个规范 + index = np.argmax(np.abs(vector_array[0])) + for i0 in range(Num_k): + vector_array[i0] = find_vector_with_fixed_gauge(vector_array[i0], index) + + # 计算Wilson loop + W_k = 1 + for i0 in range(Num_k-1): + F = np.dot(vector_array[i0+1].transpose().conj(), vector_array[i0]) + W_k = np.dot(F, W_k) + nu = np.log(W_k)/2/pi/1j + # if np.real(nu) < 0: + # nu += 1 + print('p=', nu, '\n') + + +def get_occupied_bands_vectors(x, matrix): + matrix0 = matrix(x) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] + return vector + + +def find_vector_with_fixed_gauge(vector, index): + sign_pre = np.sign(np.imag(vector[index])) + for phase in np.arange(0, 2*pi, 0.01): + sign = np.sign(np.imag(vector[index]*cmath.exp(1j*phase))) + if np.abs(np.imag(vector[index]*cmath.exp(1j*phase))) < 1e-9 or sign == -sign_pre: + break + sign_pre = sign + vector = vector*cmath.exp(1j*phase) + if np.real(vector[index]) < 0: + vector = -vector + return vector + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model_with_better_code.py b/academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model_with_better_code.py new file mode 100755 index 0000000..96f9931 --- /dev/null +++ b/academic_codes/2021.03.01_Wilson_loop_in_SSH_model/Wilson_loop_in_SSH_model_with_better_code.py @@ -0,0 +1,53 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10064 +""" + +import numpy as np +import cmath +from math import * + + +def hamiltonian(k): + gamma = 0.5 + lambda0 = 1 + delta = 0 + h = np.zeros((2, 2))*(1+0j) + h[0,0] = delta + h[1,1] = -delta + h[0,1] = gamma+lambda0*cmath.exp(-1j*k) + h[1,0] = gamma+lambda0*cmath.exp(1j*k) + return h + + +def main(): + Num_k = 100 + k_array = np.linspace(-pi, pi, Num_k) + vector_array = [] + for k in k_array: + vector = get_occupied_bands_vectors(k, hamiltonian) + if k != pi: + vector_array.append(vector) + else: + vector_array.append(vector_array[0]) + + # 计算Wilson loop + W_k = 1 + for i0 in range(Num_k-1): + F = np.dot(vector_array[i0+1].transpose().conj(), vector_array[i0]) + W_k = np.dot(F, W_k) + nu = np.log(W_k)/2/pi/1j + # if np.real(nu) < 0: + # nu += 1 + print('p=', nu, '\n') + + +def get_occupied_bands_vectors(x, matrix): + matrix0 = matrix(x) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] + return vector + + +if __name__ == '__main__': + main() diff --git a/academic_codes/2021.03.08_eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices/eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices.nb b/academic_codes/2021.03.08_eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices/eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices.nb new file mode 100755 index 0000000..05acd1b --- /dev/null +++ b/academic_codes/2021.03.08_eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices/eigenvalues_of_the_Hamiltonian_composed_of_Pauli_matrices.nb @@ -0,0 +1,81 @@ +(* Content-type: application/vnd.wolfram.mathematica *) + +(*** Wolfram Notebook File ***) +(* http://www.wolfram.com/nb *) + +(* CreatedBy='Mathematica 12.0' *) + +(*CacheID: 234*) +(* Internal cache information: +NotebookFileLineBreakTest +NotebookFileLineBreakTest +NotebookDataPosition[ 158, 7] +NotebookDataLength[ 2039, 71] +NotebookOptionsPosition[ 1730, 57] +NotebookOutlinePosition[ 2086, 73] +CellTagsIndexPosition[ 2043, 70] +WindowFrame->Normal*) + +(* Beginning of Notebook Content *) +Notebook[{ +Cell[BoxData[{ + RowBox[{"Clear", "[", "\"\<`*\>\"", "]"}], "\n", + RowBox[{ + RowBox[{"H", "=", + RowBox[{ + RowBox[{"(", + RowBox[{"{", + RowBox[{ + RowBox[{"{", + RowBox[{"a0", ",", "0"}], "}"}], ",", + RowBox[{"{", + RowBox[{"0", ",", "a0"}], "}"}]}], "}"}], ")"}], "+", + RowBox[{"(", + RowBox[{"{", + RowBox[{ + RowBox[{"{", + RowBox[{"a3", ",", + RowBox[{"a1", "-", + RowBox[{"I", "*", "a2"}]}]}], "}"}], ",", + RowBox[{"{", + RowBox[{ + RowBox[{"a1", "+", + RowBox[{"I", "*", "a2"}]}], ",", + RowBox[{"-", "a3"}]}], "}"}]}], "}"}], ")"}]}]}], ";"}], "\n", + RowBox[{"MatrixForm", "[", "H", "]"}], "\n", + RowBox[{"eigenvalue", "=", + RowBox[{"MatrixForm", "[", + RowBox[{"Simplify", "[", + RowBox[{"Eigenvalues", "[", "H", "]"}], "]"}], "]"}]}], "\n", + RowBox[{"eigenvector", "=", + RowBox[{"MatrixForm", "[", + RowBox[{"Simplify", "[", + RowBox[{"Eigenvectors", "[", "H", "]"}], "]"}], "]"}]}]}], "Input", + CellChangeTimes->{{3.830338636045154*^9, + 3.830338636046383*^9}},ExpressionUUID->"6b5e0acb-1938-4b1e-bd73-\ +d3f6bb8905fc"] +}, +WindowSize->{759, 670}, +WindowMargins->{{Automatic, 572}, {64, Automatic}}, +FrontEndVersion->"12.0 for Microsoft Windows (64-bit) (2019\:5e744\:67088\ +\:65e5)", +StyleDefinitions->"Default.nb" +] +(* End of Notebook Content *) + +(* Internal cache information *) +(*CellTagsOutline +CellTagsIndex->{} +*) +(*CellTagsIndex +CellTagsIndex->{} +*) +(*NotebookFileOutline +Notebook[{ +Cell[558, 20, 1168, 35, 193, "Input",ExpressionUUID->"6b5e0acb-1938-4b1e-bd73-d3f6bb8905fc"] +} +] +*) + +(* End of internal cache information *) + diff --git a/academic_codes/2021.03.10_bands_of_type_II_Weyl_semimetals/bands_of_type_II_Weyl_semimetals.py b/academic_codes/2021.03.10_bands_of_type_II_Weyl_semimetals/bands_of_type_II_Weyl_semimetals.py new file mode 100755 index 0000000..a114181 --- /dev/null +++ b/academic_codes/2021.03.10_bands_of_type_II_Weyl_semimetals/bands_of_type_II_Weyl_semimetals.py @@ -0,0 +1,89 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10385 +""" + +import numpy as np +from math import * + + +def main(): + k1 = np.linspace(-pi, pi, 100) + k2 = np.linspace(-pi, pi, 100) + + eigenvalue_array = Calculate_Eigenvalue_with_Two_Parameters(k1, k2, hamiltonian) + Plot_3D_Surface(k1, k2, eigenvalue_array, xlabel='kx', ylabel='ky', zlabel='E', title='', filename='a') + + +def hamiltonian(kx,ky,kz=0): + w0x = 2 + w0y = 0 + w0z = 0 + vx = 1 + vy = 1 + vz = 1 + H = (w0x*kx+w0y*ky+w0z*kz)*sigma_0() + vx*kx*sigma_x()+vy*ky*sigma_y()+vz*kz*sigma_z() + return H + + +def sigma_0(): + return np.eye(2) + +def sigma_x(): + return np.array([[0, 1],[1, 0]]) + + +def sigma_y(): + return np.array([[0, -1j],[1j, 0]]) + + +def sigma_z(): + return np.array([[1, 0],[0, -1]]) + + +def Calculate_Eigenvalue_with_Two_Parameters(x, y, matrix): + dim = np.array(matrix(0, 0)).shape[0] + dim_x = np.array(x).shape[0] + dim_y = np.array(y).shape[0] + eigenvalue_array = np.zeros((dim_y, dim_x, dim)) + i0 = 0 + for y0 in y: + j0 = 0 + for x0 in x: + matrix0 = matrix(x0, y0) + eigenvalue, eigenvector = np.linalg.eig(matrix0) + eigenvalue_array[i0, j0, :] = np.sort(np.real(eigenvalue[:])) + j0 += 1 + i0 += 1 + return eigenvalue_array + + +def Plot_3D_Surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a'): + import matplotlib.pyplot as plt + from matplotlib import cm + from matplotlib.ticker import LinearLocator + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + plt.subplots_adjust(bottom=0.1, right=0.8) + x, y = np.meshgrid(x, y) + if len(matrix.shape) == 2: + surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) + elif len(matrix.shape) == 3: + for i0 in range(matrix.shape[2]): + surf = ax.plot_surface(x, y, matrix[:,:,i0], cmap=cm.coolwarm, linewidth=0, antialiased=False) + ax.set_title(title, fontsize=20, fontfamily='Times New Roman') + ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') + ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') + ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') + # ax.set_zlim(-1, 1) # 设置z轴的范围 + ax.zaxis.set_major_locator(LinearLocator(5)) # 设置z轴主刻度的个数 + ax.zaxis.set_major_formatter('{x:.2f}') # 设置z轴主刻度的格式 + ax.tick_params(labelsize=15) # 设置刻度值字体大小 + labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() + [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 + # plt.savefig(filename+'.jpg', dpi=300) + plt.show() + plt.close('all') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_Eigenvectors.nb b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_Eigenvectors.nb new file mode 100755 index 0000000..e654c98 --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_Eigenvectors.nb @@ -0,0 +1,73 @@ +(* Content-type: application/vnd.wolfram.mathematica *) + +(*** Wolfram Notebook File ***) +(* http://www.wolfram.com/nb *) + +(* CreatedBy='Mathematica 12.0' *) + +(*CacheID: 234*) +(* Internal cache information: +NotebookFileLineBreakTest +NotebookFileLineBreakTest +NotebookDataPosition[ 158, 7] +NotebookDataLength[ 2028, 65] +NotebookOptionsPosition[ 1687, 50] +NotebookOutlinePosition[ 2075, 67] +CellTagsIndexPosition[ 2032, 64] +WindowFrame->Normal*) + +(* Beginning of Notebook Content *) +Notebook[{ +Cell[BoxData[ + RowBox[{"\[IndentingNewLine]", + RowBox[{ + RowBox[{"Clear", "[", "\"\<`*\>\"", "]"}], "\[IndentingNewLine]", + RowBox[{ + RowBox[{"A", "=", + RowBox[{"{", + RowBox[{ + RowBox[{"{", + RowBox[{"3", ",", "2", ",", + RowBox[{"-", "1"}]}], "}"}], ",", + RowBox[{"{", + RowBox[{ + RowBox[{"-", "2"}], ",", + RowBox[{"-", "2"}], ",", "2"}], "}"}], ",", " ", + RowBox[{"{", + RowBox[{"3", ",", "6", ",", + RowBox[{"-", "1"}]}], "}"}]}], "}"}]}], ";"}], "\[IndentingNewLine]", + RowBox[{"MatrixForm", "[", "A", "]"}], "\n", + RowBox[{"eigenvalue", "=", + RowBox[{"MatrixForm", "[", + RowBox[{"Eigenvalues", "[", "A", "]"}], "]"}]}], "\n", + RowBox[{"eigenvector", "=", + RowBox[{"MatrixForm", "[", + RowBox[{"Eigenvectors", "[", "A", "]"}], "]"}]}]}]}]], "Input", + CellChangeTimes->{{3.8249089321894894`*^9, 3.8249090194456663`*^9}, { + 3.8249090545199647`*^9, 3.824909158471919*^9}, {3.8249092372038407`*^9, + 3.824909243121014*^9}}, + CellLabel->"In[24]:=",ExpressionUUID->"54dc89aa-0cf7-4c91-9e21-ea7b96cf97e8"] +}, +WindowSize->{1128, 568}, +WindowMargins->{{Automatic, 375}, {Automatic, 189}}, +Magnification:>1.2 Inherited, +FrontEndVersion->"12.0 for Microsoft Windows (64-bit) (2019\:5e744\:67088\ +\:65e5)", +StyleDefinitions->"Default.nb" +] +(* End of Notebook Content *) + +(* Internal cache information *) +(*CellTagsOutline +CellTagsIndex->{} +*) +(*CellTagsIndex +CellTagsIndex->{} +*) +(*NotebookFileOutline +Notebook[{ +Cell[558, 20, 1125, 28, 238, "Input",ExpressionUUID->"54dc89aa-0cf7-4c91-9e21-ea7b96cf97e8"] +} +] +*) + diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_eig.m b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_eig.m new file mode 100755 index 0000000..1439f2f --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_eig.m @@ -0,0 +1,3 @@ +clc;clear all; +A = [3, 2, -1; -2, -2, 2; 3, 6, -1] +[V,D] = eig(A) \ No newline at end of file diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_geev.f90 b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_geev.f90 new file mode 100755 index 0000000..55b5d7f --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_geev.f90 @@ -0,0 +1,40 @@ +program main + use lapack95 + implicit none + integer i,j,info + complex*16 A(3,3), eigenvalues(3), eigenvectors(3,3) + + A(1,1)=(3.d0, 0.d0) + A(1,2)=(2.d0, 0.d0) + A(1,3)=(-1.d0, 0.d0) + A(2,1)=(-2.d0, 0.d0) + A(2,2)=(-2.d0, 0.d0) + A(2,3)=(2.d0, 0.d0) + A(3,1)=(3.d0, 0.d0) + A(3,2)=(6.d0, 0.d0) + A(3,3)=(-1.d0, 0.d0) + + write(*,*) 'matrix:' + do i=1,3 + do j=1,3 + write(*,"(f10.4, '+1i*',f7.4)",advance='no') A(i,j) ! ѭΪеָ + enddo + write(*,*) '' + enddo + + call geev(A=A, W=eigenvalues, VR=eigenvectors, INFO=info) + + write(*,*) 'eigenvectors:' + do i=1,3 + do j=1,3 + write(*,"(f10.4, '+1i*',f7.4)",advance='no') eigenvectors(i,j) ! ѭΪеָꡣΪ + enddo + write(*,*) '' + enddo + write(*,*) 'eigenvalues:' + do i=1,3 + write(*,"(f10.4, '+1i*',f7.4)",advance='no') eigenvalues(i) + enddo + write(*,*) '' + write(*,*) '' +end program \ No newline at end of file diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_hermitian_matrix.py b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_hermitian_matrix.py new file mode 100755 index 0000000..8815fd0 --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_hermitian_matrix.py @@ -0,0 +1,21 @@ +import numpy as np + +A = np.array([[3, 2+1j, -1], [2-1j, -2, 6], [-1, 6, 1]]) +eigenvalue, eigenvector = np.linalg.eig(A) +print('矩阵:\n', A) +print('特征值:\n', eigenvalue) +print('特征向量:\n', eigenvector) + +print('\n判断是否正交:\n', np.dot(eigenvector.transpose().conj(), eigenvector)) +print('判断是否正交:\n', np.dot(eigenvector, eigenvector.transpose().conj())) + +print('特征向量矩阵的列向量模方和:') +for i in range(3): + print(np.abs(eigenvector[0, i])**2+np.abs(eigenvector[1, i])**2+np.abs(eigenvector[2, i])**2) +print('特征向量矩阵的行向量模方和:') +for i in range(3): + print(np.abs(eigenvector[i, 0])**2+np.abs(eigenvector[i, 1])**2+np.abs(eigenvector[i, 2])**2) + +print('\n对角化验证:') +print(np.dot(np.dot(eigenvector.transpose().conj(), A), eigenvector)) +print(np.dot(np.dot(eigenvector, A), eigenvector.transpose().conj())) \ No newline at end of file diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_numpy.linalg.eig.py b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_numpy.linalg.eig.py new file mode 100755 index 0000000..62e5d19 --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_numpy.linalg.eig.py @@ -0,0 +1,18 @@ +import numpy as np + +A = np.array([[3, 2, -1], [-2, -2, 2], [3, 6, -1]]) +eigenvalue, eigenvector = np.linalg.eig(A) +print('矩阵:\n', A) +print('特征值:\n', eigenvalue) +print('特征向量:\n', eigenvector) +print('特征值为-4对应的特征向量理论值:\n', np.array([1/3, -2/3, 1])/np.sqrt((1/3)**2+(-2/3)**2+1**2)) + +print('\n判断是否正交:\n', np.dot(eigenvector.transpose(), eigenvector)) +print('判断是否正交:\n', np.dot(eigenvector, eigenvector.transpose())) + +print('特征向量矩阵的列向量模方和:') +for i in range(3): + print(eigenvector[0, i]**2+eigenvector[1, i]**2+eigenvector[2, i]**2) +print('特征向量矩阵的行向量模方和:') +for i in range(3): + print(eigenvector[i, 0]**2+eigenvector[i, 1]**2+eigenvector[i, 2]**2) \ No newline at end of file diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix.py b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix.py new file mode 100755 index 0000000..99f34e5 --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix.py @@ -0,0 +1,21 @@ +import numpy as np + +A = np.array([[3, 2, -1], [2, -2, 6], [-1, 6, 1]]) +eigenvalue, eigenvector = np.linalg.eig(A) +print('矩阵:\n', A) +print('特征值:\n', eigenvalue) +print('特征向量:\n', eigenvector) + +print('\n判断是否正交:\n', np.dot(eigenvector.transpose(), eigenvector)) +print('判断是否正交:\n', np.dot(eigenvector, eigenvector.transpose())) + +print('特征向量矩阵的列向量模方和:') +for i in range(3): + print(eigenvector[0, i]**2+eigenvector[1, i]**2+eigenvector[2, i]**2) +print('特征向量矩阵的行向量模方和:') +for i in range(3): + print(eigenvector[i, 0]**2+eigenvector[i, 1]**2+eigenvector[i, 2]**2) + +print('\n对角化验证:') +print(np.dot(np.dot(eigenvector.transpose(), A), eigenvector)) +print(np.dot(np.dot(eigenvector, A), eigenvector.transpose())) \ No newline at end of file diff --git a/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix2.py b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix2.py new file mode 100755 index 0000000..c7d9d97 --- /dev/null +++ b/academic_codes/2021.03.17_verify_the_orientation_of_eigenvector_in_matrix/example_real_symmetric_matrix2.py @@ -0,0 +1,32 @@ +import numpy as np + +A = np.array([[0, 1, 1, -1], [1, 0, -1, 1], [1, -1, 0, 1], [-1, 1, 1, 0]]) +eigenvalue, eigenvector = np.linalg.eig(A) +print('矩阵:\n', A) +print('特征值:\n', eigenvalue) +print('特征向量:\n', eigenvector) + +print('\n判断是否正交:\n', np.dot(eigenvector.transpose(), eigenvector)) +print('判断是否正交:\n', np.dot(eigenvector, eigenvector.transpose())) + +print('特征向量矩阵的列向量模方和:') +for i in range(4): + print(eigenvector[0, i]**2+eigenvector[1, i]**2+eigenvector[2, i]**2+eigenvector[3, i]**2) +print('特征向量矩阵的行向量模方和:') +for i in range(4): + print(eigenvector[i, 0]**2+eigenvector[i, 1]**2+eigenvector[i, 2]**2+eigenvector[i, 3]**2) + +print('\n对角化验证:') +print(np.dot(np.dot(eigenvector.transpose(), A), eigenvector)) +print(np.dot(np.dot(eigenvector, A), eigenvector.transpose())) + +print('\n特征向量理论值:') +T = np.array([[1/np.sqrt(2), 1/np.sqrt(6), -1/np.sqrt(12), 1/2], [1/np.sqrt(2), -1/np.sqrt(6), 1/np.sqrt(12), -1/2], [0, 2/np.sqrt(6), 1/np.sqrt(12), -1/2], [0, 0, 3/np.sqrt(12), 1/2]]) +print(T) + +print('\n判断是否正交:\n', np.dot(T.transpose(), T)) +print('判断是否正交:\n', np.dot(T, T.transpose())) + +print('\n对角化验证:') +print(np.dot(np.dot(T.transpose(), A), T)) +print(np.dot(np.dot(T, A), T.transpose())) \ No newline at end of file diff --git a/academic_codes/2021.03.19_Schmidt_orthogonalization/Schmidt_orthogonalization.py b/academic_codes/2021.03.19_Schmidt_orthogonalization/Schmidt_orthogonalization.py new file mode 100755 index 0000000..a19fde6 --- /dev/null +++ b/academic_codes/2021.03.19_Schmidt_orthogonalization/Schmidt_orthogonalization.py @@ -0,0 +1,44 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10890 +""" + +import numpy as np + + +def main(): + A = np.array([[0, 1, 1, -1], [1, 0, -1, 1], [1, -1, 0, 1], [-1, 1, 1, 0]]) + eigenvalue, eigenvector = np.linalg.eig(A) + print('矩阵:\n', A) + print('特征值:\n', eigenvalue) + print('特征向量:\n', eigenvector) + + print('\n判断是否正交:\n', np.dot(eigenvector.transpose(), eigenvector)) + print('判断是否正交:\n', np.dot(eigenvector, eigenvector.transpose())) + + print('对角化验证:') + print(np.dot(np.dot(eigenvector.transpose(), A), eigenvector)) + + # 施密斯正交化 + eigenvector = Schmidt_orthogonalization(eigenvector) + + print('\n施密斯正交化后,特征向量:\n', eigenvector) + + print('施密斯正交化后,判断是否正交:\n', np.dot(eigenvector.transpose(), eigenvector)) + print('施密斯正交化后,判断是否正交:\n', np.dot(eigenvector, eigenvector.transpose())) + + print('施密斯正交化后,对角化验证:') + print(np.dot(np.dot(eigenvector.transpose(), A), eigenvector)) + + +def Schmidt_orthogonalization(eigenvector): + num = eigenvector.shape[1] + for i in range(num): + for i0 in range(i): + eigenvector[:, i] = eigenvector[:, i] - eigenvector[:, i0]*np.dot(eigenvector[:, i].transpose().conj(), eigenvector[:, i0])/(np.dot(eigenvector[:, i0].transpose().conj(),eigenvector[:, i0])) + eigenvector[:, i] = eigenvector[:, i]/np.linalg.norm(eigenvector[:, i]) + return eigenvector + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.03.19_plot_twist_graphene_with_python/graphene.py b/academic_codes/2021.03.19_plot_twist_graphene_with_python/graphene.py new file mode 100755 index 0000000..f6b6b3e --- /dev/null +++ b/academic_codes/2021.03.19_plot_twist_graphene_with_python/graphene.py @@ -0,0 +1,40 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10909 +""" + +import numpy as np + + +def main(): + x_array = np.arange(-5, 5.1) + y_array = np.arange(-5, 5.1) + coordinates = [] + for x in x_array: + for y in y_array: + coordinates.append([0+x*3, 0+y*np.sqrt(3)]) + coordinates.append([1+x*3, 0+y*np.sqrt(3)]) + coordinates.append([-1/2+x*3, np.sqrt(3)/2+y*np.sqrt(3)]) + coordinates.append([-3/2+x*3, np.sqrt(3)/2+y*np.sqrt(3)]) + plot_dots(coordinates) + + +def plot_dots(coordinates): + import matplotlib.pyplot as plt + x_range = max(np.array(coordinates)[:, 0])-min(np.array(coordinates)[:, 0]) + y_range = max(np.array(coordinates)[:, 1])-min(np.array(coordinates)[:, 1]) + fig, ax = plt.subplots(figsize=(9*x_range/y_range,9)) + plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95) + plt.axis('off') + for i1 in range(len(coordinates)): + for i2 in range(len(coordinates)): + if np.sqrt((coordinates[i1][0] - coordinates[i2][0])**2+(coordinates[i1][1] - coordinates[i2][1])**2) < 1.1: + ax.plot([coordinates[i1][0], coordinates[i2][0]], [coordinates[i1][1], coordinates[i2][1]], '-k', linewidth=1) + for i in range(len(coordinates)): + ax.plot(coordinates[i][0], coordinates[i][1], 'ro', markersize=8) + # plt.savefig('graphene.eps') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.03.19_plot_twist_graphene_with_python/square.py b/academic_codes/2021.03.19_plot_twist_graphene_with_python/square.py new file mode 100755 index 0000000..828c6e9 --- /dev/null +++ b/academic_codes/2021.03.19_plot_twist_graphene_with_python/square.py @@ -0,0 +1,35 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10909 +""" + +import numpy as np + + +def main(): + x_array = np.arange(-5, 5.1) + y_array = np.arange(-5, 5.1) + coordinates = [] + for x in x_array: + for y in y_array: + coordinates.append([x, y]) + plot_dots(coordinates) + + +def plot_dots(coordinates): + import matplotlib.pyplot as plt + fig, ax = plt.subplots(figsize=(9,9)) + plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95) + plt.axis('off') + for i1 in range(len(coordinates)): + for i2 in range(len(coordinates)): + if np.sqrt((coordinates[i1][0] - coordinates[i2][0])**2+(coordinates[i1][1] - coordinates[i2][1])**2) < 1.1: + ax.plot([coordinates[i1][0], coordinates[i2][0]], [coordinates[i1][1], coordinates[i2][1]], '-k', linewidth=1) + for i in range(len(coordinates)): + ax.plot(coordinates[i][0], coordinates[i][1], 'ro', markersize=10) + # plt.savefig('square.eps') + plt.show() + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.03.19_plot_twist_graphene_with_python/twist_graphene.py b/academic_codes/2021.03.19_plot_twist_graphene_with_python/twist_graphene.py new file mode 100755 index 0000000..b03b8ff --- /dev/null +++ b/academic_codes/2021.03.19_plot_twist_graphene_with_python/twist_graphene.py @@ -0,0 +1,73 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/10909 +""" + +from types import coroutine +import numpy as np +import copy +import matplotlib.pyplot as plt +from math import * + +def main(): + x_array = np.arange(-20, 20.1) + y_array = np.arange(-20, 20.1) + coordinates = [] + for x in x_array: + for y in y_array: + coordinates.append([0+x*3, 0+y*np.sqrt(3)]) + coordinates.append([1+x*3, 0+y*np.sqrt(3)]) + coordinates.append([-1/2+x*3, np.sqrt(3)/2+y*np.sqrt(3)]) + coordinates.append([-3/2+x*3, np.sqrt(3)/2+y*np.sqrt(3)]) + x_range1 = max(np.array(coordinates)[:, 0])-min(np.array(coordinates)[:, 0]) + y_range1 = max(np.array(coordinates)[:, 1])-min(np.array(coordinates)[:, 1]) + + theta = -1.1/180*pi + rotation_matrix = np.zeros((2, 2)) + rotation_matrix[0, 0] = np.cos(theta) + rotation_matrix[1, 1] = np.cos(theta) + rotation_matrix[0, 1] = -np.sin(theta) + rotation_matrix[1, 0] = np.sin(theta) + coordinates2 = copy.deepcopy(coordinates) + for i in range(len(coordinates)): + coordinates2[i] = np.dot(rotation_matrix, coordinates[i]) + x_range2 = max(np.array(coordinates2)[:, 0])-min(np.array(coordinates2)[:, 0]) + y_range2 = max(np.array(coordinates2)[:, 1])-min(np.array(coordinates2)[:, 1]) + + x_range = max([x_range1, x_range2]) + y_range = max([y_range1, y_range2]) + fig, ax = plt.subplots(figsize=(9*x_range/y_range,9)) + plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95) + plt.axis('off') + plot_dots_1(ax, coordinates) + plot_dots_2(ax, coordinates2) + plot_dots_0(ax, [[0, 0]]) + plt.savefig('twist_graphene.eps') + plt.show() + + +def plot_dots_0(ax, coordinates): + for i in range(len(coordinates)): + ax.plot(coordinates[i][0], coordinates[i][1], 'ko', markersize=0.5) + + +def plot_dots_1(ax, coordinates): + for i1 in range(len(coordinates)): + for i2 in range(len(coordinates)): + if np.sqrt((coordinates[i1][0] - coordinates[i2][0])**2+(coordinates[i1][1] - coordinates[i2][1])**2) < 1.1: + ax.plot([coordinates[i1][0], coordinates[i2][0]], [coordinates[i1][1], coordinates[i2][1]], '-k', linewidth=0.2) + for i in range(len(coordinates)): + ax.plot(coordinates[i][0], coordinates[i][1], 'ro', markersize=0.5) + + +def plot_dots_2(ax, coordinates): + for i1 in range(len(coordinates)): + for i2 in range(len(coordinates)): + if np.sqrt((coordinates[i1][0] - coordinates[i2][0])**2+(coordinates[i1][1] - coordinates[i2][1])**2) < 1.1: + ax.plot([coordinates[i1][0], coordinates[i2][0]], [coordinates[i1][1], coordinates[i2][1]], '--k', linewidth=0.2) + for i in range(len(coordinates)): + ax.plot(coordinates[i][0], coordinates[i][1], 'bo', markersize=0.5) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/eigenvalue_of_Kronecker_product_of_Pauli_matrices.py b/academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/eigenvalue_of_Kronecker_product_of_Pauli_matrices.py new file mode 100755 index 0000000..7a381f0 --- /dev/null +++ b/academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/eigenvalue_of_Kronecker_product_of_Pauli_matrices.py @@ -0,0 +1,48 @@ +import numpy as np +import gjh + +a_00 = np.random.uniform(-1, 1) +a_0x = np.random.uniform(-1, 1) +a_0y = np.random.uniform(-1, 1) +a_0z = np.random.uniform(-1, 1) + +a_x0 = np.random.uniform(-1, 1) +a_xx = np.random.uniform(-1, 1) +a_xy = np.random.uniform(-1, 1) +a_xz = np.random.uniform(-1, 1) + +a_y0 = np.random.uniform(-1, 1) +a_yx = np.random.uniform(-1, 1) +a_yy = np.random.uniform(-1, 1) +a_yz = np.random.uniform(-1, 1) + +a_z0 = np.random.uniform(-1, 1) +a_zx = np.random.uniform(-1, 1) +a_zy = np.random.uniform(-1, 1) +a_zz = np.random.uniform(-1, 1) + +hamiltonian_1 = \ + a_00*gjh.sigma_00()+a_0x*gjh.sigma_0x()+a_0y*gjh.sigma_0y()+a_0z*gjh.sigma_0z()+ \ + a_x0*gjh.sigma_x0()+a_xx*gjh.sigma_xx()+a_xy*gjh.sigma_xy()+a_xz*gjh.sigma_xz()+ \ + a_y0*gjh.sigma_y0()+a_yx*gjh.sigma_yx()+a_yy*gjh.sigma_yy()+a_yz*gjh.sigma_yz()+ \ + a_z0*gjh.sigma_z0()+a_zx*gjh.sigma_zx()+a_zy*gjh.sigma_zy()+a_zz*gjh.sigma_zz() +eigenvalue_1 = gjh.calculate_eigenvalue(hamiltonian_1) + +hamiltonian_2 = \ + a_00*gjh.sigma_00()+a_0x*gjh.sigma_x0()+a_0y*gjh.sigma_y0()+a_0z*gjh.sigma_z0()+ \ + a_x0*gjh.sigma_0x()+a_xx*gjh.sigma_xx()+a_xy*gjh.sigma_yx()+a_xz*gjh.sigma_zx()+ \ + a_y0*gjh.sigma_0y()+a_yx*gjh.sigma_xy()+a_yy*gjh.sigma_yy()+a_yz*gjh.sigma_zy()+ \ + a_z0*gjh.sigma_0z()+a_zx*gjh.sigma_xz()+a_zy*gjh.sigma_yz()+a_zz*gjh.sigma_zz() +eigenvalue_2 = gjh.calculate_eigenvalue(hamiltonian_2) + + +print() +print('Eigenvalue:') +print(eigenvalue_1) +print(eigenvalue_2) +print() +print('Difference of matrices:') +print(hamiltonian_1-hamiltonian_2) +print() +# print(hamiltonian_1) +# print(hamiltonian_2) \ No newline at end of file diff --git a/academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/test2_eigenvalue_of_Kronecker_product_of_Pauli_matrices.py b/academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/test2_eigenvalue_of_Kronecker_product_of_Pauli_matrices.py new file mode 100755 index 0000000..c868823 --- /dev/null +++ b/academic_codes/2021.05.21_eigenvalue_of_Kronecker_product_of_Pauli_matrices/test2_eigenvalue_of_Kronecker_product_of_Pauli_matrices.py @@ -0,0 +1,44 @@ +import numpy as np +import gjh + +a_00 = np.random.uniform(-1, 1) +a_0x = np.random.uniform(-1, 1) +a_0y = np.random.uniform(-1, 1) +a_0z = np.random.uniform(-1, 1) + +a_x0 = np.random.uniform(-1, 1) +a_xx = np.random.uniform(-1, 1) +a_xy = np.random.uniform(-1, 1) +a_xz = np.random.uniform(-1, 1) + +a_y0 = np.random.uniform(-1, 1) +a_yx = np.random.uniform(-1, 1) +a_yy = np.random.uniform(-1, 1) +a_yz = np.random.uniform(-1, 1) + +a_z0 = np.random.uniform(-1, 1) +a_zx = np.random.uniform(-1, 1) +a_zy = np.random.uniform(-1, 1) +a_zz = np.random.uniform(-1, 1) + +hamiltonian_1 = \ + a_00*gjh.sigma_00()+a_0x*gjh.sigma_0x()+a_0y*gjh.sigma_0y()+a_0z*gjh.sigma_0z()+ \ + a_x0*gjh.sigma_x0()+a_xx*gjh.sigma_xx()+a_xy*gjh.sigma_xy()+a_xz*gjh.sigma_xz()+ \ + a_y0*gjh.sigma_y0()+a_yx*gjh.sigma_yx()+a_yy*gjh.sigma_yy()+a_yz*gjh.sigma_yz()+ \ + a_z0*gjh.sigma_z0()+a_zx*gjh.sigma_zx()+a_zy*gjh.sigma_zy()+a_zz*gjh.sigma_zz() +eigenvalue_1 = gjh.calculate_eigenvalue(hamiltonian_1) + + +# only gjh.sigma_0x() is changed to gjh.sigma_x0() +hamiltonian_3 = \ + a_00*gjh.sigma_00()+a_0x*gjh.sigma_x0()+a_0y*gjh.sigma_0y()+a_0z*gjh.sigma_0z()+ \ + a_x0*gjh.sigma_x0()+a_xx*gjh.sigma_xx()+a_xy*gjh.sigma_xy()+a_xz*gjh.sigma_xz()+ \ + a_y0*gjh.sigma_y0()+a_yx*gjh.sigma_yx()+a_yy*gjh.sigma_yy()+a_yz*gjh.sigma_yz()+ \ + a_z0*gjh.sigma_z0()+a_zx*gjh.sigma_zx()+a_zy*gjh.sigma_zy()+a_zz*gjh.sigma_zz() +eigenvalue_3 = gjh.calculate_eigenvalue(hamiltonian_3) + +print() +print('Eigenvalue:') +print(eigenvalue_1) +print(eigenvalue_3) +print() \ No newline at end of file diff --git a/language_learning/2019.10.10_python_example/python_example.py b/language_learning/2019.10.10_python_example/python_example.py new file mode 100755 index 0000000..99f3c9c --- /dev/null +++ b/language_learning/2019.10.10_python_example/python_example.py @@ -0,0 +1,76 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/417 +""" + +import numpy as np + +# Python基本操作【循环,判断,函数,文件写入】 +for i in range(5): # 循环(这里只举例for循环,要了解while循环可自行搜索资料) + print('我是循环产生的数:', i) # Python中没有end,所以缩进很重要,不能省! + if i == 2: # 判断 + print('判断:我是第三个数 2') + else: + pass # pass代表不执行任何语句,用于占位,可以之后再补充,不然空着会报错 +print() # 空一行 + + +def fun0(arg): # 定义函数 + print('我是函数中的内容,参数值为:', arg) # \n代表换行 + return arg*2 # 返回值 + + +print('函数返回值:', fun0(5), '\n') # 调用函数 +# 关于类class,这里不举例了。科学计算中主要还是面向过程,面向对象用的比较少。有需要了解的可以自行搜索资料。 + +# 文件写入 +# 第一种方式 +with open('test1.txt', 'w') as f1: # 其中'w'为重新写入,改为'a'是补充内容 + f1.write(str(100)+'\n这是第一种方式写入文件') # str()为转换成字符串 +# 第二种方式 +f2 = open('test2.txt', 'w') # 打开文件 +f2.write(str(200)+'\n这是第二种方式写入文件') # 写入文件 +f2.close() # 关闭文件 + + +# Numpy库中常用的语句 +print('零矩阵:\n', np.zeros((2, 3))) # 注意np.zeros()里需要填元组,因此是两个括号 +print('单位矩阵:\n', np.identity(3)) # 3行3列的单位矩阵,或者可以用np.eye() +print('把一维数组按对角矩阵排列:\n', np.diag([1, 3, 5]), '\n') + +print('指定步长的等差数列:\n', np.arange(1, 5, .5)) # 区间是左闭右开[1, 5) +print('指定个数的等差数列:\n', np.linspace(-2, 2, 5), '\n') # 区间是左闭右闭[-2, 2], 数量是5 + +print('随机数:\n', np.random.uniform(-2, 2)) # 区间是左闭右开[-2, 2) +print('随机整数:\n', np.random.randint(-10, 10), '\n') # 区间是左闭右闭[-10, 10] + +print('数组从小到大排列:\n', np.sort([1, 7, 0, 3])) +print('数组从小到大排列对应的索引:\n', np.argsort([1, 7, 0, 3]), '\n') # 注意Python中下标是从0开始的 + +matrix0 = np.array([[1, 2+9j, 3], [2, 5, 7]]) +print('矩阵0:\n', matrix0) +print('矩阵的维度:\n', matrix0.shape) # 查看矩阵的维度 +print('矩阵的行数:\n', matrix0.shape[0]) # 查看矩阵的行数 +print('矩阵的列数:\n', matrix0.shape[1]) # 查看矩阵的列数 +print('矩阵转置:\n', matrix0.transpose()) # 矩阵转置 +print('矩阵转置共轭:\n', matrix0.transpose().conj(), '\n') # 矩阵转置共轭 + +matrix1 = np.array([[3, 5], [2, 7]]) # numpy数组 +eigenvalue, eigenvector = np.linalg.eig(matrix1) # 求本征值,本征向量 +print('矩阵1:\n', matrix1) +print('本征值:\n', eigenvalue) +print('本征向量:\n', eigenvector) # 列向量对应的是本征矢量 +print('逆矩阵:\n', np.linalg.inv(matrix1)) +print('计算行列式:\n', np.linalg.det(matrix1), '\n') + +matrix2 = np.array([[1, 2], [3, 4]]) +print('矩阵2:\n', matrix2) +print('矩阵1和矩阵2相乘:\n', np.matmul(matrix1, matrix2), '\n') # 矩阵乘积,或者可以用np.dot() + +a = np.array([1, 2]) +print('数组a=', a) +b = np.array([3, 4]) +print('数组b=', b) +print('增加元素:\n', np.append(a, b, axis=0)) # 增加元素 +print('增加行:\n', np.append([a], [b], axis=0)) # 增加行(列数要相同),或者用np.row_stack(([a], [b])) +print('增加列:\n', np.append([a], [b], axis=1)) # 增加列(行数要相同),或者用np.column_stack(([a], [b])) diff --git a/language_learning/2019.10.11_0_tensorflow_example/tensorflow.py b/language_learning/2019.10.11_0_tensorflow_example/tensorflow.py new file mode 100755 index 0000000..d88edde --- /dev/null +++ b/language_learning/2019.10.11_0_tensorflow_example/tensorflow.py @@ -0,0 +1,39 @@ +import tensorflow as tf # 导入tensorflow + +greeting = tf.constant('Hello Google Tensorflow!') # 定义一个常量 + +# 第一种方式 +sess = tf.Session() # 启动一个会话 +result = sess.run(greeting) # 使用会话执行greeting计算模块 +print(result) # 打印显示 +sess.close() # 关闭会话 + +# 第二种方式 +with tf.Session() as sess: # 启动一个会话 + print(sess.run(greeting)) # 打印显示 + + +# 例子1: +matrix1 = tf.constant([[1., 3.]]) # 定义常数矩阵1 tf.constant() +matrix2 = tf.constant([[2.], [2.]]) # 定义常数矩阵2 tf.constant() +product = tf.matmul(matrix1, matrix2) # 矩阵乘积 tf.matmul() +linear = tf.add(product, tf.constant(2.)) # 矩阵乘积后再加上一个常数 tf.add() +with tf.Session() as sess: # 启动一个会话 tf.Session() + print(sess.run(matrix1)) # 执行语句并打印显示 tf.Session().run + print(sess.run(linear)) # 执行语句并打印显示 tf.Session().run +print(linear) # 直接打印是不能看到计算结果的,因为还未执行,只是一个张量。这里打印显示的结果是:Tensor("Add:0", shape=(1, 1), dtype=float32) + + +# 例子2:变量tf.Variable() +state = tf.Variable(3, name='counter') # 变量tf.Variable +init = tf.global_variables_initializer() # 如果定义了变量,后面一定要有这个语句,用来初始化变量。 +with tf.Session() as sess: + sess.run(init) # 变量一定要初始化变量 + print(sess.run(state)) # 执行语句并打印显示 + +# 例子3:占位符tf.placeholder(),用来临时占坑,需要用feed_dict来传入数值。 +x1 = tf.placeholder(tf.float32) +x2 = tf.placeholder(tf.float32) +y = x1 + x2 +with tf.Session() as sess: + print(sess.run(y, feed_dict={x1: 7, x2: 2})) diff --git a/language_learning/2019.10.11_1_neutral_network_with_tensorflow/neutral_network_with_tensorflow.py b/language_learning/2019.10.11_1_neutral_network_with_tensorflow/neutral_network_with_tensorflow.py new file mode 100755 index 0000000..f89da73 --- /dev/null +++ b/language_learning/2019.10.11_1_neutral_network_with_tensorflow/neutral_network_with_tensorflow.py @@ -0,0 +1,77 @@ +import tensorflow as tf +import numpy as np +import matplotlib.pyplot as plt + + +def add_layer(inputs, in_size, out_size, activation_function=None): # 定义一层的所有神经元 + Weights = tf.Variable(tf.random_normal([in_size, out_size])) # 定义Weights为tf变量,并给予初值 + biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) # 定义biases为tf变量,并给予初值 + Wx_plus_b = tf.matmul(inputs, Weights) + biases # 得分 + if activation_function is None: # 没有激活函数 + outputs = Wx_plus_b + else: + outputs = activation_function(Wx_plus_b) # 使用激活函数 + return outputs # 返回该层每个神经元的输出值(维度为out_size) + + +# 产生训练的数据 +x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis] # 产生数据,作为神经网络的输入数据。注:[:, np.newaxis]是用来增加一个轴,变成一个矩阵。 +noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32) # 产生噪声 +y_data = np.square(x_data) - 0.5 + noise # x_data加上噪声,作为神经网络的输出数据。 +print(x_data.shape) # 查看数据维度 +print(noise.shape) # 查看数据维度 +print(y_data.shape) # 查看数据维度 +print() # 打印输出空一行 + + +# 神经网络模型的建立 +xs = tf.placeholder(tf.float32, [None, 1]) # 定义占位符,为神经网络训练的输入数据。这里的None代表无论输入有多少数据都可以 +ys = tf.placeholder(tf.float32, [None, 1]) # 定义占位符,为神经网络训练的输出数据。 +l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) # 增加一个隐藏层 +prediction = add_layer(l1, 10, 1, activation_function=None) # 输出层 +loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1])) # 损失函数 +train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 梯度下降 +init = tf.global_variables_initializer() # 变量初始化 + +# 画出原始的输入输出数据点图 +fig = plt.figure() +ax = fig.add_subplot(1, 1, 1) +ax.scatter(x_data, y_data) +plt.ion() # 开启交互模式 +plt.show() # 显示图像 + +# 训练神经网络模型 +sess = tf.Session() # 启动一个会话 +sess.run(init) # 初始化变量 +for i in range(1000): # 训练1000次 + sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) # 喂数据,梯度下降循环1000次。 + if i % 50 == 0: # 每训练50次画一下图 + try: # to visualize the result and improvement + ax.lines.remove(lines[0]) + except Exception: + pass + prediction_value = sess.run(prediction, feed_dict={xs: x_data}) # 神经网络预测的值 + print('loss=', sess.run(loss, feed_dict={xs: x_data, ys: y_data})) # 打印输出,查看损失函数下降情况 + print('prediction=', sess.run(prediction, feed_dict={xs: [x_data[0, :]]})) # # 打印输出神经网络预测的值 + print() # 打印空一行 + lines = ax.plot(x_data, prediction_value, 'r-', lw=5) # 画出预测的值,用线连起来 + plt.pause(.1) # 暂停0.1,防止画图过快看不清。 +plt.ioff() # 关闭交互模式,再画一次图。作用是不让图自动关掉。 +lines = ax.plot(x_data, prediction_value, 'r-', lw=5) +plt.show() + + +# 保存训练好的神经网络模型tf.train.Saver() +saver = tf.train.Saver() +save_path = saver.save(sess, "my_net/save_net.ckpt") # 保存模型 +print("Save to path: ", save_path) +print() +sess.close() # 关闭会话 + + +# 调用神经网络模型,来预测新的值 +with tf.Session() as sess2: + saver.restore(sess2, "my_net/save_net.ckpt") # 提取模型中的所有变量 + print(y_data[0, :]) # 输出的原始值 + print(sess2.run(prediction, feed_dict={xs: [x_data[0, :]]})) # 预测值 + diff --git a/language_learning/2019.10.27_0_ball_games_with_pygame/ball_games_with_pygame.py b/language_learning/2019.10.27_0_ball_games_with_pygame/ball_games_with_pygame.py new file mode 100755 index 0000000..ec9f4ab --- /dev/null +++ b/language_learning/2019.10.27_0_ball_games_with_pygame/ball_games_with_pygame.py @@ -0,0 +1,359 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/703 +""" + +import pygame +import random +import math +import numpy as np + +# 参数 +screen_width = 1500 # 屏幕宽度 +screen_height = 900 # 屏幕高度 +map_width = screen_width*4 # 地图的大小 +map_height = screen_height*4 # 地图的大小 +number_enemy = map_width*map_height/500000 # 敌人的数量 +number_dots = map_width * map_height / 50 # 点点的数量 +max_show_size = 100 # 球显示的最大半径(屏幕有限,球再增大时,改变的地图比例尺寸) + +my_value = 1000 # 我的初始值 +enemy_value_low = 500 # 敌人的初始值(最低) +enemy_value_high = 1500 # 敌人的初始值(最高) +dot_value = 30 # 点点的值(地上的豆豆/食物值) +my_speed = 10 # 我的球运动的速度 +speed_up = 20 # 按下鼠标时加速 +speed_enemy = 10 # 敌人球正常运动速度 +speed_enemy_anomaly = 20 # 敌人突然加速时的速度(速度异常时的速度) +anomaly_pro = 0.5 # 敌人加速的概率 +change_pro = 0.05 # 敌人移动路径变化的概率,也就是1/change_pro左右会变化一次 +eat_percent = 0.9 # 吃掉敌人的球,按多少比例并入自己的体积,1对应的是100% +loss = 0.001 # 按比例减小体重(此外越重的减少越多,10万体积损失值为loss的一倍) +enemy_bigger_pro = 0.0005 # 敌人的值增加了我的球的值的enemy_bigger_rate倍的几率 +enemy_bigger_rate = 0.1 # 增加我的球的体积的enemy_bigger_rate倍 + + +class Color(object): # 定义颜色的类 + @classmethod # 加了这个可以不需要把实例化,能直接调用类的方法 + def random_color(cls): # cls, 即class,表示可以通过类名直接调用 + red = random.randint(0, 255) + green = random.randint(0, 255) + blue = random.randint(0, 255) + return red, green, blue + + +class Ball(object): # 定义球 + def __init__(self, x, y, sx, sy, color, value): # 初始化 + self.x = x # 球的地图位置参数 + self.y = y + self.sx = sx # 速度参数 + self.sy = sy + self.color = color # 颜色 + self.value = value # 球的值,也就是球的大小(不是显示的大小) + self.is_alive = True # 球默认是存活状态 + + +class My_Ball(Ball): # 定义我的球,继承了Ball类的方法 + def __init__(self, x, y, sx, sy, color, value): + # 注意:如果重写了__init__() 时,实例化子类,就不会调用父类已经定义的__init__() + # 如果子类不重写__init__()方法,实例化子类后,会自动调用父类的__init__()的方法 + # 如果子类重写__init__()方法又需要调用父类的方法,则要使用super关键词。 + super().__init__(x, y, sx, sy, color, value) # 调用父类Ball的初始化方法__init__() + self.radius = int(self.value**0.5) # 我的球的半径(不考虑系数pi) + if self.radius >= max_show_size: # 如果半径比规定的最大半径还大,则显示最大半径 + self.show_radius = max_show_size # 我的球显示的半径 + else: + self.show_radius = self.radius # 如果半径没有超过规定最大的半径,则显示原来实际大小的半径 + self.position_x = int(screen_width/2) # 把我的球固定在屏幕中间position_x,是屏幕显示的位置 + self.position_y = int(screen_height/2) # 把我的球固定在屏幕中间position_y,是屏幕显示的位置 + + def draw(self, window): # 把我的球画出来 + self.radius = int(self.value ** 0.5) # 这里重复上面的,因为除了初始化之后,还要更新 + if self.radius >= max_show_size: + self.show_radius = max_show_size + else: + self.show_radius = self.radius + self.position_x = int(screen_width / 2) + self.position_y = int(screen_height / 2) + pygame.draw.circle(window, self.color, (self.position_x , self.position_y), self.show_radius) + + def eat_ball(self, other): # 吃别的球(包括小点点和敌人) + if self != other and self.is_alive and other.is_alive: # 如果other不是自身,自身和对方也都是存活状态,则执行下面动作 + distance = ((self.position_x - other.position_x) ** 2 + (self.position_y - other.position_y) ** 2) ** 0.5 # 两个球之间的距离 + if distance < self.show_radius and (self.show_radius > other.show_radius or (self.show_radius == other.show_radius and self.value > other.value)): # 如果自身半径比别人大,而且两者距离小于自身半径,那么可以吃掉。 + other.is_alive = False # 吃球(敌方已死) + self.value += other.value*eat_percent # 自己的值增大(体量增大) + self.radius = int(self.value ** 0.5) # 计算出半径 + if self.radius >= max_show_size: # 我的球的显示半径 + self.show_radius = max_show_size + else: + self.show_radius = self.radius + + def move(self): # 移动规则 + self.x += self.sx # 地图位置加上速度 + self.y += self.sy + # 横向出界 + if self.x < 0: # 离开了地图左边 + self.x = 0 + if self.x > map_width: # 离开了地图右边 + self.x = map_width + # 纵向出界 + if self.y <= 0: # 离开了地图下边 + self.y = 0 + if self.y >= map_height: # 离开了地图上边 + self.y = map_height + + +class Enemy_Ball(Ball): # 定义敌人的球,继承了Ball类的方法 + def __init__(self, x, y, sx, sy, color, value, host_ball): # 初始化带上host_ball,也就是我的球 + super().__init__(x, y, sx, sy, color, value) + self.host_ball = host_ball + self.radius = int(self.value**0.5) + if self.host_ball.radius >= max_show_size: # 如果我的球比规定的最大尺寸还大,则敌人的球显示的比例要减小 + self.show_radius = max(10, int(self.radius/(self.host_ball.radius/max_show_size))) # 敌人的球也不能太小,最小半径为10 + self.position_x = int((self.x - self.host_ball.x) / (self.host_ball.radius / max_show_size)) + int( + screen_width / 2) # 计算出敌人的球和我的球的相对位置,并且按比例减小 + self.position_y = int((self.y - self.host_ball.y) / (self.host_ball.radius / max_show_size)) + int( + screen_height / 2) # 计算出敌人的球和我的球的相对位置,并且按比例减小 + else: + self.show_radius = self.radius # 正常显示 + self.position_x = (self.x - self.host_ball.x) + int(screen_width / 2) # 敌人和我的球的相对位置 + self.position_y = (self.y - self.host_ball.y) + int(screen_height / 2) # 敌人和我的球的相对位置 + + # 画出球 + def draw(self, window): + self.radius = int(self.value ** 0.5) + if self.host_ball.radius >= max_show_size: # 这边把初始化的内容再写一遍,因为敌人的球初始化之后还要根据我的球而动态改变 + self.show_radius = max(10, int(self.radius/(self.host_ball.radius/max_show_size))) + self.position_x = int((self.x - self.host_ball.x) / (self.host_ball.radius / max_show_size)) + int( + screen_width / 2) + self.position_y = int((self.y - self.host_ball.y) / (self.host_ball.radius / max_show_size)) + int( + screen_height / 2) + else: + self.show_radius = self.radius + self.position_x = (self.x - self.host_ball.x) + int(screen_width / 2) + self.position_y = (self.y - self.host_ball.y) + int(screen_height / 2) + pygame.draw.circle(window, self.color, (self.position_x, self.position_y), self.show_radius) + + def eat_ball(self, other): + if self != other and self.is_alive and other.is_alive: + distance = ((self.position_x - other.position_x) ** 2 + (self.position_y - other.position_y) ** 2) ** 0.5 + if distance < self.show_radius and (self.show_radius > other.show_radius or (self.show_radius == other.show_radius and self.value > other.value)): + other.is_alive = False # 吃球 + self.value += other.value*eat_percent + self.radius = int(self.value ** 0.5) + + def move(self): # 移动规则 + self.x += self.sx # 地图位置加上速度 + self.y += self.sy + # 横向出界 + if self.x < 0: # 离开了地图左边 + self.sx = -self.sx + self.x = 0 + if self.x > map_width: # 离开了地图右边 + self.sx = -self.sx + self.x = map_width + # 纵向出界 + if self.y <= 0: # 离开了地图下边 + self.sy = -self.sy + self.y = 0 + if self.y >= map_height: # 离开了地图上边 + self.sy = -self.sy + self.y = map_height + + +class Dot_Ball(Ball): # 定义地上的小点点,供自己的球和敌人的球吃,继承了Ball类的方法 + def __init__(self, x, y, sx, sy, color, value, host_ball): + super().__init__(x, y, sx, sy, color, value) + self.host_ball = host_ball + self.radius = 8 # 初始小点点大小 + if self.host_ball.radius >= max_show_size: + self.show_radius = max(3, int(self.radius/(self.host_ball.radius/max_show_size))) # 小点点显示也不能太小,最小显示半径为3 + self.position_x = int((self.x - self.host_ball.x) / (self.host_ball.radius / max_show_size)) + int( + screen_width / 2) + self.position_y = int((self.y - self.host_ball.y) / (self.host_ball.radius / max_show_size)) + int( + screen_height / 2) + else: + self.show_radius = self.radius + self.position_x = (self.x - self.host_ball.x) + int(screen_width / 2) + self.position_y = (self.y - self.host_ball.y) + int(screen_height / 2) + + # 画出球 + def draw(self, window): + if self.host_ball.radius >= max_show_size: # 这边把初始化的内容再写一遍,因为小点点初始化之后还要根据我的球而动态改变 + self.show_radius = max(3, int(self.radius/(self.host_ball.radius/max_show_size))) + self.position_x = int((self.x - self.host_ball.x) / (self.host_ball.radius / max_show_size)) + int( + screen_width / 2) + self.position_y = int((self.y - self.host_ball.y) / (self.host_ball.radius / max_show_size)) + int( + screen_height / 2) + else: + self.show_radius = self.radius + self.position_x = (self.x - self.host_ball.x) + int(screen_width / 2) + self.position_y = (self.y - self.host_ball.y) + int(screen_height / 2) + pygame.draw.circle(window, self.color, (self.position_x, self.position_y) , self.show_radius) + + +def creat_my_ball(): # 产生我的球 + x = random.randint(0, map_width) # 我的球在地图中的位置,随机生成 + y = random.randint(0, map_height) + value = my_value # 我的球的初始值 + color = 255, 255, 255 # 我的球的颜色 + sx = 0 # 速度默认为0 + sy = 0 + host_ball = My_Ball(x, y, sx, sy, color, value) # 调用My_Ball类 + return host_ball # 返回我的球 + + +def auto_creat_ball(balls, host_ball): # 自动产生敌人的球 + if len(balls) <= number_enemy: # 控制敌人的数量,如果个数够了,就不再生成 + x = random.randint(0, map_width) # 敌人球在地图中的位置,随机生成 + y = random.randint(0, map_height) + value = random.randint(enemy_value_low, enemy_value_high) # 敌人的球初始值 + sx = random.randint(-speed_enemy, speed_enemy) # 敌人的球移动速度 + i2 = random.randint(0, 1) # y的移动方向 + if i2 == 0: + sy = int((speed_enemy**2 - sx**2) ** 0.5) + else: + sy = -int((speed_enemy ** 2 - sx ** 2) ** 0.5) + color = Color.random_color() # 敌人的颜色随机生成 + enemy = Enemy_Ball(x, y, sx, sy, color, value, host_ball) + balls.append(enemy) + + +def auto_creat_dots(dots, host_ball): # 自动生成点点 + if len(dots) <= number_dots: # 控制点点的数量 + x = random.randint(0, map_width) # 随机生成点点的位置 + y = random.randint(0, map_height) + value = dot_value # 点点的值 + sx = 0 # 点点速度为0 + sy = 0 + color = Color.random_color() # 颜色 + dot = Dot_Ball(x, y, sx, sy, color, value, host_ball) + dots.append(dot) + + +def control_my_ball(host_ball): # 控制我的球 + host_ball.move() + host_ball.value = host_ball.value*(1-loss*host_ball.value/100000) + for event in pygame.event.get(): # 监控事件(鼠标移动) + # print(event) + if event.type == pygame.MOUSEBUTTONDOWN: + pos = event.pos + speed = speed_up + elif event.type == pygame.MOUSEMOTION: + pos = event.pos + if event.buttons[0] == 1: + speed = speed_up + if event.buttons[0] == 0: + speed = my_speed + elif event.type == pygame.MOUSEBUTTONUP: + pos = event.pos + speed = my_speed + else: + pos = [screen_width/2, screen_height/2] + speed = my_speed + if abs(pos[0] - screen_width/2) < 30 and abs(pos[1] - screen_height/2) < 30: + host_ball.sx = 0 + host_ball.sy = 0 + elif pos[0] > screen_width/2 and pos[1] >= screen_height/2: + angle = abs(math.atan((pos[1] - screen_height/2) / (pos[0] - screen_width/2))) + host_ball.sx = int(speed * math.cos(angle)) + host_ball.sy = int(speed * math.sin(angle)) + elif pos[0] > screen_width/2 and pos[1] < screen_height/2: + angle = abs(math.atan((pos[1] - screen_height/2) / (pos[0] - screen_width/2))) + host_ball.sx = int(speed * math.cos(angle)) + host_ball.sy = -int(speed * math.sin(angle)) + elif pos[0] < screen_width/2 and pos[1] >= screen_height/2: + angle = abs(math.atan((pos[1] - screen_height/2) / (pos[0] - screen_width/2))) + host_ball.sx = -int(speed * math.cos(angle)) + host_ball.sy = int(speed * math.sin(angle)) + elif pos[0] < screen_width/2 and pos[1] < screen_height/2: + angle = abs(math.atan((pos[1] - screen_height/2) / (pos[0] - screen_width/2))) + host_ball.sx = -int(speed * math.cos(angle)) + host_ball.sy = -int(speed * math.sin(angle)) + elif pos[0] == screen_width/2: + host_ball.sx = 0 + if pos[1] >= 0: + host_ball.sy = speed + else: + host.ball.sy = -speed + + +def enemy_move(balls, host_ball): # 敌人移动 + for enemy in balls: + enemy.move() # 移动 + enemy.value = enemy.value*(1-loss*enemy.value/100000) + if random.randint(1, int(1/enemy_bigger_pro)) == 1: + enemy.value += host_ball.value*enemy_bigger_rate + if random.randint(1, int(1/anomaly_pro)) == 1: + speed_enemy0 = speed_enemy_anomaly # 敌人异常速度 + else: + speed_enemy0 = speed_enemy # 敌人正常速度 + i = random.randint(1, int(1/change_pro)) # 一定的概率改变轨迹 + if i == 1: + enemy.sx = random.randint(-speed_enemy0, speed_enemy0) + i2 = random.randint(0, 1) + if i2 == 0: + enemy.sy = int((speed_enemy0 ** 2 - enemy.sx ** 2) ** 0.5) + else: + enemy.sy = -int((speed_enemy0 ** 2 - enemy.sx ** 2) ** 0.5) + + +def eat_each_other(host_ball, balls, dots): # 吃球 + for enemy in balls: + for enemy2 in balls: + enemy.eat_ball(enemy2) # 敌人互吃 + for food in dots: + enemy.eat_ball(food) # 敌人吃点点 + for enemy in balls: + host_ball.eat_ball(enemy) # 我吃敌人 + enemy.eat_ball(host_ball) # 敌人吃我 + for food in dots: + host_ball.eat_ball(food) # 我吃点点 + + +def paint(host_ball, balls, dots, screen): + screen.fill((0, 0, 0)) # 刷漆 + if host_ball.is_alive: + host_ball.draw(screen) + for enemy in balls: # 遍历容器 + if enemy.is_alive: + enemy.draw(screen) + else: + balls.remove(enemy) + for food in dots: # 遍历容器 + if food.is_alive: + food.draw(screen) + else: + dots.remove(food) + + +def main(): + pygame.init() # 初始化 + screen = pygame.display.set_mode((screen_width, screen_height)) # 设置屏幕 + pygame.display.set_caption("球球大作战") # 设置屏幕标题 + balls = [] # 定义一容器 存放所有的敌方球 + dots = [] # 定义一容器 存放所有的点点 + is_running = True # 默认运行状态 + host_ball = creat_my_ball() # 产生我的球 + i00 = 0 # 一个参数 + while is_running: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + is_running = False + auto_creat_dots(dots, host_ball) # 自动生成点点 + auto_creat_ball(balls, host_ball) # 自动生成敌人 + paint(host_ball, balls, dots, screen) # 把所有的都画出来 调用draw方法 + pygame.display.flip() # 渲染 + pygame.time.delay(30) # 设置动画的时间延迟 + + control_my_ball(host_ball) # 移动我的球 + enemy_move(balls, host_ball) # 敌人的球随机运动 + eat_each_other(host_ball, balls, dots) # 吃球 调用eat_ball方法 + i00 += 1 + if np.mod(i00, 50) == 0: + print(host_ball.value) + + +if __name__ == '__main__': + main() diff --git a/language_learning/2019.10.27_1_stock_date_from_tushare/stock_date_from_tushare.py b/language_learning/2019.10.27_1_stock_date_from_tushare/stock_date_from_tushare.py new file mode 100755 index 0000000..2022ff4 --- /dev/null +++ b/language_learning/2019.10.27_1_stock_date_from_tushare/stock_date_from_tushare.py @@ -0,0 +1,106 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/706 +""" + +import numpy as np +import time +import matplotlib.pyplot as plt +import tushare as ts + + +def main(): + start_clock = time.perf_counter() + pro = ts.pro_api('到官网上注册,寻找Token填在这里!') + print('\n我的策略:见好就收,遇低抄底。\n' + ' 【卖出】买入后涨了5%就卖出\n' + ' 【买入】卖出后跌了5%就买入\n' + '注:第一天必须买进,最后一天前必须卖出(为了与不操作的做对比)\n') + number = 1 + for i in range(number): + data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date') # 所有股票列表 + # print(data.columns) # 查看该数据的表头 + # print(data) # 3688多行的股票数据 + i = 1 # 查看第二行数据“万科A”股 + ts_code = data.values[i, 0] # 股票代码 + stock = data.values[i, 2] # 股票名称 + industry = data.values[i, 4] # 属于哪个行业 + start_date = '20110101' # 开始时间 + end_date = '20191027' # 结束时间 + df = pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date) # 查看该股票的日线数据 + # print(df.columns) # 查看该数据的表头 + # print(df) # 查看该股票的日线数据 + close = np.array(list(reversed(df.values[:, 5]))) # 提取出收盘价,并按时间顺序排列,从过去到现在 + pct_chg = np.array(list(reversed(df.values[:, 8]))) # 提取出涨跌幅,并按时间顺序排列,从过去到现在 + # print(df.columns[5], '=', close, '\n') # 查看收盘价 + # print(df.columns[8], '=', pct_chg, '\n') # 查看涨跌幅 + profit, profit_no_operation, times, invest_money, buy_time_all, sell_time_all = back_test(close.shape[0], close, pct_chg) + # 调用回测函数,返回了“利润,未操作的利润, 按该策略操作了几次, 总投资金额, 按该策略买的时间, 按该策略卖的时间”的值 + print('\n------股票:', stock, ts_code, industry, '[买入市值=%7.2f' % invest_money, ']------') + print('回测时间段:', start_date, '-', end_date) + print('操作后利润= %6.2f' % profit, ' 买入(卖出)次数=', times, ' ') + print('不操作利润= %6.2f' % profit_no_operation, '(第一天买入,最后一天卖出,中间未操作)') + end_clock = time.perf_counter() + print('CPU执行时间=', end_clock - start_clock, 's') + plt.figure(1) + plt.title('Stock Code: '+ts_code+' (red point: buy, green point: sell)') + plt.grid() + plt.plot(range(close.shape[0]), close, '-') + for i in buy_time_all: + plt.plot(i, close[int(i)], 'or', markersize=13) # 红色是买进的点 + for i in sell_time_all: + plt.plot(i, close[int(i)], 'dg', markersize=13) # 绿色是卖出的点 + plt.show() + + +def back_test(days, close, pct_chg, money_in=10000): # 定义该策略的回测效果(按旧数据检查该策略是否有效) + money_in_amount = int(money_in/close[0]) # 投资金额换算成股票股数 + invest_money = close[0]*money_in_amount # 实际买了股票的金额 + profit_no_operation = (close[close.shape[0]-1]-close[0])*money_in_amount # 不操作的利润 + position = -1 # 买入还是卖出的状态,默认卖出 + total_profit = 0 + times = 0 + current_buy_pct = -999 + current_sell_pct = 999 + buy_time_all = np.array([]) + sell_time_all = np.array([]) + for i in range(days): # 总天数 + if i == 0: # 第一天,满仓买买买!为了和不操作的对比,第一天就要买入。 + buy_time = i # 买入时间 + buy_time_all = np.append(buy_time_all, [buy_time], axis=0) # 买入时间存档 + position = 1 # 标记为买入状态 + print('------------------第', buy_time, '天买进-------------') + else: + profit = 0 + if position == 1: # 买入状态 + current_buy_pct = (close[i]-close[buy_time])/close[buy_time]*100 # 买入后的涨跌情况 + # print('当前买进后的涨跌情况:第', i, '天=', current_buy_pct) + if position == 0: # 卖出状态 + current_sell_pct = (close[i]-close[sell_time])/close[sell_time]*100 # 卖出后的涨跌情况 + + if current_sell_pct < -5 and position == 0: # 卖出状态,且卖出后跌了有3%,这时候买入 + buy_time = i # 买入时间 + buy_time_all = np.append(buy_time_all, [buy_time], axis=0) # 买入时间存档 + print('------------------第', buy_time, '天买进-------------') + position = 1 # 标记为买入状态 + continue + + if current_buy_pct > 5 and position == 1: # 买入状态,且买入后涨了有3%,这时候卖出 + sell_time = i # 卖出时间 + sell_time_all = np.append(sell_time_all, [sell_time], axis=0) # 卖出时间存档 + print('----------第', sell_time, '天卖出,持有天数:', sell_time-buy_time, '--------------\n') + position = 0 # 标记为卖出状态 + profit = close[sell_time]-close[buy_time] # 赚取利润 + times = times + 1 # 买入(卖出)次数加1 + total_profit = total_profit + profit*money_in_amount # 计算总利润 + if position == 1: # 最后一天如果是买入状态,则卖出 + profit = close[i]-close[buy_time] # 赚取利润 + total_profit = total_profit + profit # 计算总利润 + times = times + 1 # 买入(卖出)次数加1 + print('--------------第', i, '天(最后一天)卖出,持有天数:', sell_time-buy_time, '--------------\n') + sell_time_all = np.append(sell_time_all, [i], axis=0) # 卖出时间存档 + return total_profit, profit_no_operation, times, invest_money, buy_time_all, sell_time_all + + +if __name__ == '__main__': + main() diff --git a/language_learning/2019.10.29_matlab_example/matlab_example.m b/language_learning/2019.10.29_matlab_example/matlab_example.m new file mode 100755 index 0000000..9d4d173 --- /dev/null +++ b/language_learning/2019.10.29_matlab_example/matlab_example.m @@ -0,0 +1,41 @@ +% This code is supported by the website: https://www.guanjihuan.com +% The newest version of this code is on the web page: https://www.guanjihuan.com/archives/766 + + +%在matlab里加上百分号“%”是注释。 +%快捷键:选中按ctrl+R为注释,选中按ctrl+T为取消注释, +clc; %clc有窗口清空的效果,一般都用上 +clear all; %clear all可以清空所有变量,一般都用上 +clf; %clf为清空输出的图片内容,在画图的时候最好添加上 + +aa=1 %没加分号“;”,默认打印输出 +bb=2; %加了分号“;”,即不打印输出 +cc1=zeros(2,3) %零矩阵用zeros() +cc2=eye(3,3) %单位矩阵 + +%矩阵乘积 +matrix1=[3,3;3,3] %里面分号代表矩阵换一行。下标是从1开始记。 +matrix2=[2,0;0,2] +matrix_product_1=matrix1*matrix2 % *是正常的矩阵乘积 +matrix_product_2=matrix1.*matrix2 % .*是矩阵每个元素对应相乘 + +%循环 +for i0=1:0.5:2 %循环内容为for到end。a:b:c代表最小为a,最大为c,步长为b + for_result=i0+1i %i在matlab中代表虚数,所以起变量名最好不要用i。要输出内容,后面不加分号即可 +end + +%判断 +if aa~=1 %在matlab中,~=代表不等于,==代表等于 + dd=100 +else + dd=300 +end + +matrix=[2,3;5,7] +%求本征矢和本征值 +[V,D]=eig(matrix) %在matlab中,V的列向量是本征矢,注意是列。D的对角上是对应本征值。 +%求逆 +inv1=inv(matrix) %求逆 +inv2=matrix^-1 %求逆也可以这样写 +%画图 +plot([0:20],[10:-1:-10],'-o') %更多画图技巧可参考官方文档或网上资料 \ No newline at end of file diff --git a/language_learning/2019.10.31_0_fortran_example/Console1.f90 b/language_learning/2019.10.31_0_fortran_example/Console1.f90 new file mode 100755 index 0000000..b6955ed --- /dev/null +++ b/language_learning/2019.10.31_0_fortran_example/Console1.f90 @@ -0,0 +1,164 @@ +! This code is supported by the website: https://www.guanjihuan.com +! The newest version of this code is on the web page: https://www.guanjihuan.com/archives/762 + + +module global ! module是用来封装程序模块的,把相关功能的变量和函数封装在一起。一般来说,可以不设置全局变量,把这些变量写在module里,在需要用的地方用use调用即可。 + implicit none + double precision sqrt3,Pi + parameter(sqrt3=1.7320508075688773d0,Pi=3.14159265358979324d0) ! parameter代表不能改的常数 + end module global + + +program main !主函数用program开始,用end program结束。在Fortran里不区分大小写。用感叹号!来做注释 +use global +use f95_precision !这个还不知道什么时候用上,这里注释掉也可正常运行。 +use blas95 ! 里面包含了矩阵相乘的gemm()等 +use lapack95 !里面包括了矩阵求逆的GETRF,GETRI和求本征矢和本征矢的GEEV等 +implicit none ! implicit是用来设置默认类型,即根据变量名称的第一个字母来决定变量的类型。implicit none是关闭默认类型功能,所有变量要先声明 + + +integer i,j,info,index1(2) ! 定义整型 +double precision a(2,2),b(2,2),c(2,2),& ! 比较长的语句可以用&换行。在续行的开始位置可加&号,也可不加。 + x1, x2, result_1, result_2, fun1 !定义双精度浮点数 +complex*16 dd(2,2), eigenvalues(2) !定义复数 +complex*16, allocatable:: eigenvectors(:,:) ! 定义动态分配的变量 !这里的两个冒号::是必须要的。其他的可加可不加。 +character(len=15) hello, number ! 定义字符串,len是规定长度,如果不写,只会给一个字符的空间 +allocate(eigenvectors(2,2)) ! 分配空间 + + +write(*,*) '----输出----' +hello='hello world' +write(*,*) hello ! 第一个代表输出的设备,*代表屏幕。第二个是输出的格式,*代表默认。 +write(number,'(f7.3)') pi ! 用write可以把数字类型转成字符类型。'(f7.3)'是输出浮点数的格式,如果用*来代替,字符串的长度需要够长才行。整型格式用类似'(i3)'这样 +write(*,*) '数字转成字符串后再输出:', number +write(*,"(a,18x)",advance="no") hello ! advance='no'代表不换行,在有advance的时候,必须格式化输出,否则报错。'(a)'按照字符型变量的实际长度读取,这里也可以写a15或者其他。'(10x)'代表空格 +write(*,*) number,'这是不换行输出测试' +write(*,"('一些固定文字也可以写在这里面', a, a,//)") hello, number !字符串也可以直接写在"()"里面。里面有引号,外面要用上双引号才行,不然会报错。 +!'(a)'按照字符型变量的实际长度读取,也可以写a15或者其他。这里'(/)'代表再换一次行。一个斜杠换一个。 + + +write(*,*) '----写入文件----' +open(unit=10,file='learn-fortran-test.txt') ! 打开文件用open +write(10,*) hello, number +close(10) ! 关闭文件用close +write(*,*) '' + +write(*,*) '----矩阵乘积----' +a(1,1)=2;a(1,2)=5;a(2,1)=3;a(2,2)=2 ! 两个语句写在同一行是可以的,要用分号隔开 +b(1,1)=3;b(2,2)=3 +write(*,*) '矩阵直接默认输出,是按列的顺序一个个输出' +write(*,*) 'a=' +write(*,*) a +write(*,*) '矩阵格式化输出' +write(*,*) 'a=' +do i=1,2 + do j=1,2 + write(*,'(f10.4)',advance='no') a(i,j) !内循环为列的指标 + enddo + write(*,*) '' +enddo +write(*,*) 'b=' +do i=1,2 + do j=1,2 + write(*,'(f10.4)',advance='no') b(i,j) !内循环为列的指标 + enddo + write(*,*) '' +enddo +call gemm(a,b,c) ! 矩阵乘积用call gemm() +write(*,*) '矩阵乘积:c=a*b=' +do i=1,2 + do j=1,2 + write(*,'(f10.4)',advance='no') c(i,j) !内循环为列的指标 + enddo + write(*,*) '' +enddo +write(*,*) '' + + +write(*,*) '----矩阵求逆----' +call getrf(a,index1,info); call getri(a,index1,info) !getrf和getri要配合起来使用求逆。 +! info是需定义为整型。If info = 0, the execution is successful. +! 上面index1是在getrf产生,在getri里输入。index1也是需要定义为整型,而且是一维数组,数组长度一般为矩阵的维度。 +! 这时候a不再是原来的矩阵了,而是求逆后的矩阵。 +do i=1,2 + do j=1,2 + write(*,'(f10.4)',advance='no') a(i,j) !内循环为列的指标 + enddo + write(*,*) '' +enddo + + +write(*,*) '----复数矩阵----' +dd(1,1)=(1.d0, 0.d0) +dd(1,2)=(7.d0, 0.d0) +dd(2,1)=(3.d0, 0.d0) +dd(2,2)=(2.d0, 0.d0) +do i=1,2 + do j=1,2 + write(*,"(f10.4, '+1i*',f7.4)",advance='no') dd(i,j) !内循环为列的指标 + enddo + write(*,*) '' +enddo +write(*,*) '' + + +write(*,*) '----矩阵本征矢和本征值----' +call geev(A=dd, W=eigenvalues, VR=eigenvectors, INFO=info) +! 这里A矩阵最好用上复数,W是本征值一维数组,VR是本征矢二维数组,都是复数。INFO是整数。 +! 注意求完本征值后,dd的值会发生改变,不再是原来的了! +write(*,*) 'eigenvectors:' +do i=1,2 + do j=1,2 + write(*,"(f10.4, '+1i*',f7.4)",advance='no') eigenvectors(i,j) !内循环为列的指标。输出结果列向量为特征向量。 + enddo + write(*,*) '' +enddo +write(*,*) 'eigenvalues:' +do i=1,2 + write(*,"(f10.4, '+1i*',f7.4)",advance='no') eigenvalues(i) +enddo +write(*,*) '' +deallocate(eigenvectors) ! 释放动态变量的空间 + + +write(*,*) '' ! 输出空一行 +write(*,*) '----循环加判断----' +do i=1,5 ! 循环用do到enddo + if (mod(i,2)==0) then ! 判断用if()then + write(*,*) '我是偶数', i + else if (i==3) then + write(*,*) '我是第3个数字,也是奇数' + else + write(*,*) '我是奇数', i + endif +enddo +write(*,*) '' + + +call sub1(2.d0, 3.d0, result_1, result_2) ! 这里要写成2.d0或者2.0d0表示双精度,因为子程序规定该参数为双精度。写成2或者2.0都会报错。 +write(*,*) '调用子程序,求和:',result_1 +write(*,*) '调用子程序,乘积:',result_2 +write(*,*) '使用函数,返回减法结果:', fun1(2.d0, 3.d0) +write(*,*) '' + + +end program + + + +subroutine sub1(x1,x2,y1,y2) !子程序。输入输出都在括号里面,用call调用。 +double precision,intent(in):: x1, x2 ! 这里的两个冒号::是必须要的。 +double precision,intent(out):: y1, y2 +! intent(in) 表示这个参数是输入的;intent(out) 表示参数是输出的;intent(inout)表示这个参数同时用于两个方向的数据传递; +! intent()不是必须的,但最好加上,因为可读性比较强,知道哪些是输入,哪些是输出。而且intent(in)是不能赋值更改的,会提示错误,这样可以防止一些错误。 +y1=x1+x2 +y2=x1*x2 +end subroutine + + + +function fun1(x1,x2) ! 函数。函数只能返回一个数值,不能多个。而子程序可以返回多个,所以一般用子程序subroutine +double precision x1,x2,fun1 ! 要对函数名(或返回变量)定义 +fun1=x1-x2 ! 返回变量要和函数名一样 +return ! 这里的return也可以不写。写的作用是直接返回值,而不运行后面的代码。一般会跟if配合用。 +end function ! 也可以直接写end,不会报错。但最好把后面的也带上,看起来比较清晰点。 \ No newline at end of file diff --git a/language_learning/2019.10.31_1_parallel_calculations_with_OpenMP/Console1.f90 b/language_learning/2019.10.31_1_parallel_calculations_with_OpenMP/Console1.f90 new file mode 100755 index 0000000..7ae9154 --- /dev/null +++ b/language_learning/2019.10.31_1_parallel_calculations_with_OpenMP/Console1.f90 @@ -0,0 +1,78 @@ +! This code is supported by the website: https://www.guanjihuan.com +! The newest version of this code is on the web page: https://www.guanjihuan.com/archives/764 + + +program hello_open_mp + use omp_lib !这里也可以写成 include 'omp_lib.h' ,两者调用方式均可 + integer mcpu,tid,total,N,i,j,loop + double precision starttime, endtime, time,result_0 + double precision, allocatable:: T(:) + N=5 ! 用于do并行 + loop=1000000000 !如果要测试并行和串行运算时间,可以加大loop值 + allocate(T(N)) + + + !call OMP_SET_NUM_THREADS(2) !人为设置线程个数,可以取消注释看效果 + total=OMP_GET_NUM_PROCS() ! 获取计算机系统的处理器数量 + print '(a,i2)', '计算机处理器数量:' , total !也可以用write(*,'(a,i2)')来输出 + print '(a)', '-----在并行之前-----' + tid=OMP_GET_THREAD_NUM() !获取当前线程的线程号 + mcpu=OMP_GET_NUM_THREADS() !获取总的线程数 + print '(a,i2,a,i2)', '当前线程号:',tid,';总的线程数:', mcpu + print * !代表换行 + + + print'(a)','-----第一部分程序开始并行-----' + !$OMP PARALLEL DEFAULT(PRIVATE) ! 这里用的是DEFAULT(PRIVATE) + tid=OMP_GET_THREAD_NUM() !获取当前线程的线程号 + mcpu=OMP_GET_NUM_THREADS() !获取总的线程数 + print '(a,i2,a,i2)', '当前线程号:',tid,';总的线程数:', mcpu + !$OMP END PARALLEL + + + print * !代表换行 + print'(a)','-----第二部分程序开始并行-----' + starttime=OMP_GET_WTIME() !获取开始时间 + !$OMP PARALLEL DO DEFAULT(PRIVATE) SHARED(T,N,loop) ! 默认私有变量,把需要的参数以及各节点计算结果的存放器作为共享变量。 + do i=1,N !这里放上do循环体。是多个样品。 + result_0=0 + tid=OMP_GET_THREAD_NUM() !获取当前线程的线程号 + mcpu=OMP_GET_NUM_THREADS() !获取总的线程数 + do j=1,loop !这代表我们要做的计算~ + result_0 = result_0+1 !这代表我们要做的计算~ + enddo !这代表我们要做的计算~ + T(i) = result_0-loop+i !将各个线程的计算结果保存到公共变量中去。 + !这里i代表各个循环的参数,之后如果有需要可以根据参数再整理数据。 + print '(a,i2, a, f10.4,a,i2,a,i2 )', 'T(',i,')=', T(i) , ' 来源于线程号',tid,';总的线程数:', mcpu + enddo + !$OMP END PARALLEL DO !并行结束 + endtime=OMP_GET_WTIME() !获取结束时间 + time=endtime-starttime !总运行时间 + print '(a, f13.5)' , '第二部分程序按并行计算所用的时间:', time + + + print * !代表换行 + print'(a)','-----第二部分程序按串行的计算-----' + starttime=OMP_GET_WTIME() !获取开始时间 + do i=1,N + result_0=0 + tid=OMP_GET_THREAD_NUM() !获取当前线程的线程号 + mcpu=OMP_GET_NUM_THREADS() !获取总的线程数 + do j=1,loop + result_0 = result_0+1 + enddo + T(i) = result_0-loop+i + print '(a,i2, a, f10.4,a,i2,a,i2 )', 'T(' ,i,')=', T(i) , ' 来源于线程号',tid,';总的线程数:', mcpu + enddo + endtime=OMP_GET_WTIME() !获取结束时间 + time=endtime-starttime !总运行时间 + print '(a, f13.5)' , '第二部分程序按串行计算所用的时间:', time + print * !代表换行 + + + tid=OMP_GET_THREAD_NUM() !获取当前线程的线程号 + mcpu=OMP_GET_NUM_THREADS() !获取总的线程数 + print '(a,i5,a,i5)', '当前线程号:',tid,';总的线程数:', mcpu + print * !代表换行 +end program hello_open_mp ! 这里可以写成end, 也可以写成end program,都可以。 + \ No newline at end of file diff --git a/language_learning/2019.11.16_markdown_example/markdown_example.md b/language_learning/2019.11.16_markdown_example/markdown_example.md new file mode 100755 index 0000000..466662a --- /dev/null +++ b/language_learning/2019.11.16_markdown_example/markdown_example.md @@ -0,0 +1,33 @@ +# 一级标题 +## 二级标题 +### 三级标题 +#### 四级标题 + +有序列表:数字加一个点 +1. 列表内容 +2. 列表内容 +3. 列表内容 + +无序列表:用 + - * 任何一种都可以(为了不和其他记号重复,个人倾向于用+) ++ 列表内容 + + 嵌套前面加几个空格(为了保险起见,个人倾向于用四个空格) ++ 列表内容 + + 列表嵌套 + + 列表嵌套 + + 列表嵌套 + +分割线:三个或者三个以上的 - 或 *(为了不和其他记号重复,个人倾向于用---) + +---- + +*倾斜:前后一个星号* + +**加粗:前后两个星号** + +***斜体加粗:前后三个星号*** + +| 表头 | 表头 | 表头 | +| --- | --- | --- | +| 内容 | 内容 | 内容 | +| 内容 | 内容 | 内容 | +| 内容 | 内容 | 内容 | diff --git a/language_learning/2019.12.04_latex_example/basic_structure.tex b/language_learning/2019.12.04_latex_example/basic_structure.tex new file mode 100755 index 0000000..ddf11ad --- /dev/null +++ b/language_learning/2019.12.04_latex_example/basic_structure.tex @@ -0,0 +1,6 @@ +\documentclass{article} %文档类声明 +%导言区(文档类声明和正文间的是导言区) +\begin{document} %正文开始 + Hello, world! %正文 +\end{document} %正文结束 +\end{document} \ No newline at end of file diff --git a/language_learning/2019.12.04_latex_example/simple_example.tex b/language_learning/2019.12.04_latex_example/simple_example.tex new file mode 100755 index 0000000..5e1f4cd --- /dev/null +++ b/language_learning/2019.12.04_latex_example/simple_example.tex @@ -0,0 +1,18 @@ +\documentclass{article} %文档类声明 +\usepackage{ctex} %一个支持中文宏包,如果不用中文无法显示 + + +\begin{document} %正文 + \title{这是一个标题} %标题 + \author{作者名字} %作者 + \date{} %\maketitle默认会加上当前时间,用\date{},空着内容可以取消时间的显示 + \maketitle %加了这个,标题、作者等信息才会显示 + \section{节} + \subsection{小节} + \subsubsection{子小节} + Hello, world! %下面空一行代表换行 + \textbf{用\textbackslash textbf\{\}可以加粗文本} %\textbf{}可以加粗文本 + \section{节} + \part{} + \part{} +\end{document} \ No newline at end of file diff --git a/language_learning/2019.12.05_beamer_as_slides/1.jpg b/language_learning/2019.12.05_beamer_as_slides/1.jpg new file mode 100755 index 0000000000000000000000000000000000000000..6ecbf0f359d103a92f70c8c48269019ad9e47f75 GIT binary patch literal 18074 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.*
  • Received', html, re.S)[0] + word_list = abstract.split(' ') + word_list_for_one_href = [] + for word in word_list: + if 1<', word)==None: + if word not in word_list_for_one_href: # 每篇文章的某个词汇只统计一次 + word_list_for_one_href.append(word) + f.write(str(word)+' ') +f.close() + + +""" +运行一次后,以上的代码可以注释,不需要多次访问网址。 +以下代码调用的是上面代码生成的txt文件,可个性选择忽略的词汇,多次运行调试。 +""" + + +# 个性选择忽略的词汇(根据需要增删) +ignore = [] +year = datetime.datetime.now().year +month = datetime.datetime.now().month +day = datetime.datetime.now().day +with open(str(year)+'.'+str(month).rjust(2,'0')+'.'+str(day).rjust(2,'0')+'_word_list.txt', 'r', encoding='UTF-8') as f: + word_list = f.read().split(' ') +effective_words = [] +for word in word_list: + if 1.*
  • Received', html, re.S)[0] + word_list = abstract.split(' ') + word_list_for_one_href = [] + for word in word_list: + if 1', word)==None and re.search('href', word)==None: + if word not in word_list_for_one_href: + word_list_for_one_href.append(word) + all_word_list.append(word) + most_common_words = Counter(all_word_list).most_common(num) + f.write(str(year)+'.'+str(month).rjust(2,'0')+'.'+str(day).rjust(2,'0')+'|number_of_papers='+str(len(match_href))) + for word in most_common_words: + f.write('|'+str(word)) + f.write('\n\n') + f.write(content_before) + f.close() \ No newline at end of file