
    ^j7                     \   d dl Z d dlmZ d dlZd dlmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZmZ d dlmZmZmZ d d	lmZ  G d
 d      Z G d d      ZdedefdZdedefdZ G d d      Z	 	 d%dedededededefdZde e   fdZ!de e   de"fdZ#de fd Z$de"ez  fd!Z%d"ed#efd$Z&y)&    N)Path)Geom_BSplineCurveGeom_BSplineSurface)#GeomConvert_CompCurveToBSplineCurve)gp_Pnt)	Precision)TColgp_Array1OfPntTColgp_Array2OfPnt)TColStd_Array1OfIntegerTColStd_Array1OfRealTColStd_Array2OfReal)minimizec                       e Zd ZdZddefdZedefd       Zej                  defd       ZdefdZ	de
fd	Zde
fd
Zy)Standard_Realzr
    A mutable wrapper for a float value, mimicking C++'s Standard_Real
    when used as an output parameter.
    valuec                 $    t        |      | _        y Nfloat_value)selfr   s     Q/opt/ringagent/.cad-venv/lib/python3.12/site-packages/ocp_gordon/internal/misc.py__init__zStandard_Real.__init__   s    El    returnc                     | j                   S r   r   r   s    r   r   zStandard_Real.value   s    {{r   	new_valuec                 $    t        |      | _        y r   r   )r   r   s     r   r   zStandard_Real.value!   s    I&r   c                     | j                   S r   r   r   s    r   	__float__zStandard_Real.__float__%   s    {{r   c                 "    d| j                    dS )NzStandard_Real()r   r   s    r   __repr__zStandard_Real.__repr__(   s    }A..r   c                 ,    t        | j                        S r   )strr   r   s    r   __str__zStandard_Real.__str__+   s    4;;r   N        )__name__
__module____qualname____doc__r   r   propertyr   setterr"   r'   r%   r(    r   r   r   r      sq    
#e # u   \\'u ' '5 /# /   r   r   c                       e Zd ZddededefdZd ZdefdZdedefd	Zded
efdZ	d
efdZ
d
efdZd
efdZd Zd ZdefdZdefdZdefdZd Zd Zd Zy)math_Vectorlower_indexupper_index
init_valuec                     ||kD  rt        d      || _        || _        t        j                  ||z
  dz   |t        j
                        | _        y )Nz.Lower index cannot be greater than upper index   dtype)
ValueErrorr4   r5   npfullfloat64data)r   r4   r5   r6   s       r   r   zmath_Vector.__init__0   sH    $MNN&&GGK+59:RZZX	r   c                 :    | j                   | j                  z
  dz   S Nr8   )r5   r4   r   s    r   __len__zmath_Vector.__len__7   s    $"2"22Q66r   indexc           	          | j                   |cxk  r| j                  k  s+n t        d| d| j                    d| j                   d      | j                  || j                   z
     S NzIndex z out of range [z, ]r4   r5   
IndexErrorr?   r   rC   s     r   __call__zmath_Vector.__call__:   sk      E=T-=-==t/?/?.@4CSCSBTTUV  yy!1!1122r   r   c           	          | j                   |cxk  r| j                  k  s+n t        d| d| j                    d| j                   d      || j                  || j                   z
  <   y rE   rG   )r   rC   r   s      r   SetValuezmath_Vector.SetValueA   sj      E=T-=-==t/?/?.@4CSCSBTTUV  /4		%$***+r   r   c                      | |      S r   r1   rI   s     r   Valuezmath_Vector.ValueH   s    E{r   c                     | j                   S r   )r4   r   s    r   Lowerzmath_Vector.LowerK       r   c                     | j                   S r   )r5   r   s    r   Upperzmath_Vector.UpperN   rQ   r   c                     t        |       S r   )lenr   s    r   Lengthzmath_Vector.LengthQ   s    4yr   c                     t        |t              rt        |       t        |      k7  rt        d      t        | j                  | j
                        }| j                  |j                  z   |_        |S )Nz2Vectors must be of the same dimension for addition
isinstancer3   rU   r;   r4   r5   r?   r   otherresults      r   __add__zmath_Vector.__add__T   sX    %-Tc%j1HQRRT--t/?/?@ii%**,r   c                     t        |t              rt        |       t        |      k7  rt        d      t        | j                  | j
                        }| j                  |j                  z
  |_        |S )Nz5Vectors must be of the same dimension for subtractionrX   rZ   s      r   __sub__zmath_Vector.__sub__[   sX    %-Tc%j1HTUUT--t/?/?@ii%**,r   scalarc                 n    t        | j                  | j                        }| j                  |z  |_        |S r   )r3   r4   r5   r?   r   r`   r\   s      r   __mul__zmath_Vector.__mul__b   s/    T--t/?/?@ii&(r   c                 $    | j                  |      S r   )rc   )r   r`   s     r   __rmul__zmath_Vector.__rmul__g   s    ||F##r   c                     |dk(  rt        d      t        | j                  | j                        }| j                  |z  |_        |S )Nr   zCannot divide by zero)r;   r3   r4   r5   r?   rb   s      r   __truediv__zmath_Vector.__truediv__j   sB    Q;455T--t/?/?@ii&(r   c                     t        |t              rt        |       t        |      k7  ryt        j                  | j
                  |j
                        S )NF)rY   r3   rU   r<   array_equalr?   r   r[   s     r   __eq__zmath_Vector.__eq__q   s7    %-Tc%j1H~~dii44r   c                 &    | j                  |       S r   )rk   rj   s     r   __ne__zmath_Vector.__ne__v   s    ;;u%%%r   c                 V    d| j                    d| j                   d| j                   dS )Nzmath_Vector(lower=z, upper=z, data=r$   )r4   r5   r?   r   s    r   r%   zmath_Vector.__repr__y   s4    #D$4$4#5Xd>N>N=OwW[W`W`Vaabccr   Nr)   )r+   r,   r-   intr   r   rB   rJ   rL   rN   rP   rS   rV   r]   r_   rc   re   rg   rk   rm   r%   r1   r   r   r3   r3   /   s    YC Yc Yu Y73c 34c 4% 43 5  s   s   e 
$u $% 5
&dr   r3   spliner   c           	         t        d| j                               }| j                  |       t        d| j                               }| j	                  |       t        d| j                               }| j                  |       t        d| j                               }| j                  |       t        ||||| j                         | j                               }|S )zw
    Clone a B-spline curve.

    Args:
        spline: Original B-spline curve

    Returns:
        New B-spline
    r8   )r	   NbPolesPolesr   WeightsNbKnotsKnotsr   Multiplicitiesr   Degree
IsPeriodic)rp   polesweightsknotsmults
new_splines         r   clone_bspliner      s     q&.."23E
LL #1fnn&67G
NN7 !FNN$45E
LL $Av~~'78E
%  #wufmmov7H7H7JJ r   surfacec                    t        d| j                         d| j                               }| j                  |       t	        d| j                         d| j                               }| j                  |       t        d| j                               }| j                  |       t        d| j                               }| j                  |       t        d| j                               }| j                  |       t        d| j                               }| j                  |       t        ||||||| j                         | j!                         | j#                         | j%                         
      }|S )z
    Clone a B-spline surface.

    Args:
        surface: Original B-spline surface

    Returns:
        New B-spline surface
    r8   )r
   NbUPolesNbVPolesrs   r   rt   r   NbUKnotsUKnotsNbVKnotsVKnotsr   UMultiplicitiesVMultiplicitiesr   UDegreeVDegreeIsUPeriodicIsVPeriodic)r   rz   r{   u_knotsv_knotsu_multsv_multsnew_surfaces           r   clone_bspline_surfacer      sD    q'"2"2"4a9I9I9KLEMM% #1g&6&6&8!W=M=M=OPGOOG #1g&6&6&89GNN7 #1g&6&6&89GNN7 &a)9)9);<GG$ &a)9)9);<GG$ &K r   c                   ^    e Zd Zd ZdefdZdededefdZ	dededefdZ
dedededefd	Zy
)$math_MultipleVarFunctionWithGradientc                      y r   r1   r   s    r   r   z-math_MultipleVarFunctionWithGradient.__init__   s    r   r   c                      y)N   r1   r   s    r   NbVariablesz0math_MultipleVarFunctionWithGradient.NbVariables   s    r   XFc                 \    t        d| j                               }| j                  |||      S rA   )r3   r   Valuesr   r   r   Gs       r   rN   z*math_MultipleVarFunctionWithGradient.Value   s*    4++-.{{1a##r   r   c                 >    t        d      }| j                  |||      S )Nr*   )r   r   )r   r   r   r   s       r   Gradientz-math_MultipleVarFunctionWithGradient.Gradient   s    #{{1a##r   c                      y)NTr1   r   s       r   r   z+math_MultipleVarFunctionWithGradient.Values   s    r   N)r+   r,   r-   r   ro   r   r3   r   boolrN   r   r   r1   r   r   r   r      sh    S ${ $} $ $$+ $+ $$ $  + $ r   r   aFuncaX
aToleranceaNbIterationseZEPSc           	         
  j                         dt        t           f fd
t        j                  t        ddz         D cg c]
  } ||       c}      }d	
fd	} ||      }t        
|dd|d|i      }	t              D ]2  }|j                  |j                         |z   |	j                  |          4 |	j                  S c c}w )
Nargsc           	         t        d      }t              D ](  }|j                  |j                         |z   | |          * t	        d      }t        d      }j                  |||      st        d|        |j                  t        j                  t        ddz         D cg c]
  } ||       c}      fS c c}w )Nr8   r*   zfunction cannot evaluate at )
r3   rangerL   rP   r   r   RuntimeErrorr   r<   array)r   ocp_argsiF_kG_k_vecr   nb_variabless        r   fzmath_BFGS.<locals>.f   s    q,/|$ 	=Ahnn.2DG<	= C a.||Hc73!=dVDEEyy"((aPQAQ8R#S1GAJ#STTT#Ss   'B>
r8   c                    | j                   }|dk(  sJ d       t        j                  ||ft              }t	        |      D ]e  }|t        dt        | |               z  }t        j                  |       }|||<    | |z         \  }}	 | |z
        \  }}
|	|
z
  d|z  z  |dd|f<   g d||j                  z   z  }t        t        j                  t        j                  |            j                         d      }|t        j                  |      ||z  z  z   }	 t        j                  j                  |      }d||j                  z   z  }	 t        j                  j                  |      \  }}t        j                   ||d      }|t        j                  |      z  |j                  z  }d||j                  z   z  }t        j                  j#                  |       |S # t        j                  j                  $ rd t        dt        j                  t        j                  t        j                  |                        }t        j                  |      d|z  z  }Y $w xY w# t        j                  j                  $ rp t%        d	       t        dt        j                  t        j                  t        j                  |                        }t        j                  |      d|z  z  }|cY S w xY w)
a  
        Estimate 2x2 inverse Hessian by finite-differencing the gradient and inverting.
        - x0: 1D array-like, length=2 (current point)
        - grad_func: function(x) -> gradient array-like shape (2,)
        - rel_eps: relative step size for finite differences (default sqrt(machine eps))
        - reg: regularization added to Hessian diagonal before inversion
        Returns: 2x2 numpy array H0 (approx inverse Hessian)
        r   z:This routine expects 2 parameters; adapt if you have more.r9   g      ?g       @Ng      ?:0yE>u3   Hessian projection failed — fallback to identity.)sizer<   zerosr   r   maxabs
zeros_likeTdiageyelinalginvLinAlgErrormeaneighclipcholeskyprint)x0rel_epsregnHjepsej_g_plusg_minus
diag_scaleH_reginvHavg_curveigvalseigvecseigvals_clampedinvH_spdr   s                      r   estimate_initial_inv_hessianz/math_BFGS.<locals>.estimate_initial_inv_hessian  sq    GGAvSSSv HHaV5) q 	7ACSAZ00Cr"BBqE"r'
IAv27JAw'C#I6AadG	7 1qss7O 
+//137
BFF1Iz!122	099=='D dTVVm$	!yy~~d3GW !gggw=O !99GIIEHh34HIIx( 9 yy$$ 	0 4
);!<=H66!9h/D		0, yy$$ 	GH4
);!<=H66!9h/DK		s'   G BI" A=II"B
K/.K/TBFGS	hess_inv0)r   jacmethodtoloptions)r   r   )r   listr   r<   r   r   r   rL   rP   xsuccess)r   r   r   r   r   r   r   r   H0resr   r   s   `         @@r   	math_BFGSr      s     $$&L	UU 	U 
%<!+;"<=Q2a5=	>B@D 
&b	)B 	bd6zKQSCTC <  .
BHHJNCEE!H-. ;;_ >s   Csplinesc                    g }| D ]s  }g }t        d|j                         dz         D ]Q  }|j                  |      }|j                  |j	                         |j                         |j                         f       S t        d|j                         dz         D cg c]  }|j                  |       }}t        d|j                         dz         D cg c]  }|j                  |       }}t        d|j                         dz         D cg c]  }|j                  |       }}|j                  |||||j                         |j                         |j                         |j                         d       v |S c c}w c c}w c c}w )Nr8   )rz   r{   r|   r}   degreeis_periodicfirst_parameterlast_parameter)r   rr   Poleappendr   YZWeightru   KnotMultiplicityrx   ry   FirstParameterLastParameter)	r   objrp   rz   r   pr{   r|   r}   s	            r   save_bsplines_to_objectr   R  s\   
C 
24q&..*Q./ 	0AAALL!##%./	0 .31fnn6F6J-KL6==#LL).q&..2BQ2F)GHAQHH16q&..:JQ:N1OPA$$Q'PP

" --/%002#)#8#8#:"("6"6"8		

. J# MHPs   E>FF	file_pathc                     t        t        j                         |z  d      5 }t        j                  t        |       |d       d d d        y # 1 sw Y   y xY w)Nwr   )indent)openr   homejsondumpr   )r   r   r   s      r   save_bsplines_to_filer  p  sH    	diikI%s	+ Aq		)'2Aa@A A As   "AAobjsc           
         g }| D ]t  }t        |d         }t        d|      }t        |      D ]#  }|j                  |dz   t	        |d   |           % t        d|      }t        |      D ]  }|j                  |dz   |d   |           t        |d         }t        d|      }t        |      D ]  }|j                  |dz   |d   |           t        d|      }	t        |      D ]  }|	j                  |dz   |d   |           t        ||||	|d   |d         }
d|v rHd	|v rD|d   |
j                         k7  s|d	   |
j                         k7  r|
j                  |d   |d	          |j                  |
       w |S )
Nrz   r8   r{   r|   r}   r   r   r   r   )rU   r	   r   rL   r   r   r   r   r   r   Segmentr   )r  bsplinesr   rr   rz   r   r{   ru   
knot_array
mult_arrayr~   s              r   load_bsplines_from_objectr  u  s   (*H &$c'l#"1g.w 	<ANN1q5&#g,q/":;	< 'q'2w 	7AQUC	N1$56	7 c'l#)!W5
w 	8AAs7|A7	8 -Q8
w 	8AAs7|A7	8 '7J
CM3}CU


 $ C'%&**C*C*EE'(J,D,D,FF s#45s;K7LM
#M&$P Or   c                    t        |       j                         rt        |       }nt        j                         | z  }t        |d      5 }t	        j
                  |      }d d d        t        |      S # 1 sw Y   t              S xY w)Nr)r   existsr   r   r   loadr  )r   full_file_pathr   r  s       r   load_bsplines_from_filer    sn    Iiy0	nc	" ayy| %T** %T**s   	A22Bcurve1curve2c                    | j                         s|j                         rt        d      t        | j                         |j                               }| j                         |k  r| j	                  |       |j                         |k  r|j	                  |       t        j                         }t        |      }|j                  | |dd      st        d      |j                         }|S )Nz"The two splines must not be closedTz%The two splines must connect together)
IsClosedr;   r   rx   IncreaseDegreer   Confusion_sr   AddBSplineCurve)r  r  
max_degreer   combmergeds         r   concat_two_bsplinesr    s    FOO-=>>V]]_fmmo6J}}#j)}}#j)



!C.v6D88FCt,@AA FMr   )i   g-q=)'r   pathlibr   numpyr<   OCP.Geomr   r   OCP.GeomConvertr   OCP.gpr   OCP.Precisionr   
OCP.TColgpr	   r
   OCP.TColStdr   r   r   scipy.optimizer   r   r3   r   r   r   r   ro   r   r   r   r   r'   r  r  r  r  r1   r   r   <module>r$     s(      ; ?  # = 
 $
   6Kd Kdb +  0A  F0#6 0;N 0f 2 c/cc c 	c
 c 
cNT*;%< <A4(9#: As A
*D *Z
+sTz 
+ 1 ;L r   