Continuous beam animations with VBA and Python

Following a lengthy discussion at Eng-Tips I have developed several functions to generate animations of the effects of applied moving loads. The Python code and examples have been added to the py_ConBeamU.zip file which can be downloaded from:

py_ConBeamU.zip

Starting with a short VBA sub-routine, using the Conbeam spreadsheet. The code simply generates a sequence of index numbers in a specified range, which are written to the spreadsheet, and the associated position of the applied point load is generated on the spreadsheet and passed to the ConBeam function that generates the required output, in this case the beam vertical deflections.

Sub Animate()
Dim Start As Long, Stp As Long, Target As Variant, EndPause As Double
Start = Range("U25").Value
Stp = Range("V25").Value

Set Target = Range("S25")
ActiveSheet.ChartObjects("Chart 1").Activate
' Enable screen updates for real-time visualization
Application.ScreenUpdating = True
    For i = Start To Stp
        Target.Value = i
        ActiveChart.Refresh
        
        EndPause = Timer + 0.05
        Do While Timer < EndPause
        ActiveSheet.Calculate
        DoEvents
        Loop
    Next
End Sub

The animation displays in Excel as an Excel chart object. To display as a GIF:

  • Copy the active animation using a screen capture programme such as Snagit.
  • Save as an MP4 file
  • Convert to GIF with an on-line app, such as: MP4 to GIF Converter

The first Python function generates a similar graph (deflections due to a moving point moment), using the py_ConBeam function, but with the following differences:

  • The code is written as an Excel User Defined Function, using pyxll, with all input data included in the function input.
  • The deflections are calculated using the py_ConBeam function, called from the Python Code.
  • The animation is generated within the function using Matplotlib, and then written to the spreadsheet as a graphics object.
  • Optionally, the animation can be written to a GIF file, which can then be used in any program accepting the GIF format, including the examples below.

Python code for the moving point load animation:

@xl_func
@xl_arg('Segments', 'numpy_array', ndim = 2) 
@xl_arg('Supports', 'numpy_array', ndim = 2) 
@xl_arg('DLoads', 'numpy_array', ndim = 2)
@xl_arg('PLoads', 'numpy_array', ndim = 2)
@xl_arg('replot', 'bool')
@xl_arg('miny', 'float')
@xl_arg('maxy', 'float')
@xl_arg('savegif', 'bool')
def plot_momdef(Segments, Supports, DLoads, PLoads, replot = False, miny=-4, maxy=4, savegif = False):
    Supports0 = np.copy(Supports)
    if replot:
        OutPoints=np.zeros((101,1))
        endx = Segments[-1,0]
        OutPoints[:,0] = np.linspace(0, endx, 101)
        # Create the matplotlib Figure object, axes and a line
        fig = plt.figure(facecolor='white')
        ax = plt.axes(xlim=(0, endx), ylim=(miny, maxy ))
        plt.grid(True)
        line, = ax.plot([], [], lw=3)
        point, = ax.plot([], [], 'ro', markersize=8)

        # The init function is called at the start of the animation
        def init():
            line.set_data([], [])
            point.set_data([], [])
            return line, point,
        i = 1
        # The animate function is called for each frame of the animation
        def animate(i):
            x = np.linspace(0, endx, 101)
            PLoads[0,0] = OutPoints[i]
            Supports = np.copy(Supports0)
            res = py_ConBeam(Segments, OutPoints, Supports, DLoads, PLoads,1,True)
            # convert y to mm
            y = res[:,4]*1000
            line.set_data(x, y)
            x2 = np.array([OutPoints[i]])
            y2 = np.array([y[i]])
            point.set_data(x2, y2)  
            return line, point, 
        
        # Construct the Animation object        
        anim = FuncAnimation(fig,
                            animate,
                            init_func=init,
                            frames=100,
                            interval=50,
                            blit=True)

        # Call pyxll.plot with the Animation object to render the animation
        # and display it in Excel.
        plot(anim, allow_resize=False)
        # Set savegif to True to save anaimation as a gif file
        if savegif: anim.save("pointmomdef.gif", writer=PillowWriter(fps=30))
    return 'Deflections for moving point moment'

Animation generated by the Python code above:

For this example 2 m long cantilevers were added at each end of the beam, and multi-span continuous beams are also possible.

The examples above generate animations for a single applied point moment, but the py_ConBeam spreadsheet includes a moving load function which allows a vehicle with any number of axles to be generated and applied to a continuous beam with any number of spans. The animations below have been generated using this function with a three span beam with short link slab spans at each support, and the M1600 vehicle from the Australian Bridge Design Code (AS 5100.2).

The beam segment lengths and cross section properties, and support locations and properties are defined in the usual way. Output points should be generated at equal spacing, and are defined by the number of sections per span:

The Vehicle Definition, Load Factors, and Output Units are defined as in the py_MovLoad function. The vehicle positions are defined with the starting and end point of the first axle, together with the number of positions. The graph options include:

  • The action to be plotted; one of Shear, Moment, Slope or Deflection
  • Option to re-plot the animation.
  • Time interval between vehicle positions (milliseconds)
  • Option to save the pot to a gif file.

Note that the plot generation process is quite slow, so the re-plot option should be turned off (0) except when the input has been changed.

The moving load animation is generated immediately under the cell where the plot_MovingLoad function is entered:

As mentioned above, the output options include:

Bending moment:

Shear force:

Slope:

and deflection:

Posted in Animation, Beam Bending, Charts, Excel, Frame Analysis, Link to Python, Newton, PyXLL, UDFs, VBA | Tagged , , , , , , , , , , | 1 Comment

py_ConBeamU and Strand7 check updates

Following the previous post, I have updated the py_ConBeamU spreadsheet, and the associated check against Strand7 results.

The new files can be downloaded from:

py_ConBeamU.zip

The download file now includes:

  • py_ConBeamU.xlsb: The complete spreadsheet, including examples of all functions
  • py_ConBeamU-Check25-2.xlsb: As above, also including the input for all the Strand7 checks
  • Check py_ConBeamU-4Dec25.xlsb: Summary of check results, including ConBeam and Strand7 results and graphs for all 90 cases.
  • py_ConBeamU-check BeamAct-Dec25.xlsb: Check of BeamAct function against Strand7 results
  • Beam_Act2.py: The main Python code for the beam analysis functions.
  • pyNumpy.py, py_Units4Excel.py, Glob_Loc.py: Required associated Python code
  • ConBeam-S7.zip: Strand7 data file and results

For more details of the spreadsheet and included functions see py_ConBeamU and the following associated posts.

Typical results of Strand7 check:

Posted in Beam Bending, Excel, Frame Analysis, Link to Python, Newton, PyXLL, UDFs | Tagged , , , , , , , | 1 Comment

ConBeamU and Strand7 check update

Results of the continuous beam spreadsheet were last checked against Strand7 results 10 years ago. I have now updated this check with the latest version (4.19), which can be downloaded from:

ConBeamU.zip

The download file now includes:

  • ConBeamU.xlsb: The complete spreadsheet, including examples of all functions
  • ConBeamU-CheckDec25.xlsb: As above, also including the input for all the Strand7 checks
  • Check conbeamU-Dec25.xlsb: Summary of check results, including ConBeam and Strand7 results and graphs for all 90 cases.
  • ConBeamU-Template.xlsb: Spreadsheet including all VBA code and required units data, but with all examples removed.

The Strand7 check has 15 different span arrangements, each with 1 of 6 different support conditions:

The span arrangements and support conditions are listed on Sheet1 of the summary spreadsheet:

On the ConBeamU-CheckDec25 spreadsheet the Conbeam Check tab is set up with all 15 span arrangements, and the support restraint type can be selected by entering 1-6 in the “Run Type” cell (F2):

The results for the 6 different support conditions are copied to Sheets 1-6 of the Check conbeamU-Dec25 spreadsheet, together with the equivalent Strand7 results:

Both Conbeam and Strand7 results for shear, moment, slope and deflection are plotted for any selected “Span Type” (1-15):

The main ConBeamU spreadsheet has help on each of the available functions on the Functions tab:

The Strand7 checks used the ConBeam function, which requires consistent units. The ConBeamU function allows a wide range of different units to be used:

See the “Ext Unit List” tab for a list of all recognised units, and see Using ConbeamU for more information on adding to the units list, and more details on using the available functions.

Posted in Beam Bending, Excel, Frame Analysis, Newton, UDFs, VBA | Tagged , , , , , , , , , | 1 Comment

More on TrimRange and the Drop Function

A comment on my previous post links to a helpful YouTube video on using TrimRange and the Dot operator:

It also looks at using the Drop Function to exclude a specified number of rows and/or columns from the top or left of the selected range.

I have added the Drop Function to some examples from the previous post, also adding some text in one cell above the data range:

In Column G Drop has been used in conjunction with the Dot operator excluding empty rows from both the top and bottom of a single column (B.:.B). This removes the first two rows of data, which is not what we want. If the Dot operator is used to exclude only the empty rows at the end (B:.B), Drop then removes Rows 1 and 2, and returns all the data from Row 3 to 15. In Column K the number of rows to be excluded has used the Row function, so that if the data is moved, or if rows are inserted above the data, the formula will still return the data from the top of the table, excluding all new rows above.

The Drop function can also be used to remove columns, and/or rows, in conjunction with the TrimRange function:

In column U the Dot operator is used to return Columns A to E, with empty rows excluded. The Drop function then removes the top 2 rows, and 1 column from the left (Column A), leaving only rows with at least one column containing data.

In Column Z the same result has been achieved using the TrimRange function, rather than the Dot operator, again removing 2 rows and 1 column with the Drop function.

Posted in Arrays, Excel | Tagged , , , , | Leave a comment

The TrimRange Function

I have just discovered the TRIMRANGE function, and its very useful shortcut version, which were introduced to Excel 365 about a year ago. The function excludes all empty rows and/or columns from the outer edges of a range or array, and returns the remainder of the array​​​​​​​​​​​.

The function arguments are:

  • The range to be trimmed, in this case entered as the complete column B:
  • Optional “Row_trim_mode” and “Col_trim_mode” (see below for details).

The shortcut is to simply enter the range as =B.:.B. Some examples are shown below:

  • Either the left or right period may be omitted from the shortcut symbol, so that either only the rows below and columns to the right will be trimmed using B:.B, or only the rows above and columns to the left will be trimmed using B.:B.
  • The range may also be a 2D range, as shown in Column K.

Options to trim only to the left and above, or only to the right and below, are shown below:

Using the optional arguments with the full function name allows more options on the ranges to trim:

  • 0 – None
  • 1 – Trims leading blank rows or columns
  • 2 – Trims trailing blank rows or columns
  • 3 – Trims both leading and trailing blank rows or columns (default) 

In the examples above:

  • =TRIMRANGE(A1:E100,2,2) trims trailing rows and columns
  • =TRIMRANGE(A1:E100,1,2) trims leading rows and trailing columns
  • =TRIMRANGE(A1:E100,3,1) trims both leading and trailing rows, but only leading columns.

Using the shortcut notation:

  • =A1.:E100 is equivalent to: =TRIMRANGE(A1:E100,1,1)
  • =A1:.E100 is equivalent to: =TRIMRANGE(A1:E100,2,2)
  • =A1.:.E100 is equivalent to =TRIMRANGE(A1:E100,3,3) or just =TRIMRANGE(A1:E100)
Posted in Arrays, Excel | Tagged , , , | 2 Comments