# sweep.py: a parameter sweep. The gear script is run for 12 to 48 teeth at module 2.5, every gear is measured,
# and the results go to a table on screen and to sweep.csv. Needs gear.py in FOLDER (loaded if it is not yet).
# Run: exec(open('/your/folder/sweep.py').read())     Tested in FreeCAD 1.1.4.
import os, csv, math, time
FOLDER = os.path.expanduser('~/gear-scripts')        # the folder where you saved gear.py: put its full path here
FOLDER = os.environ.get('PS_SCRIPTS', FOLDER)          # (a PS_SCRIPTS setting wins: used by the tests)
OUT = os.environ.get('PS_OUT', FOLDER)                                        # where sweep.csv goes
if 'create_involute_gear' not in globals() or 'gear_numbers' not in globals():
    g = {'__name__': 'gear'}; exec(open(os.path.join(FOLDER, 'gear.py')).read(), g)
    create_involute_gear, gear_numbers = g['create_involute_gear'], g['gear_numbers']

MODULE, ANGLE, THICK = 2.5, 20, 10
STEEL = 7.85        # g/cm3
rows = []
for teeth in range(12, 49, 6):
    t0 = time.perf_counter()
    shape = create_involute_gear(module=MODULE, num_teeth=teeth, pressure_angle=ANGLE, thickness=THICK)
    ms = (time.perf_counter() - t0) * 1000
    n = gear_numbers(shape, MODULE, teeth, ANGLE)
    rows.append({
        'teeth': teeth, 'pitch_d': round(n['pitch_d'], 2), 'outer_d': round(n['outer_d'], 2),
        'base_d': round(n['base_d'], 2), 'root_d': round(n['root_d'], 2),
        'radial_line': 'yes' if n['root_d'] < n['base_d'] else 'no',           # the script's straight line at the foot
        'undercut_if_cut': 'yes' if teeth < 2 / math.sin(math.radians(ANGLE)) ** 2 else 'no',   # a rack cutter, 20 deg: under 17.1 teeth
        'volume_cm3': round(n['volume_cm3'], 2), 'steel_g': round(n['volume_cm3'] * STEEL),
        'faces': len(shape.Faces), 'valid': n['valid'] and n['solids'] == 1, 'ms': round(ms),
    })
cols = list(rows[0])
print(' '.join('%9s' % c for c in cols))
for r in rows:
    print(' '.join('%9s' % r[c] for c in cols))
path = os.path.join(OUT, 'sweep.csv')
with open(path, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=cols); w.writeheader(); w.writerows(rows)
print('Wrote', os.path.abspath(path))

# ---- test: every gear one valid solid, its sizes from the formulas, the volume growing with the square of the size
for r in rows:
    z = r['teeth']
    assert r['valid'], z
    assert abs(r['pitch_d'] - MODULE * z) < 0.01 and abs(r['outer_d'] - MODULE * (z + 2)) < 0.01 and abs(r['root_d'] - MODULE * (z - 2.5)) < 0.01
assert [r['radial_line'] for r in rows] == ['yes'] * 5 + ['no'] * 2   # root circle = base circle at 2.5 / (1 - cos 20 deg) = 41.4 teeth
by = {r['teeth']: r for r in rows}
assert 3.9 < by[48]['volume_cm3'] / by[24]['volume_cm3'] < 4.1        # twice the teeth at the same module: about 4 times the volume
print('TEST sweep.py: PASS')
