Examples

Below are various example scripts from the TransientBVD/examples directory, demonstrating how to use TransientBVD in different scenarios. Each snippet is embedded here for convenient reference.

Basic Example

A minimal script showing how to import TransientBVD and call a simple method.

 1# basic_example.py
 2from transientbvd import (
 3    print_deactivation_potential,
 4    predefined_transducers,
 5    select_transducer,
 6)
 7from transientbvd.activation import print_activation_potential
 8
 9# Step 1: List all predefined transducers
10print("Available predefined transducers:")
11transducer_names = predefined_transducers()
12for name in transducer_names:
13    print(f"  - {name}")
14
15print("\n")
16
17# Step 2: Select a transducer by name and print its details
18selected_name = "Custom"  # Change to another name if desired
19transducer = select_transducer(selected_name)
20
21# Use __str__ to print transducer details
22print(f"Details of selected transducer:\n{transducer}")
23
24
25# Deactivation: Define resistance range for deactivation potential analysis
26resistance_range = (1, 10000)  # Range of resistances to evaluate in ohms
27print_deactivation_potential(transducer, resistance_range)
28
29# Activation: Use a boost voltage of 20V and a continuous wave voltage of 10V
30print_activation_potential(transducer, ucw=20.0, ub=40)

Basic Predefined Transducer Example

Demonstrates creating a predefined transducer object and using library methods.

 1from transientbvd import predefined_transducers, select_transducer
 2
 3# Step 1: List all predefined transducers
 4print("Available predefined transducers:")
 5transducer_names = predefined_transducers()
 6for name in transducer_names:
 7    print(f"  - {name}")
 8
 9print("\n")
10
11# Step 2: Select a transducer by name and print its details
12selected_name = "SMBLTD45F40H_1"  # Change to another name if desired
13transducer = select_transducer(selected_name)
14
15# Use __str__ to print transducer details
16print(f"Details of selected transducer:\n{transducer}")
17
18# Step 3: Print the equivalent circuit parameters using built-in pretty print
19print("\nEquivalent Circuit Parameters:")
20print(transducer)
21
22# Step 4: Access individual parameters (since Transducer inherits EquivalentCircuitParams)
23print("\nAccessing individual circuit parameters:")
24print(f"  rs = {transducer.rs:.4f} Ω")
25print(f"  ls = {transducer.ls:.6f} H")
26print(f"  cs = {transducer.cs:.2e} F")
27print(f"  c0 = {transducer.c0:.2e} F")
28
29# If the transducer has an optional parallel resistance (rp)
30if transducer.rp is not None:
31    print(f"  rp = {transducer.rp:.2f} Ω")
32
33# Step 5: Print resonance frequency
34print(f"\nResonance Frequency: {transducer.frequency:.2f} Hz")

Deactivation Time Example

Shows how to compute deactivation time (τ) in different conditions for deactivation.

 1from transientbvd import select_transducer, deactivation_tau, deactivation_two_tau
 2
 3# Step 1: Select a predefined transducer
 4selected_name = "SMBLTD45F28H_28kHz"
 5transducer = select_transducer(selected_name)
 6print(f"Selected Transducer:\n{transducer}\n")
 7
 8# Step 2: Calculate τ (tau) and 2τ (two tau) without parallel resistance (rp=None)
 9tau_no_rp = deactivation_tau(transducer)
10two_tau_no_rp = deactivation_two_tau(transducer)
11
12print("Decay Times without Parallel Resistance (rp=None):")
13print(f"  τ (Tau): {tau_no_rp:.6f} s ({tau_no_rp * 1e3:.2f} ms)")
14print(f"  2τ (Two Tau): {two_tau_no_rp:.6f} s ({two_tau_no_rp * 1e3:.2f} ms)\n")
15
16# Step 3: Calculate τ (tau) and 2τ (two tau) with a specified parallel resistance (rp=950 Ω)
17rp = 900  # Parallel resistance in ohms
18tau_with_rp = deactivation_tau(transducer, rp)
19two_tau_with_rp = deactivation_two_tau(transducer, rp)
20
21print(f"Decay Times with Parallel Resistance (rp={rp} Ω):")
22print(f"  τ (Tau): {tau_with_rp:.6f} s ({tau_with_rp * 1e3:.2f} ms)")
23print(f"  2τ (Two Tau): {two_tau_with_rp:.6f} s ({two_tau_with_rp * 1e3:.2f} ms)")

Deactivation Time Over Rp Example

Explores how deactivation time changes over various parallel resistance values (Rp) in the deactivation scenario.

 1import numpy as np
 2import matplotlib.pyplot as plt
 3from transientbvd import select_transducer, deactivation_two_tau
 4
 5# Step 1: Select a predefined transducer
 6selected_name = "SMBLTD45F28H_28kHz"
 7transducer = select_transducer(selected_name)
 8print(f"Selected Transducer:\n{transducer}\n")
 9
10# Step 2: Define the range of resistance values
11rp_values = np.logspace(1, 4, 100)  # Logarithmic scale from 10 Ω to 10,000 Ω
12
13# Step 3: Calculate decay times for each resistance value
14decay_times = [deactivation_two_tau(transducer, rp) for rp in rp_values]
15
16# Step 4: Plot Decay Time vs Resistance
17plt.figure(figsize=(8, 6))
18plt.plot(rp_values, decay_times, label="Decay Time (2τ)", linewidth=2)
19plt.xscale("log")
20plt.yscale("log")
21plt.xlabel("Parallel Resistance (Rp) [Ω]")
22plt.ylabel("Decay Time (2τ) [s]")
23plt.title("Decay Time vs Parallel Resistance")
24plt.grid(True, which="both", linestyle="--", linewidth=0.5)
25plt.legend()
26plt.show()

Optimum Resistance Example

Uses the library’s optimization routine to find the best Rp for minimal deactivation time.

 1from transientbvd import optimum_resistance, select_transducer
 2
 3# Step 1: Select a predefined transducer
 4selected_name = "SMBLTD45F28H_28kHz"
 5transducer = select_transducer(selected_name)
 6print(f"Selected Transducer:\n{transducer}\n")
 7
 8# Step 2: Define a resistance range
 9resistance_range = (10, 5000)  # Resistance range in ohms
10
11# Step 3: Calculate the optimum resistance
12optimal_resistance, minimal_decay_time = optimum_resistance(
13    transducer, resistance_range
14)
15
16# Step 4: Display the results
17print("Optimal Resistance Calculation:")
18print(f"  Resistance Range: {resistance_range[0]} Ω to {resistance_range[1]} Ω")
19print(f"  Optimal Resistance: {optimal_resistance:.2f} Ω")
20print(
21    f"  Minimal Decay Time: {minimal_decay_time:.6f} s ({minimal_decay_time * 1e3:.2f} ms)"
22)

Plot Activation Current Example

Plots the transient current response under an activation scenario with overboost.

  1"""
  2activation_current_plot_example.py
  3
  4This script plots the activation transient current response from the
  5TransientBVD library. It compares:
  61. The overboost approach (using switching time).
  72. The default approach (only continuous-wave voltage).
  8"""
  9
 10import numpy as np
 11import matplotlib.pyplot as plt
 12from transientbvd import select_transducer
 13from transientbvd.activation import activation_current, activation_4tau
 14
 15
 16def plot_activation_current(
 17    timestamps: list[float],
 18    transducer,
 19    ucw: float,
 20    ub: float | None = None,
 21    t_sw: float | None = None,
 22) -> None:
 23    """
 24    Plot the transient current response over time for an activation BVD model.
 25
 26    If 'ub' is given, plots two lines:
 27      1) Overboost approach (from 0 to t_sw with Ub, then switching to Ucw).
 28      2) Default approach (only Ucw from t=0).
 29    Adds lines for:
 30      - Steady-state current (horizontal)
 31      - 4τ time for both the overboosted and non-overboosted scenarios (vertical lines)
 32      - Switching time t_sw if provided.
 33
 34    Parameters
 35    ----------
 36    timestamps : list[float]
 37        Time points (seconds) for evaluating the current.
 38    transducer : Transducer
 39        The transducer object containing the equivalent circuit parameters.
 40    ucw : float
 41        Continuous-wave voltage (volts).
 42    ub : float, optional
 43        Overboost voltage (volts). If None, no overboost is applied.
 44    t_sw : float, optional
 45        Switching time (seconds). If None, and 'ub' is given, an optimal switching time
 46        can be calculated internally by `switching_time`.
 47    """
 48    # 1) Evaluate currents for the overboost approach (if ub is given) or default approach
 49    currents_overboost = [
 50        activation_current(t, transducer, ucw, ub, t_sw) for t in timestamps
 51    ]
 52
 53    # 2) Plot results
 54    plt.figure(figsize=(8, 5))
 55    label_overboost = (
 56        "Transient Current using overboost"
 57        if ub is not None
 58        else "Transient Current (No Overboost)"
 59    )
 60    plt.plot(timestamps, currents_overboost, label=label_overboost, color="b")
 61
 62    # 3) Add the steady-state current reference
 63    steady_state_current = ucw / transducer.rs
 64    plt.axhline(
 65        y=steady_state_current, color="r", linestyle="--", label="Steady-State Current"
 66    )
 67
 68    # 4) If ub is specified, also plot the scenario without any overboost
 69    if ub is not None:
 70        # Currents if only UCW is applied from t=0
 71        currents_no_boost = [activation_current(t, transducer, ucw) for t in timestamps]
 72        plt.plot(
 73            timestamps,
 74            currents_no_boost,
 75            label="Transient Current (Only U_cw)",
 76            color="orange",
 77            linestyle="dashed",
 78        )
 79
 80    # 5) Plot the 4τ time for the overboost approach (or single approach if no ub)
 81    t_4tau_overboost = activation_4tau(transducer, ucw, ub, t_sw)
 82    plt.axvline(
 83        x=t_4tau_overboost, color="black", linestyle="--", label="4τ (Overboost)"
 84    )
 85
 86    # 6) If ub is specified, also show the 4τ time for no overboost
 87    if ub is not None:
 88        t_4tau_no_boost = activation_4tau(transducer, ucw)
 89        plt.axvline(
 90            x=t_4tau_no_boost, color="g", linestyle="dashed", label="4τ (Only U_cw)"
 91        )
 92
 93    # 7) If switching time is given, visualize it
 94    if t_sw is not None:
 95        plt.axvline(x=t_sw, color="black", linestyle="solid", label="Switching Time")
 96
 97    # 8) Final plot formatting
 98    plt.xlabel("Time (s)")
 99    plt.ylabel("Current (A)")
100    plt.title("Activation Transient Current Response Example")
101    plt.legend()
102    plt.grid()
103    plt.show()
104
105
106def main():
107    """
108    Demonstrates usage of the 'plot_activation_current' function.
109    """
110    # Step 1: Select a predefined transducer
111    selected_name = "SMBLTD45F40H_1"
112    transducer = select_transducer(selected_name)
113    print(f"Selected Transducer:\n{transducer}\n")
114
115    # Example parameters (modify as needed):
116    ucw = 40.0
117    ub = 60.0
118
119    # Example timestamps
120    timestamps = np.linspace(0, 0.020, 10000).tolist()
121
122    # Optional switching time
123    t_sw = 0.003  # 3 ms
124
125    # Run the plotting function
126    plot_activation_current(
127        timestamps=timestamps, transducer=transducer, ucw=ucw, ub=ub, t_sw=t_sw
128    )
129
130
131if __name__ == "__main__":
132    main()

Regular Decay Example

Illustrates “regular” or default decay behavior without special damping or overboost.

 1import pandas as pd
 2from transientbvd import select_transducer
 3
 4# Define the transducer models and their numbers
 5transducer_info = {
 6    1: "Custom",
 7    2: "8AF200184",
 8    3: "GB-4540-4SH",
 9    4: "SMBLTD45F40H_1",
10    5: "MA40S4S",
11    6: "SMBLTD45F28H_28kHz",
12}
13
14# Data storage for export
15data = []
16
17# Process each transducer
18for number, name in transducer_info.items():
19    try:
20        # Load the predefined transducer
21        transducer = select_transducer(name)
22
23        # Calculate decay times without using Rp
24        tau_no_rp = 2 * transducer.ls / transducer.rs
25        two_tau_no_rp = 2 * tau_no_rp
26
27        # Store data for export
28        data.append(
29            {
30                "Transducer Number": number,
31                "Model": name,
32                "Rs (Ω)": transducer.rs,
33                "Ls (mH)": transducer.ls * 1e3,  # Convert H to mH
34                "Cs (pF)": transducer.cs * 1e12,  # Convert F to pF
35                "C0 (pF)": transducer.c0 * 1e12,  # Convert F to pF
36                "Two Tau (ms)": two_tau_no_rp * 1e3,  # Convert s to ms
37            }
38        )
39
40    except Exception as e:
41        print(f"Error processing {name}: {e}")
42
43# Export data to CSV
44export_df = pd.DataFrame(data)
45export_df.to_csv("transducer_two_tau.csv", index=False)
46
47print("Regular decay data exported to transducer_two_tau.csv")

Results Saving Example

Showcases how to capture and save computation results (e.g., to CSV or JSON).

 1import pandas as pd
 2import numpy as np
 3from transientbvd import Transducer, deactivation_tau
 4
 5# Step 1: Create a transducer directly in the code
 6transducer = (
 7    Transducer(
 8        rs=24.764,  # Series resistance in ohms
 9        ls=38.959e-3,  # Inductance in henries
10        cs=400.33e-12,  # Series capacitance in farads
11        c0=3970.1e-12,  # Parallel capacitance in farads
12    )
13    .set_name("ExampleTransducer")
14    .set_manufacturer("Example Manufacturer")
15)
16
17print("Transducer used for analysis:")
18print(transducer)
19
20# Step 2: Perform decay analysis over a resistance range
21resistance_range = np.linspace(10, 1000, 50)  # 50 points between 10 and 1000 ohms
22decay_times = [deactivation_tau(transducer, rp=rp) for rp in resistance_range]
23
24# Create a DataFrame to store the results
25decay_df = pd.DataFrame(
26    {"Resistance (Ohms)": resistance_range, "Decay Time (s)": decay_times}
27)
28
29# Print the first few rows of the analysis
30print("\nDecay Analysis Results:")
31print(decay_df.head())
32
33# Step 3: Save the results to a CSV file
34output_file = "decay_analysis_results.csv"
35decay_df.to_csv(output_file, index=False)
36print(f"\nDecay analysis results saved to {output_file}.")