Skip to content

Code tidying #907

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open

Code tidying #907

wants to merge 15 commits into from

Conversation

XZTian64
Copy link
Collaborator

@XZTian64 XZTian64 commented Jun 29, 2025

User description

Description

This is the latest progress of code tidying.

Fixes #845

Type of change

  • Fixed most of the warnings during ./mfc.sh build --debug

A few issues remaining

  • Several unused functions.
  • A few unused dummy variables. They can be resolved by creating local copies to force usage, but this may reduce runtime efficiency unnecessarily.

For example:

    subroutine s_convert_primitive_to_flux_variables(qK_prim_vf, &
                                                     FK_vf, &
                                                     FK_src_vf, &
                                                     is1, is2, is3, s2b, s3b)

        integer, intent(in) :: s2b, s3b
        real(wp), dimension(0:, s2b:, s3b:, 1:), intent(in) :: qK_prim_vf
        ......
#ifdef MFC_SIMULATION
        !$acc loop seq
        do i = 1, contxe
            alpha_rho_K(i) = qK_prim_vf(j, k, l, i)
        end do

Adding a local variable only to silence a warning:

  real(wp), allocatable :: qK_prim_vf_loc(:,:,:,:)
  qK_prim_vf_loc = qK_prim_vf

which I feel is not necessary.

  • Unused loop variables (i, j, k) in /pre_process/m_patches.fpp. They appear unused but are required by the @:analytical() macro during ./mfc.sh test.
  • Several rank mismatch issues in /post_process/m_data_output.fpp. This relates to silo package, wondering if this required to be fixed.
    An example is attached:
err = DBADDIOPT(optlist, DBOPT_LO_OFFSET, lo_offset)    
      |                                                                 ! rank-1 array
......
err = DBADDIOPT(optlist, DBOPT_EXTENTS_SIZE, 2)            
      |                                                                 ! scalar
Warning: Rank mismatch between actual argument at (1) and actual argument at (2) (scalar and rank-1)

PR Type

Bug fix, Enhancement


Description

  • Fixed compiler warnings and unused variable declarations

  • Corrected MPI data type mismatches and function signatures

  • Improved precision handling for floating point comparisons

  • Removed redundant variable allocations and declarations


Diagram Walkthrough

flowchart LR
  A["Unused Variables"] --> B["Remove/Guard Declarations"]
  C["MPI Type Mismatches"] --> D["Fix Data Types"]
  E["Function Signatures"] --> F["Correct Parameter Order"]
  G["Precision Issues"] --> H["Add Precision-Aware Defaults"]
  B --> I["Cleaner Code"]
  D --> I
  F --> I
  H --> I
Loading

File Walkthrough

Relevant files

@XZTian64 XZTian64 requested a review from a team as a code owner June 29, 2025 00:36
Copy link

qodo-merge-pro bot commented Jun 29, 2025

PR Reviewer Guide 🔍

(Review updated until commit caa51db)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

845 - PR Code Verified

Compliant requirements:

• Remove unused variables, subroutines, dummy variables, etc.
• Handle different compilation units marked by #ifdef
• Work around warnings by enclosing offending variables with corresponding #ifdef and #endif tags
• Address warnings that persist due to different compilation contexts

Requires further human verification:

• Fix compiler warnings like unused dummy variables and such - requires compilation testing to verify all warnings are resolved

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Code Duplication

Multiple instances of similar variable initialization and Re_K assignment patterns are repeated across different functions. Consider extracting common initialization logic into a helper subroutine to reduce duplication.

! Initiate the variables
Y_rs(:) = rhoYks(:)/rho
e_Per_Kg = energy/rho
Pdyn_Per_Kg = dyn_p/rho
E_e = 0._wp
Possible Issue

The hardcoded constants alpha_mp and beta_mp were removed but replaced with variables 'alpha' and 'beta' that may not be defined in scope. This could cause compilation errors or undefined behavior.

           - v_rs_ws(j, k, l, i))*alpha

vL_MD = (v_rs_ws(j, k, l, i) &
         + v_rs_ws(j - 1, k, l, i) &
         - d_MD)*5.e-1_wp

vL_LC = v_rs_ws(j, k, l, i) &
        - (v_rs_ws(j + 1, k, l, i) &
           - v_rs_ws(j, k, l, i))*5.e-1_wp + beta*d_LC
Logic Change

The creation of local copies of alpha_K and alpha_rho_K arrays and their usage instead of the original parameters changes the function behavior. This may impact performance and could introduce subtle bugs if the local copies are not properly synchronized.

        real(wp), dimension(num_fluids) :: alpha_K_local, alpha_rho_K_local !<
        real(wp), dimension(2), intent(out) :: Re_K
#ifdef MFC_SIMULATION
        integer :: i, j !< Generic loop iterators
#endif
        ! Initiate the variables
        rho_K = 0._wp
        gamma_K = 0._wp
        pi_inf_K = 0._wp
        qv_K = 0._wp
        Re_K(:) = dflt_real
        alpha_K_local(:) = alpha_K(:)
        alpha_rho_K_local(:) = alpha_rho_K(:)

Copy link

qodo-merge-pro bot commented Jun 29, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Use correct variable for allocation
Suggestion Impact:The commit directly implements the suggested fix by replacing fd_number_in with fd_number in the allocate statement, fixing the bug with optional parameter handling

code diff:

-        allocate (fd_coeff_s(-fd_number_in:fd_number_in, lb:lE))
+        allocate (fd_coeff_s(-fd_number:fd_number, lb:lE))

The variable fd_number_in is used in the allocation but should be replaced with
the local variable fd_number that handles the optional parameter logic.

src/common/m_finite_differences.fpp [100-101]

 if (allocated(fd_coeff_s)) deallocate (fd_coeff_s)
-        allocate (fd_coeff_s(-fd_number_in:fd_number_in, lb:lE))
+        allocate (fd_coeff_s(-fd_number:fd_number, lb:lE))
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug. The code uses an optional argument fd_number_in directly in an allocate statement. If fd_number_in is not provided, this will lead to a runtime error. The fix correctly proposes using the local variable fd_number, which is designed to handle the optional logic.

High
Fix preprocessor directive syntax
Suggestion Impact:The suggestion was directly implemented - both #endif directives in the file had their macro names removed to follow standard preprocessor syntax

code diff:

-#endif MFC_PRE_PROCESS
+#endif
 
         @:PROHIBIT(surface_tension .and. sigma < 0._wp, &
             "sigma must be greater than or equal to zero")
@@ -340,7 +340,7 @@
             @:PROHIBIT(surface_tension .and. f_is_default(patch_icpp(i)%cf_val), &
                 "patch_icpp(i)%cf_val must be set if surface_tension is enabled")
         end do
-#endif MFC_PRE_PROCESS
+#endif

The #endif directive should not include the macro name. In Fortran preprocessor
directives, #endif should stand alone without the condition name.

src/common/m_checker_common.fpp [319-321]

 #ifdef MFC_PRE_PROCESS
         integer :: i
-#endif MFC_PRE_PROCESS
+#endif
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly points out that the standard preprocessor syntax for #endif does not include the macro name. While some compilers might tolerate this, it's non-standard and harms portability. The fix improves code correctness and style.

Low
  • Update

Copy link

codecov bot commented Jun 29, 2025

Codecov Report

Attention: Patch coverage is 55.22388% with 30 lines in your changes missing coverage. Please review.

Project coverage is 44.03%. Comparing base (c933e72) to head (caa51db).

Files with missing lines Patch % Lines
src/common/m_variables_conversion.fpp 48.14% 11 Missing and 3 partials ⚠️
src/common/m_nvtx.f90 0.00% 2 Missing and 1 partial ⚠️
src/simulation/m_hyperelastic.fpp 0.00% 3 Missing ⚠️
src/common/m_finite_differences.fpp 33.33% 1 Missing and 1 partial ⚠️
src/pre_process/m_patches.fpp 50.00% 2 Missing ⚠️
src/simulation/m_derived_variables.fpp 33.33% 2 Missing ⚠️
src/common/m_helper_basic.fpp 50.00% 1 Missing ⚠️
src/common/m_phase_change.fpp 0.00% 1 Missing ⚠️
src/simulation/m_data_output.fpp 66.66% 1 Missing ⚠️
src/simulation/m_mhd.fpp 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #907      +/-   ##
==========================================
+ Coverage   44.02%   44.03%   +0.01%     
==========================================
  Files          69       69              
  Lines       19625    19644      +19     
  Branches     2430     2436       +6     
==========================================
+ Hits         8640     8651      +11     
- Misses       9484     9488       +4     
- Partials     1501     1505       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sbryngelson
Copy link
Member

Failed on AMD GPU hardware with Cray compilers because:

ftn-3175 ftn: ERROR S_CONVERT_CONSERVATIVE_TO_PRIMITIVE_VARIABLES, File = ../../../lustre/orion/cfd154/scratch/sbryngelson/actions-runner-1/_work/MFC/MFC/src/common/m_variables_conversion.fpp, Line = 905, Column = 34 
  s_convert_species_to_mixture_variables_acc was not inlined.  Reveal autothread loops must flatten.


ftn-3175 ftn: ERROR S_CONVERT_PRIMITIVE_TO_FLUX_VARIABLES, File = ../../../lustre/orion/cfd154/scratch/sbryngelson/actions-runner-1/_work/MFC/MFC/src/common/m_variables_conversion.fpp, Line = 1516, Column = 30 
  s_convert_species_to_mixture_variables_acc was not inlined.  Reveal autothread loops must flatten.

Cray Fortran : 1834 source lines
Cray Fortran : 2 errors, 0 warnings, 0 other messages, 0 ansi
Cray Fortran : "explain ftn-message number" gives more information about each message.
ftn-5025 ftn: WARNING in command line
   The lister is using the source file "../../../lustre/orion/cfd154/scratch/sbryngelson/actions-runner-1/_work/MFC/MFC/src/common/m_variables_conversion.fpp", rather than the specified source file "/lustre/orion/cfd154/scratch/sbryngelson/actions-runner-1/_work/MFC/MFC/build/staging/4fdcb09442/fypp/simulation/m_variables_conversion.fpp.f90".

gmake[3]: *** [CMakeFiles/simulation.dir/build.make:993: CMakeFiles/simulation.dir/fypp/simulation/m_variables_conversion.fpp.f90.o] Error 1
gmake[3]: *** Waiting for unfinished jobs....
ftn-5025 ftn: WARNING in command line
   The lister is using the source file "../../../lustre/orion/cfd154/scratch/sbryngelson/actions-runner-1/_work/MFC/MFC/src/common/m_boundary_common.fpp", rather than the specified source file "/lustre/orion/cfd154/scratch/sbryngelson/actions-runner-1/_work/MFC/MFC/build/staging/4fdcb09442/fypp/simulation/m_boundary_common.fpp.f90".

gmake[2]: *** [CMakeFiles/Makefile2:83: CMakeFiles/simulation.dir/all] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:90: CMakeFiles/simulation.dir/rule] Error 2
gmake: *** [Makefile:170: simulation] Error 2
 

Error: Failed to build the simulation target.

@sbryngelson
Copy link
Member

I will review this soon. It's hard to review because I want to be sure the tests caught all the ways this could have possibly broken something.

call nvtxRangePush(tempName)
else
event%color = col(mod(id, 7) + 1)
if (present(id)) then
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this work, too? you need to run nsys with cpu and gpu modes to find out

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is one output with --nsys and --gpu
Now that each row represent a specific NVTX range, I think this code works properly.

[3/8] Executing 'nvtx_sum' stats report
 Time (%)  Total Time (ns)  Instances     Avg (ns)         Med (ns)        Min (ns)       Max (ns)     StdDev (ns)   Style           Range        
 --------  ---------------  ---------  ---------------  ---------------  -------------  -------------  -----------  -------  ---------------------
     22.5    2,208,358,145          1  2,208,358,145.0  2,208,358,145.0  2,208,358,145  2,208,358,145          0.0  PushPop  SIMULATION-TIME-MARCH
     19.1    1,867,369,618          1  1,867,369,618.0  1,867,369,618.0  1,867,369,618  1,867,369,618          0.0  PushPop  INIT                 
     13.0    1,274,854,743          1  1,274,854,743.0  1,274,854,743.0  1,274,854,743  1,274,854,743          0.0  PushPop  INIT-MODULES         
     12.5    1,223,361,067         50     24,467,221.3     23,591,994.0     21,520,831     50,213,333  3,972,174.3  PushPop  TIMESTEP             
      8.3      817,515,022          1    817,515,022.0    817,515,022.0    817,515,022    817,515,022          0.0  PushPop  SAVE-DATA            
      6.5      637,690,738        150      4,251,271.6      4,070,501.5      3,991,106     27,681,810  1,927,606.5  PushPop  COMPUTE-RHS          
      6.0      591,356,493          1    591,356,493.0    591,356,493.0    591,356,493    591,356,493          0.0  PushPop  INIT-MPI             
      4.3      421,111,172          1    421,111,172.0    421,111,172.0    421,111,172    421,111,172          0.0  PushPop  MPI:MPI_Init         
      3.6      349,779,183        450        777,287.1        764,172.0        749,605      3,553,709    132,730.3  PushPop  RHS-ADVECTION-SRC    
      1.5      142,218,607        450        316,041.3        303,346.0        282,750      4,176,763    182,804.3  PushPop  RHS-WENO             
      0.8       81,742,288        450        181,649.5        165,865.5        160,829      6,887,448    316,954.3  PushPop  RHS-RIEMANN-SOLVER   
      0.7       66,194,030          1     66,194,030.0     66,194,030.0     66,194,030     66,194,030          0.0  PushPop  FINALIZE-MODULES     
      0.6       62,960,296          1     62,960,296.0     62,960,296.0     62,960,296     62,960,296          0.0  PushPop  MPI:MPI_Finalize     
      0.3       30,719,602        150        204,797.3        164,348.0        160,500      6,002,360    476,562.6  PushPop  RHS-COMMUNICATION    
      0.1       11,811,929        150         78,746.2         76,288.5         74,967        317,997     19,778.8  PushPop  RHS-ACOUSTIC-SRC     
      0.1       10,396,748        150         69,311.7         44,600.0         41,059      3,761,697    303,513.2  PushPop  RHS-CONVERT          
      0.0        1,134,973          1      1,134,973.0      1,134,973.0      1,134,973      1,134,973          0.0  PushPop  INIT-GPU-VARS        
      0.0          225,778        745            303.1            322.0            163          1,897        119.6  PushPop  MPI:MPI_Bcast        
      0.0          144,716        450            321.6            311.5            172            748         84.4  PushPop  RHS-HYPOELASTICITY   
      0.0          125,007        450            277.8            265.0            152            602         76.3  PushPop  RHS-MHD              
      0.0           75,393         51          1,478.3            838.0            721          7,647      1,806.1  PushPop  MPI:MPI_Barrier      
      0.0           72,677        200            363.4            326.0            164          5,742        391.1  PushPop  RHS-ELASTIC          

@@ -1261,9 +1261,6 @@ contains
!! Determines the amount of freedom available from utilizing a large
!! value for the local curvature. The default value for beta is 4/3.

real(wp), parameter :: alpha_mp = 2._wp
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do these not get used anywhere?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the subroutine, defined both alpha and alpha_mp with the same value, but only used the alpha_mp. They are literally the same, so I just removed the redundant one.

@sbryngelson sbryngelson marked this pull request as draft July 14, 2025 07:06
@sbryngelson
Copy link
Member

comments are unresolved and now there are merge conflicts

@sbryngelson
Copy link
Member

merge conflicts (probably due to my refactoring to get rid of masking parent variables)

@sbryngelson sbryngelson marked this pull request as ready for review July 23, 2025 13:42
@Copilot Copilot AI review requested due to automatic review settings July 23, 2025 13:42
@sbryngelson
Copy link
Member

please review the comments i left above 3 weeks ago. e.g., do these not get used anywhere?

Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR performs code tidying to fix compiler warnings in the MFC Fortran codebase, primarily by removing unused variables, correcting MPI data type declarations, and adding conditional compilation guards. The changes address various issues raised during debug builds while maintaining code functionality.

  • Remove unused variables, parameters, and dummy arguments throughout the codebase
  • Fix MPI data type declarations to use proper address kinds instead of regular integers
  • Add conditional compilation guards to prevent unused variable warnings
  • Correct parameter order in finite difference coefficient function calls

Reviewed Changes

Copilot reviewed 27 out of 27 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
m_weno.fpp Remove duplicate parameter declarations and use existing alpha/beta variables
m_time_steppers.fpp Comment out unused gradient magnitude variables
m_start_up.fpp Fix integer conversion and conditional variable declaration
m_riemann_solvers.fpp Remove unused xi_field variables from private clause
m_rhs.fpp Comment out unused gradient magnitude allocations
m_mpi_proxy.fpp Remove unused loop variables and communication flags
m_mhd.fpp Remove unused derivative arrays and fix function parameter order
m_hypoelastic.fpp Fix parameter order in finite difference function calls
m_hyperelastic.fpp Fix parameter order in finite difference function calls
m_fftw.fpp Add conditional compilation for OpenACC-specific variables
m_derived_variables.fpp Fix parameter order and GPU update device references
m_data_output.fpp Remove unused stability criterion variables and add directory handling
m_compute_cbc.fpp Remove unused loop variable
m_patches.fpp Remove unused parameters from airfoil subroutines
m_compute_levelset.fpp Remove unused length_z variable
ExtrusionHardcodedIC.fpp Remove unused variables and improve floating-point comparisons
m_start_up.f90 Fix parameter order in finite difference function calls
m_data_input.f90 Remove unused MPI offset and loop variables
m_variables_conversion.fpp Add conditional compilation guards and improve variable initialization
m_phase_change.fpp Remove unused parameter from relaxation solver
m_nvtx.f90 Fix variable scope and improve conditional compilation
m_mpi_common.fpp Initialize variables and add conditional guards for different compilation modes
m_helper_basic.fpp Improve precision-specific tolerance handling
m_finite_differences.fpp Fix parameter order and add optional parameter handling
m_checker_common.fpp Add conditional compilation guard for unused variable
m_boundary_common.fpp Fix MPI data types and remove unused variables

$:GPU_UPDATE(device='[fd_coeff_x]')

fd_order, fd_number)
$:GPU_UPDATE(device='[fd_coeff_z]')
Copy link
Preview

Copilot AI Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be updating fd_coeff_x, not fd_coeff_z. The variable being allocated is fd_coeff_x but the GPU update references fd_coeff_z.

Suggested change
$:GPU_UPDATE(device='[fd_coeff_z]')
$:GPU_UPDATE(device='[fd_coeff_x]')

Copilot uses AI. Check for mistakes.

fd_number, fd_order)
$:GPU_UPDATE(device='[fd_coeff_y]')
fd_order, fd_number)
$:GPU_UPDATE(device='[fd_coeff_z]')
Copy link
Preview

Copilot AI Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be updating fd_coeff_y, not fd_coeff_z. The variable being allocated is fd_coeff_y but the GPU update references fd_coeff_z.

Suggested change
$:GPU_UPDATE(device='[fd_coeff_z]')
$:GPU_UPDATE(device='[fd_coeff_y]')

Copilot uses AI. Check for mistakes.

Comment on lines +507 to +510
do i = 1, 2
Re_K(i) = dflt_real
end do
#ifdef MFC_SIMULATION
Copy link
Preview

Copilot AI Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop initializes Re_K(i) but Re_K is not declared in this scope without MFC_SIMULATION. The Re_K initialization should be moved inside the MFC_SIMULATION conditional block.

Suggested change
do i = 1, 2
Re_K(i) = dflt_real
end do
#ifdef MFC_SIMULATION
#ifdef MFC_SIMULATION
do i = 1, 2
Re_K(i) = dflt_real
end do

Copilot uses AI. Check for mistakes.

@@ -132,9 +134,17 @@ contains
real(wp) :: e_Per_Kg, Pdyn_Per_Kg
real(wp) :: T_guess
real(wp), dimension(1:num_species) :: Y_rs
#:if not chemistry
Copy link
Preview

Copilot AI Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use standard Fortran preprocessing directives. The Fypp syntax '#:if not chemistry' should follow the project's established preprocessing patterns. Based on other conditional blocks in the file, this should likely use #ifdef/#ifndef directives.

Copilot uses AI. Check for mistakes.

Copy link

PR Code Suggestions ✨

No code suggestions found for the PR.

@XZTian64
Copy link
Collaborator Author

please review the comments i left above 3 weeks ago. e.g., do these not get used anywhere?

Oh I forgot to submit the review changes. Those comments can be published now.

@sbryngelson
Copy link
Member

@wilfonba, can you look at this PR for anything suspicious? I have two (possibly unlikely) worries:

  1. This works for the tests, but there are some cases that this changes that the tests don't touch. Maybe a case where MPI uses more than 2 ranks, or uses 2 ranks on a cylindrical case, and this PR somehow breaks that.
  2. like 1., this goes down many #ifdef chains for mpi/no mpi, acc/noacc, etc. But I presume we aren't touching every test heavily through every possible ifdef combination.

It's not so hard to look through the changes, and most seem benign, but some are higher risk and could truly break the code for a specific kind of simulation.

@sbryngelson sbryngelson requested a review from wilfonba July 24, 2025 23:13
@wilfonba
Copy link
Contributor

@wilfonba, can you look at this PR for anything suspicious? I have two (possibly unlikely) worries:

  1. This works for the tests, but there are some cases that this changes that the tests don't touch. Maybe a case where MPI uses more than 2 ranks, or uses 2 ranks on a cylindrical case, and this PR somehow breaks that.
  2. like 1., this goes down many #ifdef chains for mpi/no mpi, acc/noacc, etc. But I presume we aren't touching every test heavily through every possible ifdef combination.

It's not so hard to look through the changes, and most seem benign, but some are higher risk and could truly break the code for a specific kind of simulation.

I'll add it to my list for tomorrow or this weekend.

@wilfonba
Copy link
Contributor

wilfonba commented Jul 31, 2025

Nothing sticks out as obviously problematic to me. Apologies for the delay in response

# for free to join this conversation on GitHub. Already have an account? # to comment
Development

Successfully merging this pull request may close these issues.

Code tidying - Remove unused variables, subroutines, dummy variables, etc.
3 participants