File size: 2,003 Bytes
07af0b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""Mechanics-based bounded intrinsic-curvature design; no neural claims."""
from dataclasses import asdict
import numpy as np
from scipy.optimize import least_squares
from rod import Rod,Controls,serial

def forward(k):
    r=Rod(48)
    c=Controls(chi=.001,fx=.0003,fy=-.0001,k1=float(k[0]),k2=float(k[1]),k3=float(k[2]))
    seed=np.cumsum(np.repeat(k,16))/48
    return r.solve(c,seed),c

def design(target,shape=False):
    target=np.asarray(target)
    def residual(k):
        result,_=forward(k)
        mismatch=result['centerline']-target if shape else result['tip']-target
        return np.r_[mismatch.ravel()*20,.002*k]
    candidates=[least_squares(residual,np.full(3,s),bounds=(-2.4,2.4),max_nfev=70,ftol=1e-10,xtol=1e-10,gtol=1e-10) for s in [-1.,0.,1.]]
    best=min(candidates,key=lambda r:np.linalg.norm(residual(r.x)))
    state,c=forward(best.x)
    path=[]
    for t in np.linspace(0,1,25):
        step,cc=forward(t*best.x)
        path.append(dict(t=float(t),controls=asdict(cc),**serial(step)))
    err=float(np.linalg.norm(state['tip']-target)) if not shape else float(np.sqrt(np.mean(np.sum((state['centerline']-target)**2,axis=1))))
    return dict(target=target.tolist(),controls=asdict(c),error_over_L=err,matched=bool(err<.005 and state['accepted']),stable_sampled_path=all(p['accepted'] and p['stability']=='stable' for p in path),path=path)

if __name__=='__main__':
    from pathlib import Path
    import json
    rng=np.random.default_rng(50);results=[]
    for i in range(12):
        known,_=forward(rng.uniform(-2,2,3))
        shape=i>=8
        result=design(known['centerline'] if shape else known['tip'],shape)
        result['task']='shape' if shape else 'tip'
        assert result['matched'] and result['stable_sampled_path']
        results.append(result)
    (Path(__file__).resolve().parents[1]/'reports/inverse_checks.json').write_text(json.dumps(results))
    print('Inverse checks:',len(results),'max error/L:',max(r['error_over_L'] for r in results))