File size: 2,036 Bytes
6d15d6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Independent browser translation of the MIT-licensed RST MATLAB synthesis.
// Source and model assumptions are linked in README.md. Coefficients descend in s.
export function multiply(a,b){const c=Array(a.length+b.length-1).fill(0);a.forEach((x,i)=>b.forEach((y,j)=>c[i+j]+=x*y));return c;}
export function add(a,b){const n=Math.max(a.length,b.length);return Array.from({length:n},(_,i)=>(a[i-n+a.length]||0)+(b[i-n+b.length]||0));}
export function design(length=.35,beta=.5,gamma=30){
  if(!Number.isFinite(length)||length<.16||length>.6||!Number.isFinite(beta)||beta<.2||beta>3||!Number.isFinite(gamma)||gamma<4||gamma>40)throw new RangeError('Outside the documented design domain');
  const a=Math.sqrt(9.81/length),a2=a*a;
  const desired=[[1,a],[1,a],[1,beta],[1,gamma],[1,2*beta,beta*beta+1]].reduce(multiply,[1]);
  const [,c1,c2,c3,c4,c5,c6]=desired;
  const R=[(1-a2-c2)/a2,(c1*(1-a2)-c3)/a2,-(a2+c4)/a2,-(a2*c1+c5)/a2,-c6/a2];
  const S=multiply([1,0,1,0],[1,c1]);
  const t2=R[4]/(gamma*beta),m=1-gamma*beta,n=-(gamma+beta),q=-m;
  const y0=R[0]-R[2]+R[4]-(gamma*beta-1)*t2,y1=R[3]-R[1]-(gamma+beta)*t2,det=m*q-n*n;
  const t0=(y0*q-n*y1)/det,t1=(m*y1-n*y0)/det;
  const T=multiply([1,beta+gamma,beta*gamma],[t0,t1,t2]),A=[1,0,-a2],B=[-a2];
  const actual=add(multiply(A,S),multiply(B,R));
  return {length,beta,gamma,a,R,S,T,A,B,desired,actual,poles:[[-a,0],[-a,0],[-beta,0],[-gamma,0],[-beta,1],[-beta,-1]],residual:Math.max(...actual.map((x,i)=>Math.abs(x-desired[i])))/Math.max(...desired.map(Math.abs))};
}
export function evaluate(poly,w){let r=0,i=0;for(const c of poly){const nr=-i*w+c;i=r*w;r=nr;}return [r,i];}
export function response(d,w){const [nr,ni]=evaluate(multiply(d.B,d.T),w),[dr,di]=evaluate(d.actual,w),den=dr*dr+di*di;return [(nr*dr+ni*di)/den,(ni*dr-nr*di)/den];}
export function rollingMean(values,window){if(!Number.isInteger(window)||window<1)throw new RangeError('Invalid window');let sum=0;return values.map((v,i)=>{sum+=v;if(i>=window)sum-=values[i-window];return sum/Math.min(i+1,window);});}