{"text": "function lax_wendroff_2d_display ( )\n\n%*****************************************************************************80\n%\n%% LAX_WENDROFF_2D_DISPLAY illustrates the Lax-Wendroff procedure in 2D.\n%\n% Discussion:\n%\n% A sequence of ball and stick drawings is displayed in steps 0 through 9.\n%\n% Hitting return causes the next item to be drawn.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n for frame = 0 : 9\n%\n% Clear the plotting frame.\n%\n clf\n%\n% Make all the subsequent plotting \"cumulative\".\n%\n hold on\n\n if ( 0 == frame )\n title ( 'Lax-Wendroff 2D scheme' )\n end\n%\n% Central nodes on the blue level.\n%\n if ( 1 <= frame )\n plot3 ( 0.0, 0.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n end\n if ( frame == 1 )\n title ( 'A node where we have the solution.' )\n end\n%\n% The region associated with the central node, blue level.\n%\n if ( 2 <= frame )\n plot3 ( [ -0.5, 0.5 ], [ -0.5, -0.5 ], [ 0.0, 0.0 ], 'b', 'LineWidth', 3 )\n plot3 ( [ 0.5, 0.5 ], [ -0.5, 0.5 ], [ 0.0, 0.0 ], 'b', 'LineWidth', 3 )\n plot3 ( [ 0.5, -0.5 ], [ 0.5, 0.5 ], [ 0.0, 0.0 ], 'b', 'LineWidth', 3 )\n plot3 ( [ -0.5, -0.5 ], [ 0.5, -0.5 ], [ 0.0, 0.0 ], 'b', 'LineWidth', 3 )\n end\n if ( frame == 2 )\n title ( 'The region associated with the node.' )\n end\n%\n% Neighbor nodes on the blue level.\n%\n if ( 3 <= frame )\n plot3 ( -1.0, 0.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 1.0, 0.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, -1.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, 1.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n end\n if ( frame == 3 )\n title ( 'The neighboring nodes.' )\n end\n%\n% Midside nodes on the blue level.\n%\n if ( 4 <= frame )\n plot3 ( -0.5, 0.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.5, 0.0, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, -0.5, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, 0.5, 0.0, 'o', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n end\n if ( frame == 4 )\n plot3 ( [ -1.0, +1.0 ], [ 0.0, 0.0 ], [ 0.0, 0.0 ], 'b', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ -1.0, 1.0 ], [ 0.0, 0.0 ], 'b', 'LineWidth', 3 )\n end\n if ( frame == 4 )\n title ( 'Values at midsides by averaging.' )\n end\n%\n% Center node on the green level.\n% Line from center node on blue to center node on green.\n%\n if ( 5 <= frame )\n plot3 ( -0.5, 0.0, 0.5, 'o', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.5, 0.0, 0.5, 'o', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, -0.5, 0.5, 'o', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, 0.5, 0.5, 'o', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( [ -0.5, 0.5 ], [ -0.5, -0.5 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n plot3 ( [ 0.5, 0.5 ], [ -0.5, 0.5 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n plot3 ( [ 0.5, -0.5 ], [ 0.5, 0.5 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n plot3 ( [ -0.5, -0.5 ], [ 0.5, -0.5 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n end\n if ( frame == 5 )\n plot3 ( [ -0.5, -0.5 ], [ 0.0, 0.0 ], [ 0.0, 0.5 ], 'k', 'LineWidth', 3 )\n plot3 ( [ 0.5, 0.5 ], [ 0.0, 0.0 ], [ 0.0, 0.5 ], 'k', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ -0.5, -0.5 ], [ 0.0, 0.5 ], 'k', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ 0.5, 0.5 ], [ 0.0, 0.5 ], 'k', 'LineWidth', 3 )\n end\n if ( frame == 5 )\n title ( 'Values at midside, half time step.' )\n end\n%\n% Lines from midside nodes to center.\n%\n if ( 6 == frame )\n plot3 ( [ 0.5, 0.0 ], [ 0.0, 0.0 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n plot3 ( [ -0.5, 0.0 ], [ 0.0, 0.0 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ 0.5, 0.0 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ -0.5, 0.0 ], [ 0.5, 0.5 ], 'g', 'LineWidth', 3 )\n end\n if ( frame == 6 )\n title ( 'Estimate fluxes' )\n end\n%\n% Carry neighbor nodes to green level, and draw lines.\n%\n if ( 7 <= frame )\n plot3 ( 0.0, 0.0, 0.5, 'o', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n end\n if ( frame == 7 )\n title ( 'Estimate derivative at node, half time step.' )\n end\n%\n% Advance solution to full time.\n%\n if ( 8 <= frame )\n plot3 ( [ 0.0, 0.0 ], [ 0.0, 0.0 ], [ 0.0, 1.0 ], 'k', 'LineWidth', 3 )\n plot3 ( 0.0, 0.0, 1.0, 'o', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( [ -0.5, 0.5 ], [ -0.5, -0.5 ], [ 1.0, 1.0 ], 'r', 'LineWidth', 3 )\n plot3 ( [ 0.5, 0.5 ], [ -0.5, 0.5 ], [ 1.0, 1.0 ], 'r', 'LineWidth', 3 )\n plot3 ( [ 0.5, -0.5 ], [ 0.5, 0.5 ], [ 1.0, 1.0 ], 'r', 'LineWidth', 3 )\n plot3 ( [ -0.5, -0.5 ], [ 0.5, -0.5 ], [ 1.0, 1.0 ], 'r', 'LineWidth', 3 )\n end\n if ( frame == 8 )\n title ( 'Take full step to new time.' )\n end\n%\n% Advance all data.\n%\n if ( 9 <= frame )\n plot3 ( [ -1.0, -1.0 ], [ 0.0, 0.0 ], [ 0.0, 1.0 ], 'k', 'LineWidth', 3 )\n plot3 ( [ 1.0, 1.0 ], [ 0.0, 0.0 ], [ 0.0, 1.0 ], 'k', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ -1.0, -1.0 ], [ 0.0, 1.0 ], 'k', 'LineWidth', 3 )\n plot3 ( [ 0.0, 0.0 ], [ 1.0, 1.0 ], [ 0.0, 1.0 ], 'k', 'LineWidth', 3 )\n plot3 ( -1.0, 0.0, 1.0, 'o', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 1.0, 0.0, 1.0, 'o', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, -1.0, 1.0, 'o', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n plot3 ( 0.0, 1.0, 1.0, 'o', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k', 'MarkerSize', 12 )\n end\n if ( frame == 9 )\n title ( 'Advance all data to new time.' )\n end\n\n xlabel ( '- X -' )\n ylabel ( '- Y -' )\n zlabel ( '- Time -' )\n\n axis ( [ -1, +1, -1, +1, 0, 1] )\n view ( 3 )\n%\n% \"Release\" the plotting screen.\n%\n hold off\n\n pause\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ball_and_stick_display/lax_wendroff_2d_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.39999753773871144}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% example 4 DOF planar robot.\n%\n% Author: Arturo Gil. Universidad Miguel Hernandez de Elche. \n% email: arturo.gil@umh.es date: 05/03/2012\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction robot = parameters()\n\nrobot.name='Example 4DOF planar arm';\n\n%kinematic data DH parameters\nrobot.DH.theta='[q(1) q(2) q(3) q(4)]';\nrobot.DH.d='[0 0 0 0]';\nrobot.DH.a='[1 1 1 1]';\nrobot.DH.alpha='[0 0 0 0]';\n\n%number of degrees of freedom\nrobot.DOF = 4;\n\n%Jacobian matrix\n% if not defined, compute it with manipulator_jacobian\nrobot.J=[];\n%the proper rows of J to compute manipulability\nrobot.selJ =[1,2,6];\nrobot.kind=['R' 'R' 'R' 'R'];\n\n\n%Function name to compute inverse kinematic\nrobot.inversekinematic_fn = 'inverse_kinematics_4dofplanar(robot, T, q)';\nrobot.directkinematic_fn = 'directkinematic(robot, q)';\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum\n deg2rad(-180) deg2rad(180);\n deg2rad(-180) deg2rad(180)]; %Axis 2, minimum, maximum\n \n %minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-90) deg2rad(90); %Axis 1, minimum, maximum\n deg2rad(-90) deg2rad(90);\n deg2rad(-180) deg2rad(180)]; %Axis 2, minimum, maximum\n \n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = []; %empty, not available\n\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n% end effectors maximum velocity\nrobot.linear_velmax = 0; %m/s, example, not available\n\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\nrobot.path = pwd;\n\n%this is an ad hoc transformation between the piece and the robot's end\n%effector\n% robot.Tcoupling=[-1 0 0 0;\n% 0 1 0 0;\n% 0 0 -1 0;\n% 0 0 0 1];\n% Tc1 = [cos(-pi/2) 0 sin(-pi/2) 0;\n% 0 1 0 0;\n% -sin(-pi/2) 0 cos(-pi/2) 0;\n% 0 0 0 1 ];\n% Tc2 = [1 0 0 0;\n% 0 cos(pi) -sin(pi) 0;\n% 0 sin(pi) cos(pi) 0;\n% 0 0 0 1];\n% robot.Tcoupling =Tc1*Tc2;\nrobot.Tcoupling = eye(4);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%GRAPHICS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%read graphics files\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 20 40]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-3.5 3.5 -3.5 3.5 0 1]\nrobot = read_graphics(robot);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%DYNAMIC PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrobot.has_dynamics=1;\n\n%consider friction in the computations\nrobot.dynamics.friction=0;\n\n%link masses (kg)\nrobot.dynamics.masses=[1 1 1] ;\n\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[-0.5 0 0; %(rx, ry, rz) link 1\n -0.5 0 0;\n -0.5 0 0];%(rx, ry, rz) link 2\n\n%link masses\nm1 = robot.dynamics.masses(1);\nm2 = robot.dynamics.masses(2);\nm3 = robot.dynamics.masses(3);\n\na=eval(robot.DH.a);\nL1 = a(1);\nL2 = a(2);\nL3 = a(3);\n\n%Momentos de inercia de cada eslabon.\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, por cada fila\nrobot.dynamics.Inertia=[0 m1*L1^2/3 m1*L1^2/3 0\t0\t0;\n 0 m2*L2^2/3 m2*L2^2/3 0\t0\t0;\n 0 m3*L3^2/3 m3*L3^2/3 0\t0\t0];\n \n%Actuator rotor inertia\nrobot.motors.Inertia=[0 0 0];\n%Reduction ratio motor/joint speed\nrobot.motors.G=[1 1 1];\n%consider friction\nrobot.friction=0;\n%Viscous friction factor, motor referred\n%robot.B = [1e-3 1e-3 1e-3];\nrobot.motors.Viscous = [10 10 10];\n%Coulomb friction, motor referred\nrobot.motors.Coulomb = [0 0;\n 0 0;\n 0 0];\n \n%SPECIAL PARAMETERS TO SOLVE THE INVERSE KINEMATICS\nrobot.parameters.step_time=0.1;\n%Error in XYZ to stop inverse kinematics\nrobot.parameters.epsilonXYZ=0.01;\n%Error in Quaternion to stop inverse kinematics.\nrobot.parameters.epsilonQ=0.01;\nrobot.parameters.stop_iterations=500;\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/example/4dofplanar/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.39999752766547825}}
{"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%\tlengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us %to add a specific muscle model, please let Nick (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the HEART-TUBE-EXAMPLE geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction HeartTube()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 128; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nNy = 128; % # of Eulerian Grid Pts. in y-Direction (MUST BE EVEN!!!)\nLx = 5.0; % Length of Eulerian Grid in x-Direction\nLy = 5.0; % Length of Eulerian Grid in y-Direction\n\n\n% Immersed Structure Geometric / Dynamic Parameters %\nds = Lx/(2*Nx); % Lagrangian Spacing\nd = 1.0; % Diameter of the tube\nL = 3.0; % Length of the heart-tube\nstruct_name = 'HeartTube'; % Name for .vertex, .spring, etc files.\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,L,d,Lx,Ly);\n\n\n% Plot Geometry to test\nplot(xLag(1:end/2),yLag(1:end/2),'r-'); hold on;\nplot(xLag(end/2+1:end),yLag(end/2+1:end),'r-'); hold on;\nplot(xLag,yLag,'*'); hold on;\nxlabel('x'); ylabel('y');\naxis([0 Lx 0 Ly]);\n\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .spring file!\nk_Spring = 1e7;\nprint_Lagrangian_Springs(xLag,k_Spring,ds,struct_name);\n\n% Prints .muscle file! [ a_f * Fmax *exp( -( (Q-1)/SK )^2 ) * (1/P0)*(b*P0-a*v)/(v+b); Q = LF/LFO ]\nLFO = d; SK = 0.3; a = 0.25; b = 4.0; Fmax = 1e5;\nprint_Lagrangian_Muscles(xLag,LFO,SK,a,b,Fmax,struct_name)\n\n\n% Prints .beam file!\nk_Beam = 7.5e7; C = 0.0;\nprint_Lagrangian_Beams(xLag,k_Beam,C,struct_name);\n\n\n% Prints .target file!\nk_Target = 1e6;\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called rubberband.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag);\n\n vertex_fid = fopen([struct_name '.vertex'], 'w');\n\n fprintf(vertex_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n X_v = xLag(s);\n Y_v = yLag(s);\n fprintf(vertex_fid, '%1.16e %1.16e\\n', X_v, Y_v);\n end\n\n fclose(vertex_fid); \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints Vertex points to a file called rubberband.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name)\n\n N = length(xLag); % Total Number of Lagrangian Pts\n num = 1; % Number of target points on each end\n\n target_fid = fopen([struct_name '.target'], 'w');\n\n fprintf(target_fid, '%d\\n', 4*num );\n\n %Loops over all Lagrangian Pts.\n %for s = 1:N\n \n \n %Left Bottom Target Points\n for s=1:num\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n \n %Right Bottom Target Points\n for s=(N/2)-(num-1):N/2\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n \n %Left Top Target Points\n for s=(N/2+1):(N/2+1)+(num-1)\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n \n %Right Top Target Points\n for s=N-(num-1):N\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n \n\n\n %end\n\n fclose(target_fid); \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints BEAM (Torsional Spring) points to a file called rubberband.beam\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Beams(xLag,k_Beam,C,struct_name)\n\n % k_Beam: beam stiffness\n % C: beam curvature\n \n N = length(xLag); % NOTE: Total number of beams = Number of Total Lag Pts. - 2\n\n beam_fid = fopen([struct_name '.beam'], 'w');\n\n fprintf(beam_fid, '%d\\n', N - 4 );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %BEAMS BETWEEN VERTICES\n for s = 2:N-1\n if s <= N/2-1\n % Bottom of tube\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C); \n elseif ( ( s >= N/2+2 ) && ( s <= N-1 ) )\n % Top of Tube\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C); \n end\n end\n fclose(beam_fid); \n \n \n \n\n \n \n\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints MUSCLE points to a file called \"struct_name\".muscle\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Muscles(xLag,LFO,SK,a,b,Fmax,struct_name)\n\n N = length(xLag); %Number of Lagrangian Pts. Total\n\n muscle_fid = fopen([struct_name '.muscle'], 'w');\n\n fprintf(muscle_fid, '%d\\n', N/2-2 );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %MUSCLES BETWEEN VERTICES\n for s = 2:N/2-1\n fprintf(muscle_fid, '%d %d %1.16e %1.16e %1.16e %1.16e %1.16e\\n', s, s+N/2, LFO, SK, a,b,Fmax); \n end\n fclose(muscle_fid);\n \n \n \n \n \n \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called rubberband.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,k_Spring,ds_Rest,struct_name)\n\n N = length(xLag); %Number of Lagrangian Pts. Total\n\n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', N-2 );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %SPRINGS BETWEEN VERTICES\n for s = 1:N\n if s < N/2 \n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n elseif ( ( s >= N/2+1 ) && ( s < N ) )\n %Case s=N\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n end\n end\n fclose(spring_fid); \n \n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,L,d,Lx,Ly)\n\n% The immsersed structure is a straight heart-tube %\nx1 = [-L/2:ds:L/2 L/2]; % Constructs x-Values for bottom of tube\ny1 = -d/2*ones(1,length(x1)); % Constructs y-Values for bottom of tube\n\nx2 = x1; % Constructs x-Values for top of tube\ny2 = -y1; % Constructs y-Values for top of tube\n\nx1 = x1 + Lx/2; % Shift into correct box\nx2 = x2 + Lx/2; % Shift into correct box\n\ny1 = y1 + Ly/2; % Shift into correct box\ny2 = y2 + Ly/2; % Shift into correct box\n\nxLag = [x1 x2];\nyLag = [y1 y2];\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_HeartTube/3_Element_Muscle_Model/HeartTube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3994874076196448}}
{"text": "%SerialLink.ikine6s Analytical inverse kinematics\n%\n% Q = R.ikine(T) are the joint coordinates (1xN) corresponding to the robot\n% end-effector pose T which is an SE3 object or homogenenous transform\n% matrix (4x4), and N is the number of robot joints. This is a analytic\n% solution for a 6-axis robot with a spherical wrist (the most common form\n% for industrial robot arms).\n%\n% If T represents a trajectory (4x4xM) then the inverse kinematics is\n% computed for all M poses resulting in Q (MxN) with each row representing\n% the joint angles at the corresponding pose.\n%\n% Q = R.IKINE6S(T, CONFIG) as above but specifies the configuration of the arm in\n% the form of a string containing one or more of the configuration codes:\n%\n% 'l' arm to the left (default)\n% 'r' arm to the right\n% 'u' elbow up (default)\n% 'd' elbow down\n% 'n' wrist not flipped (default)\n% 'f' wrist flipped (rotated by 180 deg)\n%\n% Trajectory operation::\n%\n% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous\n% transform sequence (4x4xM) then R.ikcon() returns the joint coordinates\n% corresponding to each of the transforms in the sequence.\n%\n% Notes::\n% - Treats a number of specific cases:\n% - Robot with no shoulder offset\n% - Robot with a shoulder offset (has lefty/righty configuration)\n% - Robot with a shoulder offset and a prismatic third joint (like Stanford arm)\n% - The Puma 560 arms with shoulder and elbow offsets (4 lengths parameters)\n% - The Kuka KR5 with many offsets (7 length parameters)\n% - The inverse kinematics for the various cases determined using ikine_sym.\n% - The inverse kinematic solution is generally not unique, and\n% depends on the configuration string.\n% - Joint offsets, if defined, are added to the inverse kinematics to\n% generate Q.\n% - Only applicable for standard Denavit-Hartenberg parameters\n%\n% Reference::\n% - Inverse kinematics for a PUMA 560,\n% Paul and Zhang,\n% The International Journal of Robotics Research,\n% Vol. 5, No. 2, Summer 1986, p. 32-44\n%\n% Author::\n% - The Puma560 case: Robert Biro with Gary Von McMurray,\n% GTRI/ATRP/IIMB, Georgia Institute of Technology, 2/13/95\n% - Kuka KR5 case: Gautam Sinha,\n% Autobirdz Systems Pvt. Ltd., SIDBI Office,\n% Indian Institute of Technology Kanpur, Kanpur, Uttar Pradesh.\n%\n% See also SerialLink.fkine, SerialLink.ikine, SerialLink.ikine_sym.\n\nfunction thetavec = ikine6s(robot, TT, varargin)\n \n if robot.mdh ~= 0\n error('RTB:ikine:notsupported','Solution only applicable for standard DH conventions');\n end\n \n if robot.n ~= 6\n error('RTB:ikine:notsupported','Solution only applicable for 6-axis robot');\n end\n \n \n %\n % % recurse over all poses in a trajectory\n % if ndims(T) == 3\n % theta = zeros(size(T,3),robot.n);\n % for k=1:size(T,3)\n % theta(k,:) = ikine6s(robot, T(:,:,k), varargin{:});\n % end\n % return;\n % end\n %\n %\n % if ~ishomog(T)\n % error('RTB:ikine:badarg', 'T is not a homog xform');\n % end\n \n TT = SE3(TT);\n \n \n L = robot.links;\n \n if ~robot.isspherical()\n error('RTB:ikine:notsupported', 'wrist is not spherical');\n end\n \n \n \n % The configuration parameter determines what n1,n2,n4 values are used\n % and how many solutions are determined which have values of -1 or +1.\n \n if nargin < 3\n configuration = '';\n else\n configuration = lower(varargin{1});\n end\n \n % default configuration\n \n sol = [1 1 1]; % left, up, noflip\n \n for c=configuration\n switch c\n case 'l'\n sol(1) = 1;\n case 'r'\n sol(1) = 2;\n case 'u'\n sol(2) = 1;\n case 'd'\n sol(2) = 2;\n case 'n'\n sol(3) = 1;\n case 'f'\n sol(3) = 2;\n end\n end\n \n \n % determine the arm structure and the relevant solution to use\n if isempty(robot.ikineType)\n if is_simple(L)\n robot.ikineType = 'nooffset';\n elseif is_puma(L)\n robot.ikineType = 'puma';\n elseif is_offset(L)\n robot.ikineType = 'offset';\n elseif is_rrp(L)\n robot.ikineType = 'rrp';\n else\n error('RTB:ikine6s:badarg', 'This kinematic structure not supported');\n end\n end\n \n for k=1:length(TT)\n \n % undo base and tool transformations\n T = inv(robot.base) * TT(k) * inv(robot.tool);\n \n % drop back to matrix form\n T = T.T;\n \n %% now solve for the first 3 joints, based on position of the spherical wrist centre\n \n \n switch robot.ikineType\n case 'puma'\n % Puma model with shoulder and elbow offsets\n %\n % - Inverse kinematics for a PUMA 560,\n % Paul and Zhang,\n % The International Journal of Robotics Research,\n % Vol. 5, No. 2, Summer 1986, p. 32-44\n %\n % Author::\n % Robert Biro with Gary Von McMurray,\n % GTRI/ATRP/IIMB,\n % Georgia Institute of Technology\n % 2/13/95\n \n a2 = L(2).a;\n a3 = L(3).a;\n d1 = L(1).d;\n d3 = L(3).d;\n d4 = L(4).d;\n \n % The following parameters are extracted from the Homogeneous\n % Transformation as defined in equation 1, p. 34\n \n Ox = T(1,2);\n Oy = T(2,2);\n Oz = T(3,2);\n \n Ax = T(1,3);\n Ay = T(2,3);\n Az = T(3,3);\n \n Px = T(1,4);\n Py = T(2,4);\n Pz = T(3,4) - d1;\n \n %\n % Solve for theta(1)\n %\n % r is defined in equation 38, p. 39.\n % theta(1) uses equations 40 and 41, p.39,\n % based on the configuration parameter n1\n %\n \n r = sqrt(Px^2 + Py^2);\n if sol(1) == 1\n theta(1) = atan2(Py,Px) + pi - asin(d3/r);\n else\n theta(1) = atan2(Py,Px) + asin(d3/r);\n end\n \n %\n % Solve for theta(2)\n %\n % V114 is defined in equation 43, p.39.\n % r is defined in equation 47, p.39.\n % Psi is defined in equation 49, p.40.\n % theta(2) uses equations 50 and 51, p.40, based on the configuration\n % parameter n2\n %\n if sol(2) == 1\n n2 = -1;\n else\n n2 = 1;\n end\n if sol(1) == 2\n n2 = -n2;\n end\n \n V114 = Px*cos(theta(1)) + Py*sin(theta(1));\n r = sqrt(V114^2 + Pz^2);\n Psi = acos((a2^2-d4^2-a3^2+V114^2+Pz^2)/(2.0*a2*r));\n if ~isreal(Psi)\n theta = [];\n else\n \n theta(2) = atan2(Pz,V114) + n2*Psi;\n \n %\n % Solve for theta(3)\n %\n % theta(3) uses equation 57, p. 40.\n %\n num = cos(theta(2))*V114+sin(theta(2))*Pz-a2;\n den = cos(theta(2))*Pz - sin(theta(2))*V114;\n theta(3) = atan2(a3,d4) - atan2(num, den);\n end\n case 'nooffset'\n a2 = L(2).a;\n a3 = L(3).a;\n d1 = L(1).d;\n \n px = T(1,4); py = T(2,4); pz = T(3,4);\n \n %%% autogenerated code\n if L(1).alpha < 0\n if sol(1) == 1\n q(1) = angle(-px-py*1i);\n else\n q(1) = angle(px+py*1i);\n end\n S1 = sin(q(1));\n C1 = cos(q(1));\n \n if sol(2) == 1\n q(2) = -angle(a2*d1*-2.0+a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i-sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);\n else\n q(2) = -angle(a2*d1*-2.0+a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i+sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);\n end\n S2 = sin(q(2));\n C2 = cos(q(2));\n \n if sol(3) == 1\n q(3) = -angle(a2*-1i+C2*d1-C2*pz+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i-sqrt((-a2+S2*d1-S2*pz+C1*C2*px+C2*S1*py)^2+(-C2*d1+C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));\n else\n q(3) = -angle(a2*-1i+C2*d1-C2*pz+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt((-a2+S2*d1-S2*pz+C1*C2*px+C2*S1*py)^2+(-C2*d1+C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));\n end\n else\n if sol(1) == 1\n q(1) = angle(px+py*1i);\n else\n q(1) = angle(-px-py*1i);\n end\n S1 = sin(q(1));\n C1 = cos(q(1));\n \n if sol(2) == 1\n q(2) = -angle(a2*d1*2.0-a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i-sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);\n else\n q(2) = -angle(a2*d1*2.0-a2*pz*2.0-C1*a2*px*2.0i-S1*a2*py*2.0i)+angle(d1*pz*2.0i-a2^2*1i+a3^2*1i-d1^2*1i-pz^2*1i-C1^2*px^2*1i+sqrt((a2*d1*2.0-a2*pz*2.0)^2+(C1*a2*px*2.0+S1*a2*py*2.0)^2-(d1*pz*-2.0+a2^2-a3^2+d1^2+pz^2+C1^2*px^2+S1^2*py^2+C1*S1*px*py*2.0)^2)-S1^2*py^2*1i-C1*S1*px*py*2.0i);\n end\n S2 = sin(q(2));\n C2 = cos(q(2));\n \n if sol(3) == 1\n q(3) = -angle(a2*-1i-C2*d1+C2*pz-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i-sqrt((-a2-S2*d1+S2*pz+C1*C2*px+C2*S1*py)^2+(C2*d1-C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));\n else\n q(3) = -angle(a2*-1i-C2*d1+C2*pz-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt((-a2-S2*d1+S2*pz+C1*C2*px+C2*S1*py)^2+(C2*d1-C2*pz+C1*S2*px+S1*S2*py)^2-a3^2));\n end\n end\n \n theta(1:3) = q;\n \n case'offset'\n % general case with 6 length parameters\n a1 = L(1).a;\n a2 = L(2).a;\n a3 = L(3).a;\n d1 = L(1).d;\n d2 = L(2).d;\n d3 = L(3).d;\n \n px = T(1,4); py = T(2,4); pz = T(3,4);\n \n %%% autogenerated code\n if L(1).alpha < 0\n \n if sol(1) == 1\n q(1) = -angle(-px+py*1i)+angle(d2*1i+d3*1i-sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2));\n else\n q(1) = angle(d2*1i+d3*1i+sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2))-angle(-px+py*1i);\n end\n S1 = sin(q(1));\n C1 = cos(q(1));\n \n if sol(2) == 1\n q(2) = angle(d1*pz*2.0i-sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i+d1-pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));\n else\n q(2) = angle(d1*pz*2.0i+sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i+d1-pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));\n end\n S2 = sin(q(2));\n C2 = cos(q(2));\n \n if sol(3) == 1\n q(3) = angle(a3*1i-sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0-S2*a2*d1*2.0-S1*a1*py*2.0+S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0))-angle(a2*-1i-C2*a1*1i+C2*d1-C2*pz+S2*a1+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py);\n else\n q(3) = -angle(a2*-1i-C2*a1*1i+C2*d1-C2*pz+S2*a1+S2*d1*1i-S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0-S2*a2*d1*2.0-S1*a1*py*2.0+S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0));\n end\n else\n if sol(1) == 1\n q(1) = -angle(px-py*1i)+angle(d2*1i+d3*1i-sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2));\n else\n q(1) = -angle(px-py*1i)+angle(d2*1i+d3*1i+sqrt(d2*d3*-2.0-d2^2-d3^2+px^2+py^2));\n end\n S1 = sin(q(1));\n C1 = cos(q(1));\n \n if sol(2) == 1\n q(2) = angle(d1*pz*2.0i-sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i-d1+pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));\n else\n q(2) = angle(d1*pz*2.0i+sqrt(d1*pz^3*4.0+d1^3*pz*4.0-a1^4-a2^4-a3^4-d1^4-py^4-pz^4-C1^4*px^4+C1^2*py^4*2.0-C1^4*py^4+a1^2*a2^2*2.0+a1^2*a3^2*2.0+a2^2*a3^2*2.0-a1^2*d1^2*2.0+a2^2*d1^2*2.0+a3^2*d1^2*2.0-a1^2*py^2*6.0-a2^2*py^2*2.0+a3^2*py^2*2.0-a1^2*pz^2*2.0+a2^2*pz^2*2.0+a3^2*pz^2*2.0-d1^2*py^2*2.0-d1^2*pz^2*6.0-py^2*pz^2*2.0+d1*py^2*pz*4.0+C1^3*a1*px^3*4.0+S1^3*a1*py^3*4.0-C1^2*a1^2*px^2*6.0+C1^2*a2^2*px^2*2.0+C1^2*a3^2*px^2*2.0+C1^2*a1^2*py^2*6.0+C1^2*a2^2*py^2*1.0e1-C1^2*a3^2*py^2*2.0-C1^4*a2^2*py^2*1.2e1+C1^6*a2^2*py^2*4.0-C1^2*d1^2*px^2*2.0+C1^2*d1^2*py^2*2.0-C1^2*px^2*py^2*6.0+C1^4*px^2*py^2*6.0-C1^2*px^2*pz^2*2.0+C1^2*py^2*pz^2*2.0+S1^6*a2^2*py^2*4.0+C1*a1^3*px*4.0+S1*a1^3*py*4.0+a1^2*d1*pz*4.0-a2^2*d1*pz*4.0-a3^2*d1*pz*4.0-C1*a1*a2^2*px*4.0-C1*a1*a3^2*px*4.0-C1*S1*px^3*py*4.0+C1*a1*d1^2*px*4.0+C1*a1*px*py^2*1.2e1+C1*a1*px*pz^2*4.0+S1*a1*a2^2*py*4.0-S1*a1*a3^2*py*4.0+S1*a1*d1^2*py*4.0+S1*a1*px^2*py*4.0+S1*a1*py*pz^2*4.0-C1*S1^3*px*py^3*4.0+C1*S1^3*px^3*py*4.0-C1^3*a1*px*py^2*1.2e1-S1^3*a1*a2^2*py*8.0+C1^2*d1*px^2*pz*4.0-C1^2*d1*py^2*pz*4.0-S1^3*a1*px^2*py*4.0-C1*a1*d1*px*pz*8.0-S1*a1*d1*py*pz*8.0-C1*S1*a1^2*px*py*1.2e1-C1*S1*a2^2*px*py*4.0+C1*S1*a3^2*px*py*4.0-C1*S1*d1^2*px*py*4.0-C1*S1*px*py*pz^2*4.0-C1^2*S1*a1*a2^2*py*8.0+C1^2*S1*a1*px^2*py*8.0+C1*S1^3*a2^2*px*py*8.0+C1^3*S1*a2^2*px*py*8.0+C1*S1*d1*px*py*pz*8.0)-a1^2*1i-a2^2*1i+a3^2*1i-d1^2*1i-py^2*1i-pz^2*1i-C1^2*px^2*1i+C1^2*py^2*1i+C1*a1*px*2.0i+S1*a1*py*2.0i-C1*S1*px*py*2.0i)-angle(-a2*(a1*-1i-d1+pz+C1*px*1i+S1^3*py*1i+C1^2*S1*py*1i));\n end\n S2 = sin(q(2));\n C2 = cos(q(2));\n \n if sol(3) == 1\n q(3) = angle(a3*1i-sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0+S2*a2*d1*2.0-S1*a1*py*2.0-S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0))-angle(a2*-1i-C2*a1*1i-C2*d1+C2*pz+S2*a1-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py);\n else\n q(3) = -angle(a2*-1i-C2*a1*1i-C2*d1+C2*pz+S2*a1-S2*d1*1i+S2*pz*1i+C1*C2*px*1i-C1*S2*px+C2*S1*py*1i-S1*S2*py)+angle(a3*1i+sqrt(d1*pz*-2.0+a1^2+a2^2-a3^2+d1^2+py^2+pz^2+C1^2*px^2-C1^2*py^2+C2*a1*a2*2.0-C1*a1*px*2.0+S2*a2*d1*2.0-S1*a1*py*2.0-S2*a2*pz*2.0-C1*C2*a2*px*2.0-C2*S1*a2*py*2.0+C1*S1*px*py*2.0));\n end\n end\n \n theta(1:3) = q;\n \n \n case 'rrp'\n % RRP (Stanford arm like)\n \n px = T(1,4); py = T(2,4); pz = T(3,4);\n d1 = L(1).d;\n d2 = L(2).d;\n \n %%% autogenerated code\n if L(1).alpha < 0\n if sol(1) == 1\n q(1) = -angle(-px+py*1i)+angle(d2*1i-sqrt(-d2^2+px^2+py^2));\n else\n q(1) = angle(d2*1i+sqrt(-d2^2+px^2+py^2))-angle(-px+py*1i);\n end\n S1 = sin(q(1));\n C1 = cos(q(1));\n \n if sol(2) == 1\n q(2) = angle(d1-pz-C1*px*1i-S1*py*1i);\n else\n q(2) = angle(-d1+pz+C1*px*1i+S1*py*1i);\n end\n S2 = sin(q(2));\n C2 = cos(q(2));\n \n q(3) = -C2*d1+C2*pz+C1*S2*px+S1*S2*py;\n \n else\n if sol(1) == 1\n q(1) = -angle(px-py*1i)+angle(d2*1i-sqrt(-d2^2+px^2+py^2));\n else\n q(1) = -angle(px-py*1i)+angle(d2*1i+sqrt(-d2^2+px^2+py^2));\n end\n S1 = sin(q(1));\n C1 = cos(q(1));\n \n if sol(2) == 1\n q(2) = angle(-d1+pz-C1*px*1i-S1*py*1i);\n else\n q(2) = angle(d1-pz+C1*px*1i+S1*py*1i);\n end\n S2 = sin(q(2));\n C2 = cos(q(2));\n \n q(3) = -C2*d1+C2*pz-C1*S2*px-S1*S2*py;\n end\n theta(1:3) = q;\n \n case 'kr5'\n %Given function will calculate inverse kinematics for KUKA KR5 robot\n \n % Equations are calculated and implemented by\n % Gautam Sinha\n % Autobirdz Systems Pvt. Ltd.\n % SIDBI Office,\n % Indian Institute of Technology Kanpur, Kanpur, Uttar Pradesh\n % 208016\n % India\n %email- gautam.sinha705@gmail.com\n \n \n % get the a1, a2 and a3-- link lenghts for link no 1,2,3\n L = robot.links;\n a1 = L(1).a;\n a2 = L(2).a;\n a3 = L(3).a;\n \n % Check wether wrist is spherical or not\n if ~robot.isspherical()\n error('wrist is not spherical')\n end\n \n % get d1,d2,d3,d4---- Link offsets for link no 1,2,3,4\n d1 = L(1).d;\n d2 = L(2).d;\n d3 = L(3).d;\n d4 = L(4).d;\n \n % Get the parameters from transformation matrix\n Ox = T(1,2);\n Oy = T(2,2);\n Oz = T(3,2);\n \n Ax = T(1,3);\n Ay = T(2,3);\n Az = T(3,3);\n \n Px = T(1,4);\n Py = T(2,4);\n Pz = T(3,4);\n \n \n \n % Set the parameters n1, n2 and n3 to get required configuration from\n % solution\n n1 = -1; % 'l'\n n2 = -1; % 'u'\n n4 = -1; % 'n'\n if ~isempty(strfind(configuration, 'l'))\n n1 = -1;\n end\n if ~isempty(strfind(configuration, 'r'))\n n1 = 1;\n end\n if ~isempty(strfind(configuration, 'u'))\n if n1 == 1\n n2 = 1;\n else\n n2 = -1;\n end\n end\n if ~isempty(strfind(configuration, 'd'))\n if n1 == 1\n n2 = -1;\n else\n n2 = 1;\n end\n end\n if ~isempty(strfind(configuration, 'n'))\n n4 = 1;\n end\n if ~isempty(strfind(configuration, 'f'))\n n4 = -1;\n end\n \n \n % Calculation for theta(1)\n r=sqrt(Px^2+Py^2);\n \n if (n1 == 1)\n theta(1)= atan2(Py,Px) + asin((d2-d3)/r);\n else\n theta(1)= atan2(Py,Px)+ pi - asin((d2-d3)/r);\n end\n \n % Calculation for theta(2)\n X= Px*cos(theta(1)) + Py*sin(theta(1)) - a1;\n r=sqrt(X^2 + (Pz-d1)^2);\n Psi = acos((a2^2-d4^2-a3^2+X^2+(Pz-d1)^2)/(2.0*a2*r));\n \n if ~isreal(Psi)\n warning('RTB:ikine6s:notreachable', 'point not reachable');\n theta = [NaN NaN NaN NaN NaN NaN];\n return\n end\n \n theta(2) = atan2((Pz-d1),X) + n2*Psi;\n \n % Calculation for theta(3)\n Nu = cos(theta(2))*X + sin(theta(2))*(Pz-d1) - a2;\n Du = sin(theta(2))*X - cos(theta(2))*(Pz-d1);\n theta(3) = atan2(a3,d4) - atan2(Nu, Du);\n \n % Calculation for theta(4)\n Y = cos(theta(1))*Ax + sin(theta(1))*Ay;\n M2 = sin(theta(1))*Ax - cos(theta(1))*Ay ;\n M1 = ( cos(theta(2)-theta(3)) )*Y + ( sin(theta(2)-theta(3)) )*Az;\n theta(4) = atan2(n4*M2,n4*M1);\n \n % Calculation for theta(5)\n Nu = -cos(theta(4))*M1 - M2*sin(theta(4));\n M3 = -Az*( cos(theta(2)-theta(3)) ) + Y*( sin(theta(2)-theta(3)) );\n theta(5) = atan2(Nu,M3);\n \n % Calculation for theta(6)\n Z = cos(theta(1))*Ox + sin(theta(1))*Oy;\n L2 = sin(theta(1))*Ox - cos(theta(1))*Oy;\n L1 = Z*( cos(theta(2)-theta(3) )) + Oz*( sin(theta(2)-theta(3)));\n L3 = Z*( sin(theta(2)-theta(3) )) - Oz*( cos(theta(2)-theta(3)));\n A1 = L1*cos(theta(4)) + L2*sin(theta(4));\n A3 = L1*sin(theta(4)) - L2*cos(theta(4));\n Nu = -A1*cos(theta(5)) - L3*sin(theta(5));\n Du = -A3;\n theta(6) = atan2(Nu,Du);\n \n \n otherwise\n error('RTB:ikine6s:badarg', 'Unknown solution type [%s]', robot.ikineType);\n end\n \n if ~isempty(theta)\n % Solve for the wrist rotation\n\n % we need to account for some random translations between the first and last 3\n % joints (d4) and also d6,a6,alpha6 in the final frame.\n\n T13 = robot.A(1:3, theta(1:3)); % transform of first 3 joints\n\n\n % T = T13 * Tz(d4) * R * Tz(d6) Tx(a5)\n Td4 = SE3(0, 0, L(4).d); % Tz(d4)\n Tt = SE3(L(6).a, 0, L(6).d) * SE3.Rx(L(6).alpha); % Tz(d6) Tx(a5) Rx(alpha6)\n\n R = inv(Td4) * inv(T13) * SE3(T) * inv(Tt);\n\n\n % the spherical wrist implements Euler angles\n\n if sol(3) == 1\n theta(4:6) = tr2eul(R, 'flip');\n else\n theta(4:6) = tr2eul(R);\n\n end\n if L(4).alpha > 0\n theta(5) = -theta(5);\n end\n\n % remove the link offset angles\n for j=1:robot.n %#ok<*AGROW>\n theta(j) = theta(j) - L(j).offset;\n end\n\n % stack the rows\n thetavec(k,:) = theta;\n else\n warning('RTB:ikine6s:notreachable', 'point not reachable');\n thetavec(k,:) = [NaN NaN NaN NaN NaN NaN];\n end\n end\nend\n\n% predicates to determine which kinematic solution to use\nfunction s = is_simple(L)\n alpha = [-pi/2 0 pi/2];\n s = all([L(2:3).d] == 0) && ...\n (all([L(1:3).alpha] == alpha) || all([L(1:3).alpha] == -alpha)) && ...\n all([L(1:3).isrevolute] == 1) && ...\n (L(1).a == 0);\nend\n\nfunction s = is_offset(L)\n alpha = [-pi/2 0 pi/2];\n s = (all([L(1:3).alpha] == alpha) || all([L(1:3).alpha] == -alpha)) && ...\n all([L(1:3).isrevolute] == 1);\nend\n\nfunction s = is_rrp(L)\n alpha = [-pi/2 pi/2 0];\n s = all([L(2:3).a] == 0) && ...\n (all([L(1:3).alpha] == alpha) || all([L(1:3).alpha] == -alpha)) && ...\n all([L(1:3).isrevolute] == [1 1 0]);\nend\n\nfunction s = is_puma(L)\n alpha = [pi/2 0 -pi/2];\n s = (L(2).d == 0) && (L(1).a == 0) && ...\n (L(3).d ~= 0) && (L(3).a ~= 0) && ...\n all([L(1:3).alpha] == alpha) && ...\n all([L(1:3).isrevolute] == 1);\nend\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/@SerialLink/ikine6s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3993906246297293}}
{"text": "function Q = vbpcamv(Y, d, varargin)\n% Modified RPPCA by Jaakko Luttinen\n% Uses separate outlier models for each observed signal.\n% p(y|W,x,mu,u,tau) = N(y | W*x+mu, diag(1/u*1/tau))\n% Uses hierarchical models and variational learning.\n%\n% If you have troubles with bad minima, you may want to try changing the\n% time when the algorithm starts to update the hyperparameters\n% (startupdatehyper) and/or to rotate (startrotate).\n\n% Last updated 13th February 2009, Jaakko Luttinen\n\nopts = struct( ...\n 'init', [],...\n 'prior', [], ...\n 'hiermean', false, ...\n 'rotate', true, ...\n 'commonnoise', true, ...\n 'startrotate', 1, ...\n 'startupdatehyper', 1, ...\n 'autosavetime', 0,...\n 'autosavefile', 'vbpcamv_autosave',...\n 'testset', [], ...\n 'fixw', false, ...\n 'maxiters', 1000, ...\n 'convergence', eps);\n\n[ opts, errmsg, wrnmsg ] = argschk( opts, varargin{:} );\nif ~isempty(errmsg), error( errmsg ), end\nif ~isempty(wrnmsg), warning( wrnmsg ), end\n\n[m,n] = size(Y);\n\n% Missing values\nif issparse(Y)\n Obs = Y~=0; %spones(Y);\nelse\n Obs = ~isnan(Y);\nend\n[ObsI, ObsJ] = find(Obs);\n\n%%%%%%%%%%%%%%%%%%%\n%% INITIALIZATION\n\nnmv = sum(Obs,2);\n\n% NAMING CONVENTION:\n% variables are named without '_': e.g. a->tau->mu ==> ataumu\n% but the values of posterior distribution parameters are named with one\n% '_': e.g. a->tau->mu ==> a_taumu\n% So, priors (or hyperparameter variables) have no '_'. Understand the\n% difference!\n% But for clarity mu_W is just W and mu_X is just X and so on. That is,\n% plain variable name (W,X,mu,tau,logtau,U,logU) refers to posterior\n% expectation if there is no naming conflict.\n\n\n% Mean (mu)\n% $$$ mumumu = 0; % prior for hierarchical stuff\n% $$$ taumumu = 1e-5; % prior for hierarchical stuff\nv_mumu = 0;\nataumu = 1e-3; % prior for hierarchical stuff\nbtaumu = 1e-3; % prior for hierarchical stuff\nmumu = 0; % init posterior or prior if no hierarchical mean\ntaumu = 1e-6; % init posterior or prior if no hierarchical mean\nv_mu = 1e0*ones(m,1); % init posterior\nmu = zeros(m,1); % init posterior\n \n% Loading matrix (W)\n%aw = 1e-16; % prior\n%bw = 1e-13; % prior\naw = 1e-10; % prior\nbw = 1e-5; % prior\na_w = aw * ones(1,d); % init size\nb_w = bw * ones(1,d); % init size\nw = 1e-6 * ones(1,d); % init posterior\nlogw = nan * ones(1,d); % init size\nW = orth(randn(m,d)); % init posterior\nCovW = 1e-0*repmat(eye(d),[1,1,m]); % init posterior\nvarW = nan*ones(m,d); % init size\n\n% Observation noise\natau = 1e-4; % prior\nbtau = 1e-4; % prior\na_tau = nan * ones(m,1);\nb_tau = nan * ones(m,1);\ntau = 1e2 * ones(m,1); % init posterior (THIS SEEMS TO BE IMPORTANT!!!)\n%tau = 1./varmv(Y,2) * (m^2)/((m-d)^2) % adhoc init posterior\nlogtau = nan * ones(m,1); % init size\n \n% Outlier parameters\n% $$$ nu = 10 * ones(m,1); % variable init\n% $$$ a_U = nan * ones(m,n); % init size\n% $$$ b_U = nan * ones(m,n); % init size\nU = ones(m,n); % init posterior\n% $$$ logU = nan * zeros(m,n); % init size\n\n% Initialize sizes\nX = nan * zeros(d,n); % init size\nSv = cell(n,1);\nSv(:) = {nan*zeros(d,d)};\nCovX = nan*zeros(d,d,n);\nXX = nan*zeros(d,d,n);\nUXX = nan*zeros(d,d,m);\n\n\n% Prior information\nif isstruct(opts.prior)\n if isfield(opts.prior, 'mumumu')\n mumumu(1) = opts.prior.mumumu\n end\n if isfield(opts.prior, 'taumumu')\n taumumu(1) = opts.prior.taumumu\n end\n if isfield(opts.prior, 'ataumu')\n ataumu(1) = opts.prior.ataumu\n end\n if isfield(opts.prior, 'btaumu')\n btaumu(1) = opts.prior.btaumu\n end\n if isfield(opts.prior, 'aw')\n aw(1) = opts.prior.aw\n end\n if isfield(opts.prior, 'bw')\n bw(1) = opts.prior.bw\n end\n if isfield(opts.prior, 'atau')\n atau(1) = opts.prior.atau\n end\n if isfield(opts.prior, 'btau')\n btau(1) = opts.prior.btau\n end\nend\n\n% Use given initialization (size matching is checked by using ':' )\nif isstruct(opts.init)\n if isfield(opts.init, 'W')\n W(:,:) = opts.init.W;\n fprintf('Using old W.\\n');\n end\n if isfield(opts.init, 'CovW')\n CovW(:,:,:) = opts.init.CovW;\n fprintf('Using old CovW.\\n');\n end\n if isfield(opts.init, 'w')\n w(:) = opts.init.w\n fprintf('Using old w.\\n');\n end\n if isfield(opts.init, 'X')\n X(:,:) = opts.init.X;\n fprintf('Using old X.\\n');\n end\n if isfield(opts.init, 'CovX')\n CovX(:,:,:) = opts.init.CovX;\n fprintf('Using old CovX.\\n');\n end\n if isfield(opts.init, 'Sv')\n Sv(:) = opts.init.Sv;\n fprintf('Using old Sv.\\n');\n end\n if isfield(opts.init, 'mu')\n mu(:) = opts.init.mu;\n fprintf('Using old mu.\\n');\n end\n if isfield(opts.init, 'v_mu')\n v_mu(:) = opts.init.v_mu;\n fprintf('Using old v_mu.\\n');\n end\n if isfield(opts.init, 'mumu')\n mumu(1) = opts.init.mumu;\n fprintf('Using old mumu.\\n');\n end\n if isfield(opts.init, 'taumu')\n taumu(1) = opts.init.taumu;\n fprintf('Using old taumu.\\n');\n end\n if isfield(opts.init, 'tau')\n tau(:) = opts.init.tau;\n fprintf('Using old tau.\\n');\n end\n if isfield(opts.init, 'nu')\n nu(:) = opts.init.nu;\n fprintf('Using old nu.\\n');\n end\n if isfield(opts.init, 'U')\n U(:,:) = opts.init.U;\n fprintf('Using old U.\\n');\n end\nend\n\nWW = zeros(d,d,m);\nfor i=1:m\n WW(:,:,i) = W(i,:)'*W(i,:) + CovW(:,:,i);\nend\n\n% Log-likelihood\nlogP = -Inf;\n\nIm = eye(m);\nId = eye(d);\n\nlastsave = now;\n\nN = 1:n;\nvM = 1:m;\nm_mv = sum(Obs,1);\nn_mv = sum(Obs,2);\nnm_mv = sum(Obs(:)); % number of observations\n\nlog2pi = log(2*pi);\n\noldcosts = -inf;\n\n% Monitor the overall time of the iteration\nstarttime = cputime;\nduration = nan*zeros(opts.maxiters,1);\nrmse = nan*zeros(opts.maxiters,1);\nrmse_test = nan*zeros(opts.maxiters,1);\n\ncost = nan*zeros(opts.maxiters,1);\nfor k=1:opts.maxiters\n \n itertime = cputime;\n \n % This is used to monitor the rotation of the subspace after each step\n W_old = W;\n \n % Update X\n for j=1:n\n imv = Obs(:,j);\n UTau = diag(U(imv,j).*tau(imv));\n UWWTau = 0;\n for i=vM(imv)\n UWWTau = UWWTau + U(i,j)*tau(i) * WW(:,:,i);\n end\n CovX(:,:,j) = inv(UWWTau + Id);\n X(:,j) = CovX(:,:,j) * W(imv,:)' * UTau * (Y(imv,j)-mu(imv)); \n XX(:,:,j) = CovX(:,:,j) + X(:,j)*X(:,j)';\n Sv{j} = CovX(:,:,j); % only for backward compatibility..\n end\n\n for i=1:m\n jmv = Obs(i,:);\n\n % Update sum_j()\n UXX(:,:,i) = 0;\n for j=N(jmv) % sum over observed time instances\n UXX(:,:,i) = UXX(:,:,i) + U(i,j)*XX(:,:,j);%(CovX(:,:,j) + X(:,j)*X(:,j)');\n end\n\n % Update W\n CovW(:,:,i) = inv(UXX(:,:,i)*tau(i) + diag(w));\n W(i,:) = (U(i,jmv).*(Y(i,jmv)-mu(i))*X(:,jmv)') * CovW(:,:,i) * tau(i);\n WW(:,:,i) = W(i,:)'*W(i,:) + CovW(:,:,i);\n \n % Update mu\n v_mu(i) = 1 / (taumu + sum(U(i,jmv))*tau(i));\n mu(i) = v_mu(i) * (taumu*mumu + U(i,jmv)*(Y(i,jmv)-W(i,:)*X(:,jmv))'*tau(i));\n\n end\n \n % Rotate\n % THINK/TODO: WHAT WOULD BE A GOOD TIME TO START ROTATING??\n % (rotating too early may lead to bad local minima and not rotating\n % makes converging very slow) should one measure how \"converged\" the\n % loglikelihood is and then decide whether to start rotate?\n if opts.rotate && k>=opts.startrotate\n% $$$ before = trace( sum(CovX,3) * sum(CovW,3) )\n [W,CovW,X,Sv,CovX,mu] = orthogonalize(W,CovW,X,Sv,CovX,mu,opts.fixw,tau,Obs);\n% $$$ after = trace( sum(CovX,3) * sum(CovW,3) )\n% [W,CovW,X,Sv,CovX,mu] = orthogonalize_TEST(W,CovW,X,Sv,CovX,mu,tau(1)); false\n% [W,CovW,X,CovX,mu] = RotateToPCA(W,CovW,X,CovX,mu);\n end\n\n \n for i=1:m\n jmv = Obs(i,:); % observed\n \n WW(:,:,i) = W(i,:)'*W(i,:) + CovW(:,:,i);\n varW(i,:) = diag(CovW(:,:,i));\n \n % Update sum_j()\n UXX(:,:,i) = 0;\n for j=N(jmv) % sum over observed time instances\n UXX(:,:,i) = UXX(:,:,i) + U(i,j)*(CovX(:,:,j) + X(:,j)*X(:,j)');\n end\n\n % Update tau\n UWXXW = sum(sum( WW(:,:,i) .* UXX(:,:,i) ));\n a_tau(i) = atau + 0.5*sum(jmv);\n b_tau(i) = btau ...\n + 0.5 * (UWXXW + ...\n sum(-2*W(i,:)*X(:,jmv)*(U(i,jmv).*(Y(i,jmv)-mu(i)))') + ...\n sum(U(i,jmv).*(Y(i,jmv)-mu(i)).^2) + ...\n sum(U(i,jmv)*v_mu(i)));\n \n end\n \n % \"AD HOC\"(?): Use common variance\n if opts.commonnoise\n a_tau(:) = sum(a_tau-atau) + atau;\n b_tau(:) = sum(b_tau-btau) + btau;\n end\n tau = a_tau./b_tau;\n logtau = psi(a_tau) - log(b_tau);\n % TODO: DEBUGGING: USE ML ESTIMATE\n% $$$ logtau = log(tau);\n\n % Update hyperparameters for mu\n if ~opts.hiermean\n logtaumu = log(taumu);\n else\n a_taumu = ataumu + 0.5*m;\n b_taumu = btaumu + 0.5*sum( (mu-mumu).^2 + v_mu + v_mumu);\n taumu = a_taumu ./ b_taumu; % posterior mean of accuracy hyperparameter\n logtaumu = psi(a_taumu) - log(b_taumu);\n end\n\n % Update hyperparameter for W (you can try to start updating these\n % hyperparameters only after some iteration if some problems seem to\n % appear.)\n if ~opts.fixw\n if k >= opts.startupdatehyper\n a_w(:) = aw + 0.5*m;\n b_w(:) = bw + 0.5*sum(W.^2 + varW, 1);\n end\n w = a_w ./ b_w; % posterior mean of precision hyperparameter\n logw = psi(a_w) - log(b_w);\n else\n logw = log(w);\n end\n \n % Change of the principal subspace (in radians)\n angle = subspace(W,W_old);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Calculate lower bound of the log-likelihood\n\n % Cost from Y\n cost_Y = 0;\n for j=1:n\n imv = Obs(:,j);\n for i=vM(imv)\n mean_muY = W(i,:)*X(:,j)+mu(i);\n var_muY = W(i,:)*CovX(:,:,j)*W(i,:)' + X(:,j)'*CovW(:,:,i)*X(:,j) ...\n + sum(sum( CovX(:,:,j).*CovW(:,:,i) )) + v_mu(i);\n tauY = tau(i);\n logtauY = logtau(i);\n cost_Y = cost_Y + cost_gaussian(Y(i,j),[], mean_muY,var_muY, ...\n tauY,logtauY);\n end\n end\n \n % Cost from W\n cost_W = 0;\n for i=1:m\n cost_W = cost_W + cost_gaussian(W(i,:)',CovW(:,:,i), 0,0, w',logw');\n end\n \n % Cost from X\n cost_X = 0;\n for j=1:n\n cost_X = cost_X + cost_gaussian(X(:,j),CovX(:,:,j), 0,0, 1,0);\n end\n \n % Cost from mu\n cost_mu = cost_gaussian(mu,diag(v_mu), mumu,v_mumu, taumu,logtaumu);\n\n % Cost from tau\n if opts.commonnoise\n cost_tau = cost_gamma(tau(1),logtau(1),a_tau(1),b_tau(1),atau,btau);\n else\n cost_tau = sum(cost_gamma(tau,logtau,a_tau,b_tau,atau,btau));\n end\n \n % Cost from w\n if ~opts.fixw\n cost_w = sum(cost_gamma(w,logw,a_w,b_w,aw,bw));\n else\n cost_w = 0;\n end\n \n if opts.hiermean\n cost_taumu = cost_gamma(taumu,logtaumu,a_taumu,b_taumu,ataumu,btaumu);\n end\n \n oldlogP = logP;\n \n % Lower bound of loglikelihood\n logP = cost_Y + cost_W + cost_X + cost_mu + cost_tau + cost_w;\n %logP = cost_Y;\n costs = [cost_Y; cost_W; cost_X; cost_mu; cost_tau; cost_w];\n \n cost(k) = logP;\n \n % Show progress\n time = cputime - itertime;\n if k > 1\n duration(k) = duration(k-1) + time;\n else\n duration(1) = time;\n end\n fprintf('Step %d: loglike=%e, angle=%e (%f seconds)\\n', ...\n k, logP, angle, time);\n \n % Debugging..\n if logP < oldlogP\n% diff_costs = costs - oldcosts\n% error('Log-likelihood bound not improved! Bug in code or likelihood?');\n warning('Log-likelihood bound decreased! Bug in code or likelihood?');\n end\n oldcosts = costs;\n \n % RMSE\n Yh = W*X + repmat(mu, 1,n);\n err = Y-Yh;\n err = err(~isnan(err));\n rmse(k) = sqrt( mean(err(:).^2) );\n if ~isempty(opts.testset)\n err = opts.testset-Yh;\n err = err(~isnan(err));\n rmse_test(k) = sqrt( mean(err(:).^2) );\n end\n\n % Check whether to save the results\n if (now-lastsave)*3600*24 >= opts.autosavetime && opts.autosavetime > 0\n fprintf('Saving to %s...', opts.autosavefile);\n loglikelihood = logP;\n if opts.hiermean\n save(opts.autosavefile, 'W','CovW','w','a_w','b_w','X','CovX','Sv', ...\n 'mu','v_mu','mumu','v_mumu','taumu','a_taumu','b_taumu','tau', ...\n 'a_tau','b_tau','U','a_U','b_U','nu','loglikelihood');\n else\n save(opts.autosavefile, 'W','CovW','w','a_w','b_w','X','CovX','Sv', ...\n 'mu','v_mu','tau', 'a_tau','b_tau', 'loglikelihood', 'cost', ...\n 'duration', 'rmse', 'rmse_test');\n end\n lastsave = now;\n fprintf(' done.\\n');\n end\n \n% $$$ if angle < 1e-14\n% $$$ fprintf('Stopping iteration: only minor change in subspace\\n');\n% $$$ break\n% $$$ end\n improvement = abs((logP - oldlogP) / logP);\n if improvement < opts.convergence && k > opts.startupdatehyper\n fprintf('Stopping iteration: only minor improvement in loglikelihood\\n');\n break\n end\n\nend\n\nfprintf('Saving to %s...', opts.autosavefile);\nloglikelihood = logP;\nif opts.hiermean\n save(opts.autosavefile, 'W','CovW','w','a_w','b_w','X','CovX','Sv', ...\n 'mu','v_mu','mumu','v_mumu','taumu','a_taumu','b_taumu','tau', ...\n 'a_tau','b_tau','U','a_U','b_U','nu','loglikelihood');\nelse\n save(opts.autosavefile, 'W','CovW','w','a_w','b_w','X','CovX','Sv', ...\n 'mu','v_mu','tau', 'a_tau','b_tau', 'loglikelihood', 'cost', ...\n 'duration', 'rmse', 'rmse_test');\nend\nfprintf(' done.\\n');\n\n% Results as a struct if desired\nif true %nargout == 1\n results.W = W;\n results.CovW = CovW;\n results.w = w;\n results.a_w = a_w;\n results.b_w = b_w;\n results.X = X;\n results.CovX = CovX;\n results.Sv = Sv;\n results.mu = mu;\n results.v_mu = v_mu;\n if opts.hiermean\n results.mumu = mumu;\n results.v_mumu = v_mumu;\n results.taumu = taumu;\n results.a_taumu = a_taumu;\n results.b_taumu = b_taumu;\n end\n results.tau = tau;\n results.a_tau = a_tau;\n results.b_tau = b_tau;\n% $$$ results.U = U;\n% $$$ results.a_U = a_U;\n% $$$ results.b_U = b_U;\n% $$$ results.nu = nu;\n results.loglikelihood = logP;\n results.cost = cost;\n results.time = duration;\n Q = results;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction c = cost_gaussian(x,Covx,mu,Covmu,tau,logtau)\n% c = cost_gaussian(x,Covx,mu,Covmu,tau,logtau)\n%\n% Calculates the difference between - \n% where expectation is over q(X).\n%\n% A lower bound for a Gaussian:\n% p(X) = N(MU,1/TAU)\n% q(X) = N(x,Covx)\n% \n% Rest of the parameters are defined as:\n% q(MU) = N(mu,Covmu)\n% = tau\n% = logtau\n%\n% If Covx==[], then the term is not calculated.\n% This is useful when X is, e.g., observations.\n\n\nc = 0;\n\n% Cost from q-posterior\nif ~isempty(Covx)\n entropy = entropy_gaussian(Covx);\n c = entropy;\nelse\n Covx = 0;\nend\n\n% Cost from prior\nerr2 = ((x-mu).^2 + diag(Covx) + diag(Covmu));\nc = c + 0.5 * sum( -log(2*pi) + logtau - tau .* err2 );\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction c = cost_gamma(x,logx,apost,bpost,aprior,bprior)\n% A lower bound for a Gamma distributed X:\n% p(X) = G(aprior,bprior)\n% q(X) = G(apost,bpost)\n% = x\n% = logx\n\n% Cost from prior\nc = aprior*log(bprior) - gammaln(aprior) + (aprior-1)*logx - bprior*x;\n% Cost from q-posterior\nc = c + entropy_gamma(apost,bpost);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction H = entropy_gaussian(Cov)\n% Cov is covariance matrix\nd = size(Cov,1);\n\nlog2pi = log(2*pi);\n%H = 0;\n\n%for j=1:size(Cov,3)\nL = chol(Cov);\nH = d/2*log2pi + 0.5*2*logdettri(L) + d/2;\n%end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction H = entropy_gamma(a,b)\n% a is shape, b is inverse scale\n\nH = a - log(b) + gammaln(a) - (a-1).*psi(a);\n%H = sum(H(:));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [ A, Av, S, Sv, mu ] = ...\n RotateToPCA( A, Av, S, Sv, mu);\n\nn1 = size(A,1);\nn2 = size(S,2);\n\n% TODO: Take into account the prior for Mu, A???\nmS = mean(S,2);\ndMu = A*mS;\nS = S - repmat(mS,1,n2);\nmu = mu + dMu;\n\ncovS = S*S';\nfor j = 1:n2\n covS = covS + Sv(:,:,j);\nend\n\nR = 1;\n\n% w.r.t. S\ncovS = covS / n2;\n[VS,D] = eig(covS);\nRA = VS*sqrt(D);\nA = A*RA;\ncovA = A'*A;\nfor i = 1:n1\n Av(:,:,i) = RA'*Av(:,:,i)*RA;\n covA = covA + Av(:,:,i);\nend\nR = diag(1./sqrt(diag(D)))*VS';\n\n% $$$ % w.r.t. A\n% $$$ covA = covA / n1;\n% $$$ [VA,DA] = eig(covA);\n% $$$ [DA,I] = sort( -diag(DA) );\n% $$$ DA = -DA;\n% $$$ VA = VA(:,I);\n% $$$ A = A*VA;\n% $$$ for i = 1:n1\n% $$$ Av(:,:,i) = VA'*Av(:,:,i)*VA;\n% $$$ end\n% $$$ R = VA'*R;\n\nS = R*S;\nfor j = 1:length(Sv)\n Sv(:,:,j) = R*Sv(:,:,j)*R';\nend\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [W,CovW,X,Sv,CovX,mu] = orthogonalize(W,CovW,X,Sv,CovX,mu,fixw,tau,Obs)\n[m,c] = size(W);\nn = size(X,2);\n\nWW = W'*W + sum(CovW,3);\n\n% $$$ old_recon = W*X + repmat(mu,1,n);\n\n% Use ML zero mean (mu should be updated after this function!!) ..\nif false\n disp('Using complicated but exact mean translation');\n tau = reshape(tau,[1,1,m]);\n nom = 0;\n denom = 0;\n I = eye(c);\n for j=1:n\n imv = Obs(:,j);\n tmp = I + sum(bsxfun(@times,tau(1,1,imv),CovW(:,:,imv)),3);\n nom = nom + tmp * X(:,j);\n denom = denom + tmp;\n end\n dmu = denom \\ nom;\nelse\n dmu = mean(X,2);\nend\n% .. or my analytic zero mean with proper fix to mu:\n% $$$ dmu = inv(n*eye(c)+taumu*WW) * (sum(X,2) + taumu*W'*(mumu-mu));\n\n% Move bias\nX = X - repmat(dmu,1,n);\nmu = mu + W*dmu;\n% $$$ nobiasmove = true\n\nQx = 1;\n\n% Whiten w.r.t. X\nXX = X*X' + sum(CovX,3);\nif fixw\n [Vx,Dx,tmp] = svd(XX/(n-m)); % USE THIS IF FIXED w ??\nelse\n [Vx,Dx,tmp] = svd(XX/n);\nend\nQx = diag(1./sqrt(diag(Dx))) * Vx';\nQw = Vx*sqrt(Dx);\nW = W * Qw;\nfor i=1:size(CovW,3)\n CovW(:,:,i) = Qw'*CovW(:,:,i)*Qw;\nend\nX = Qx * X;\nfor j = 1:size(CovX,3)\n Sv{j} = Qx*Sv{j}*Qx';\n CovX(:,:,j) = Qx*CovX(:,:,j)*Qx';\nend\n\n% Check that XX is really whitened! (because of numerical issues!!)\nXX = X*X' + sum(CovX,3);\nif fixw\n [Vx,Dx,tmp] = svd(XX/(n-m)); % USE THIS IF FIXED w ??\nelse\n [Vx,Dx,tmp] = svd(XX/n);\nend\nif Dx(1) > 1.1\n warning('Needs to whiten X again. See vbpcamv->orthogonalize');\n % Whiten w.r.t. X AGAIN\n Qx = diag(1./sqrt(diag(Dx))) * Vx';\n Qw = Vx*sqrt(Dx);\n W = W * Qw;\n for i=1:size(CovW,3)\n CovW(:,:,i) = Qw'*CovW(:,:,i)*Qw;\n end\n X = Qx * X;\n for j = 1:size(CovX,3)\n Sv{j} = Qx*Sv{j}*Qx';\n CovX(:,:,j) = Qx*CovX(:,:,j)*Qx';\n end\nend\n\nQx = 1;\n% Diagonalize w.r.t. W\nWW = W'*W + sum(CovW,3);\n[Vw,Dw,tmp] = svd(WW);\n%[Dw,I] = sort(diag(Dw), 'descend');\n%Vw = Vw(:,I);\nQx = Vw' * Qx;\nQw = Vw;\nW = W * Qw;\nfor i=1:size(CovW,3)\n CovW(:,:,i) = Qw'*CovW(:,:,i)*Qw;\nend\nX = Qx * X;\nfor j = 1:size(CovX,3)\n Sv{j} = Qx*Sv{j}*Qx';\n CovX(:,:,j) = Qx*CovX(:,:,j)*Qx';\nend\n\n% $$$ xx = X*X' + sum(CovX,3)\n% $$$ ww = W'*W + sum(CovW,3)\n\n% $$$ new_recon = W*X + repmat(mu,1,n);\n% $$$ \n% $$$ mse = mean((old_recon(:) - new_recon(:)).^2)\n\nreturn\n% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% $$$ function [W,CovW,X,Sv,CovX,mu] = orthogonalize_TEST(W,CovW,X,Sv,CovX,mu,tau)\n% $$$ [m,c] = size(W);\n% $$$ n = size(X,2);\n% $$$ \n% $$$ WW = W'*W + sum(CovW,3);\n% $$$ \n% $$$ old_recon = W*X + repmat(mu,1,n);\n% $$$ \n% $$$ % Use ML zero mean (mu should be updated after this function!!) ..\n% $$$ % $$$ dmu = mean(X,2);\n% $$$ % $$$ tau*sum(CovW,3)\n% $$$ dmu = inv(n*eye(c)+tau*n*sum(CovW,3)) * (sum((eye(c)+tau*sum(CovW,3))*X, 2));\n% $$$ %(dmu2-dmu)./dmu\n% $$$ % .. or my analytic zero mean with proper fix to mu:\n% $$$ % $$$ dmu = inv(n*eye(c)+taumu*WW) * (sum(X,2) + taumu*W'*(mumu-mu));\n% $$$ \n% $$$ % Move bias\n% $$$ X = X - repmat(dmu,1,n);\n% $$$ mu = mu + W*dmu;\n% $$$ \n% $$$ Qx = 1;\n% $$$ \n% $$$ % Whiten w.r.t. X\n% $$$ XX = X*X' + sum(CovX,3);\n% $$$ [Vx,Dx] = eig(XX/n);\n% $$$ %[Vx,Dx] = eig(XX/(n+m));\n% $$$ %[Vx,Dx] = eig(XX/(n-m));\n% $$$ Qx = diag(1./sqrt(diag(Dx))) * Vx';\n% $$$ Qw = Vx*sqrt(Dx);\n% $$$ W = W * Qw;\n% $$$ for i=1:size(CovW,3)\n% $$$ CovW(:,:,i) = Qw'*CovW(:,:,i)*Qw;\n% $$$ end\n% $$$ \n% $$$ % Whiten w.r.t. W\n% $$$ WW = W'*W + sum(CovW,3);\n% $$$ [Vw,Dw] = eig(WW);\n% $$$ [Dw,I] = sort(diag(Dw), 'descend');\n% $$$ Vw = Vw(:,I);\n% $$$ Qx = Vw' * Qx;\n% $$$ Qw = Vw;\n% $$$ W = W * Qw;\n% $$$ for i=1:size(CovW,3)\n% $$$ CovW(:,:,i) = Qw'*CovW(:,:,i)*Qw;\n% $$$ end\n% $$$ \n% $$$ X = Qx * X;\n% $$$ for j = 1:size(CovX,3)\n% $$$ Sv{j} = Qx*Sv{j}*Qx';\n% $$$ CovX(:,:,j) = Qx*CovX(:,:,j)*Qx';\n% $$$ end\n% $$$ \n% $$$ new_recon = W*X + repmat(mu,1,n);\n% $$$ \n% $$$ mse = mean((old_recon(:) - new_recon(:)).^2);\n% $$$ \n% $$$ return\n% $$$ \n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/pca/vbpcamv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210897, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.399256256323067}}
{"text": "function EmergencyTrajectory = calcEmergencyVelocityProfile_veldep(TargetTrajectory, ...\n drag_coefficient, roh_air, vehiclemass_kg, ...\n P_VDC_AccLimits_v_mps, P_VDC_AccLimits_ax_mps2, P_VDC_AccLimits_ay_mps2)\n\n% Authors: Alexander Wischnewski\n%\n% Description: \n% calculates a brake velocity profile to a given target trajectory to generate a reasonable\n% emergency backup\n\n% Inputs:\n% TargetTrajectory Trajectory to be checked (see tests for format)\n% drag_coefficient Vehicle drag coefficient\n% roh_air air density \n% vehiclemass_kg vehicle mass \n% P_VDC_AccLimits_v_mps: Acceleration limit map - velocity interpolation points\n% P_VDC_AccLimits_ax_mps2: Acceleration limit map - long. acc. limits\n% P_VDC_AccLimits_ay_mps2: Acceleration limit map - lat. acc. limits\n%\n% Outputs: \n% EmergencyTrajectory True if trajectory complies with all specs \n\n% copy target trajectory\nEmergencyTrajectory = TargetTrajectory; \n% only if the trajectory is a driving trajectory \nif(EmergencyTrajectory.v_mps(1) > 1) \n % calculate new velocity profile starting with the fifth element to ensure that the trajectory\n % does not begin prior to switching on it as this might cause serious issues\n for i = 6:1:50\n % distance to next point \n dS = double(EmergencyTrajectory.s_loc_m(i) - EmergencyTrajectory.s_loc_m(i-1)); \n % update acceleration limits \n EmergencyTrajectory.ax_lim_mps2(i-1) = interp1(P_VDC_AccLimits_v_mps, P_VDC_AccLimits_ax_mps2, EmergencyTrajectory.v_mps(i-1)); \n EmergencyTrajectory.ay_lim_mps2(i-1) = interp1(P_VDC_AccLimits_v_mps, P_VDC_AccLimits_ay_mps2, EmergencyTrajectory.v_mps(i-1)); \n % calculate allowed longitudinal deceleration \n ax_mps2 = -(1 - abs(double(EmergencyTrajectory.kappa_radpm(i-1))*double(EmergencyTrajectory.v_mps(i-1)).^2/EmergencyTrajectory.ay_lim_mps2(i-1)))*EmergencyTrajectory.ax_lim_mps2(i-1); \n % add acceleration from drag \n ax_mps2 = ax_mps2 - 0.5*drag_coefficient*roh_air*EmergencyTrajectory.v_mps(i-1)^2/vehiclemass_kg;\n % calculate time needed to travel there using pq formula \n p = 2*EmergencyTrajectory.v_mps(i-1)/ax_mps2; \n q = -2*dS/ax_mps2;\n % check if the solution is still valid\n if((p/2)^2 > q && EmergencyTrajectory.v_mps(i-1) > 0.2)\n v_next = (-p/2 - sqrt((p/2)^2 - q))*ax_mps2 + EmergencyTrajectory.v_mps(i-1); \n else\n v_next = 0; \n end\n % set calculated speed and start next step with this speed\n EmergencyTrajectory.v_mps(i) = single(v_next);\n EmergencyTrajectory.ax_mps2(i-1) = ax_mps2; \n end\n % set final acceleration to value of before\n % use a lot less as this might lead to issues with the safety checks otherwise\n % speed should be zero here anyway\n EmergencyTrajectory.ax_mps2(50) = 0.5*EmergencyTrajectory.ax_mps2(49); \nelse\n % set speeds and acceleration to zero if the initial planning speed is too slow for driving\n EmergencyTrajectory.v_mps = zeros(50, 1); \n EmergencyTrajectory.ax_mps2 = zeros(50, 1); \nend\n", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/softwareEmulation/src/calcEmergencyVelocityProfile_veldep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.399192629849348}}
{"text": "function [pnt, tri] = triangulate_seg(seg, npnt, origin)\n\n% TRIANGULATE_SEG constructs a triangulation of the outer surface of a\n% segmented volume. It starts at the center of the volume and projects the\n% vertices of an evenly triangulated sphere onto the outer surface. The\n% resulting surface is star-shaped from the origin of the sphere.\n%\n% Use as\n% [pnt, tri] = triangulate_seg(seg, npnt, origin)\n%\n% Input arguments:\n% seg = 3D-matrix (boolean) containing segmented volume. If not boolean\n% seg = seg(~=0);\n% npnt = requested number of vertices\n% origin = 1x3 vector specifying the location of the origin of the sphere\n% in voxel indices. This argument is optional. If undefined, the\n% origin of the sphere will be in the centre of the volume.\n%\n% Output arguments:\n% pnt = Nx3 matrix of vertex locations\n% tri = Mx3 matrix of triangles\n%\n% Seg will be checked for holes, and filled if necessary. Also, seg will be\n% checked to consist of a single boolean blob. If not, only the outer surface\n% of the largest will be triangulated. SPM is used for both the filling and\n% checking for multiple blobs.\n%\n% See also KSPHERE\n\n% Copyright (C) 2005-2012, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% impose it to be boolean\nseg = (seg~=0);\ndim = size(seg);\nlen = ceil(sqrt(sum(dim.^2))/2);\n\nif ~any(seg(:))\n ft_error('the segmentation is empty')\nend\n\n% define the origin if it is not provided in the input arguments\nif nargin<3\n origin(1) = dim(1)/2;\n origin(2) = dim(2)/2;\n origin(3) = dim(3)/2;\nend\n\n% ensure that the seg consists of only one filled blob.\n% if not filled: throw a warning and fill\n% if more than one blob: throw a warning and use the biggest\n\n% look for holes\nseg = volumefillholes(seg);\n\n% ensure that SPM is available, needed for spm_bwlabel\nft_hastoolbox('spm8up', 3) || ft_hastoolbox('spm2', 1);\n\n% look for >1 blob\n[lab, num] = spm_bwlabel(double(seg), 26);\nif num>1,\n ft_warning('the segmented volume consists of more than one compartment, using only the biggest one for the segmentation');\n\n for k = 1:num\n n(k) = sum(lab(:)==k);\n end\n [m,ix] = max(n);\n seg(lab~=ix) = false;\nend\n\n% start with a unit sphere with evenly distributed vertices\n[pnt, tri] = mesh_sphere(npnt, 'ksphere');\n\nishollow = false;\n\nfor i=1:npnt\n % construct a sampled line from the center of the volume outward into the direction of the vertex\n lin = (0:0.5:len)' * pnt(i,:);\n lin(:,1) = lin(:,1) + origin(1);\n lin(:,2) = lin(:,2) + origin(2);\n lin(:,3) = lin(:,3) + origin(3);\n % round the sampled line towards the nearest voxel indices, which allows\n % a quick nearest-neighbour interpolation/lookup\n lin = round(lin);\n % exclude indices that do not lie within the volume\n sel = lin(:,1)<1 | lin(:,1)>dim(1) | ...\n lin(:,2)<1 | lin(:,2)>dim(2) | ...\n lin(:,3)<1 | lin(:,3)>dim(3);\n lin = lin(~sel,:);\n sel = sub2ind(dim, lin(:,1), lin(:,2), lin(:,3));\n\n % interpolate the segmented volume along the sampled line\n int = seg(sel);\n\n % the value along the line is expected to be 1 at first and then drop to 0\n % anything else suggests that the segmentation is hollow\n ishollow = any(diff(int)==1);\n\n % find the last sample along the line that is inside the segmentation\n sel = find(int, 1, 'last');\n % this is a problem if sel is empty. If so, use the edge of the volume\n if ~isempty(sel)\n % take the last point inside and average with the first point outside\n pnt(i,:) = lin(sel,:);\n else\n % take the edge\n pnt(i,:) = lin(end,:);\n end\nend\n\nif ishollow\n % this should not have hapened, especially not after filling the holes\n ft_warning('the segmentation is not star-shaped, please check the surface mesh');\nend\n\n% undo the shift of the origin from where the projection is done\n% pnt(:,1) = pnt(:,1) - origin(1);\n% pnt(:,2) = pnt(:,2) - origin(2);\n% pnt(:,3) = pnt(:,3) - origin(3);\n\n% fast unconditional re-implementation of the standard MATLAB function\nfunction [s] = sub2ind(dim, i, j, k)\ns = i + (j-1)*dim(1) + (k-1)*dim(1)*dim(2);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/private/triangulate_seg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3991353238454252}}
{"text": "%% Import from VPSC\n%\n%%\n% is a crystal plasticity code\n% originally written by Ricardo Lebensohn and Carlos Tome from Los Alamos\n% National Laboratory - USA.\n% \n% Original code can be requested to lebenso@lanl.gov\n%\n% https://public.lanl.gov/lebenso/\n%\n%% Import the orientations generated by VPSC\n%\n% Running a simulation in VPSC ussually results in an output file\n% |TEX_PH1.OUT| which contains multiple sets of orientations for different\n% strain levels. As these files does not contain any information on the\n% crystal symmetry we need to specify it first\n\ncs = crystalSymmetry('222', [4.762 10.225 5.994],'mineral', 'olivine');\n\n%%\n% In the next step the orientations are imported and converted into a list\n% of using the command .\n\n% put in here the path to the VPSC output files\npath2file = [mtexDataPath filesep 'VPSC'];\n\nodf = ODF.load([path2file filesep 'TEX_PH1.OUT'],'halfwidth',10*degree,'CS',cs)\n\n%%\n% The individuel ODFs can be accessed by |odf{id}|\n\n% lets plot the second ODF\nplotSection(odf{2},'sigma','figSize','normal')\n\n%%\n% The information about the strain are stored as additional properties\n% within each ODF variable\n\nodf{1}.opt\n\n%% Compare pole figures during deformation\n%\n% Next we examine the evaluation of the ODF during the deformation by\n% plotting strain depended pole figures. \n\n% define some crystal directions\nh = Miller({1,0,0},{0,1,0},{0,0,1},cs,'uvw');\n\n% generate some figure\nfig = newMtexFigure('layout',[4,3],'figSize','huge');\nsubSet = 1:4;\n\n% plot pole figures for different strain steps\nfor n = subSet\n nextAxis\n plotPDF(odf{n},h,'lower','contourf','doNotDraw');\n ylabel(fig.children(end-2),['\\epsilon = ',xnum2str(odf{n}.opt.strain)]);\nend\nsetColorRange('equal')\nmtexColorbar\n\n%% Visualize slip system activity\n% \n% Alongside with the orientation data VPSC also outputs a file\n% |ACT_PH1.OUT| which contains the activity of the different slip systems\n% during the deformation. Lets read this file as a table\n\nACT = readtable([path2file filesep 'ACT_PH1.OUT'],'FileType','text')\n\n%%\n% and plot the slip activity with respect to the strain for the different\n% modes\n\n% loop though the columns MODE1 ... MOD11\nclose all\nfor n = 3: size(ACT,2)\n \n % perform the plotting\n plot(ACT.STRAIN, table2array(ACT(:,n)),'linewidth',2,...\n 'DisplayName',['Slip mode ',num2str(n-2)])\n hold on;\nend\nhold off\n\n% some styling\nxlabel('Strain');\nylabel('Slip activity');\nlegend('show','location','NorthEastOutside');\n\nset(gca,'Ylim',[-0.005 1])\nset(gcf,'MenuBar','none','units','normalized','position',[0.25 0.25 0.5 0.5]);\n\n%for only one mode plot, e.g.,mode 3: cs = csapi(STRAIN,MODE{3});fnplt(cs,3,'color','b');hold off;", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/Plasticity/VPSCImport.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.3989057176526204}}
{"text": "function [params] = sv_calcB(vResults)\n% function [vResults] = sv_calcB(vResults)\n% -------------------------------------\n% Calculation of b-value uncertainty from given mValueGrid_ determined with\n% sv_calcMc\n%\n%\n% Input parameters:\n% vResults\n%\n% Output parameters:\n%\n%\n% J. Woessner; woessner@seismo.ifg.ethz.ch\n% last update: 14.04.03\n\n\n% Initialize\n\n% Create Indices to catalog\n[vResults.caNodeIndices] = ex_CreateIndexCatalog(vResults.mCatalog, vResults.mPolygon, vResults.bMap, vResults.nGriddingMode,...\n vResults.nNumberEvents, vResults.fRadius, vResults.fSizeRectHorizontal, vResults.fSizeRectDepth);\n\n% Determine time period of catalog\nvResults.fTminCat = min(vResults.mCatalog(:,3));\nvResults.fTmaxCat = max(vResults.mCatalog(:,3));\n% Adjust to decimal years\nfTimePeriod =vResults.fTimePeriod/365;\n\n% Init result matrix\nmValueGrid_ = [];\n\n% Loop over all grid nodes\nfor nNode_ = 1:length(vResults.mPolygon(:,1))\n nNode_\n % Create node catalog\n mNodeCatalog_ = vResults.mCatalog(vResults.caNodeIndices{nNode_}, :);\n % Select time period for mNodeCatalog_\n vSel = (vResults.fTstart <= mNodeCatalog_(:,3) & mNodeCatalog_(:,3) < vResults.fTstart+fTimePeriod);\n mNodeCatalog_ = mNodeCatalog_(vSel,:);\n % Check for constant number of events calculations\n if (vResults.nGriddingMode == 0)\n [mNodeCatalog_] = ex_MaxRadius(vResults.mCatalog, vResults.mPolygon, nNode_, vResults.caNodeIndices, vResults.fMaxRadius, vResults.nNumberEvents, vResults.bMap);\n end\n [nX,nY] = size(mNodeCatalog_);\n if (nX < vResults.nMinimumNumber)\n mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];\n else\n try\n % b-value for median Mc(EMR)\n vSel1=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,6));\n mCat1=mNodeCatalog_(vSel1,:);\n [fMeanMag1, fBValue1, fStdDev1, fAValue1] = calc_bmemag(mCat1, vResults.fBinning);\n % b-value for 16 percentile Mc\n vSel2=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,16));\n mCat2=mNodeCatalog_(vSel2,:);\n [fMeanMag2, fBValue2, fStdDev2, fAValue2] = calc_bmemag(mCat2, vResults.fBinning);\n % b-value for 84 percentile Mc\n vSel3=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,17));\n mCat3=mNodeCatalog_(vSel3,:);\n [fMeanMag3, fBValue3, fStdDev3, fAValue3] = calc_bmemag(mCat3, vResults.fBinning);\n % b-value check for Mc(EMR)\n vSel4=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,5));\n mCat4=mNodeCatalog_(vSel4,:);\n [fMeanMag4, fBValue4, fStdDev4, fAValue4] = calc_bmemag(mCat4, vResults.fBinning);\n mValueGrid_= [mValueGrid_; fBValue1 fStdDev1 fAValue1 fBValue2 fStdDev2 fAValue2...\n fBValue3 fStdDev3 fAValue3 fMeanMag4 fBValue4 fStdDev4 fAValue4];\n catch\n mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];\n end\n end; % End of if on length(mNodeCatalog_(:,1)\nend; % for nNode\nsave(['Bval_result_Time' num2str(vResults.fTstart) '_Nmin_' num2str(vResults.nMinimumNumber) '.mat'], 'mValueGrid_');\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/jochen/seisvar/sv_calcB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.39878901449506887}}
{"text": "function fem2d_project ( sample_prefix, fem_prefix )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for FEM2D_PROJECT.\n%\n% Discussion:\n%\n% FEM2D_PROJECT reads files defining a sampling of a (scalar or vector)\n% function of 2 arguments, and a list of nodes and triangular elements\n% to use for a finite element representation of the data.\n%\n% It computes a set of finite element coefficients to be associated with\n% the given finite element mesh, and writes that information to a file\n% so that an FEM representation is formed by the node, element and value\n% files.\n%\n% Usage:\n%\n% fem2d_project ( 'sample_prefix', 'fem_prefix' )\n%\n% where 'sample_prefix' is the common prefix for the SAMPLE files:\n%\n% * sample_prefix_nodes.txt, the node coordinates where samples were taken;\n% * sample_prefix_elements.txt, the nodes that make up each element;\n% * sample_prefix_values.txt, the sample values.\n%\n% and 'fem_prefix' is the common prefix for the FEM files:\n%\n% * fem_prefix_nodes.txt, the node coordinates;\n% * fem_prefix_elements.txt, the nodes that make up each element;\n% * fem_prefix_values.txt, the values defined at each node, \n% (computed by this program).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string SAMPLE_PREFIX, the common prefix for sample files.\n%\n% Input, string FEM_PREFIX, the common prefix for FEM files.\n%\n timestamp ( );\n\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT\\n' );\n fprintf ( ' MATLAB version.\\n' );\n fprintf ( '\\n' );\n fprintf ( ' Read files defining a sampling of a function of 2 arguments.\\n' );\n fprintf ( ' Read files defining a finite element mesh.\\n' );\n fprintf ( ' Project the sample data onto the mesh, and\\n' );\n fprintf ( ' write a file of FEM coefficient values.\\n' );\n%\n% Get the number of command line arguments.\n%\n if ( nargin < 1 )\n\n fprintf ( '\\n' );\n sample_prefix = input ( 'Enter the sample file prefix: ' );\n\n else\n\n end\n\n if ( nargin < 2 )\n\n fprintf ( '\\n' );\n fem_prefix = input ( 'Enter the FEM file prefix: ' );\n\n else\n\n end\n%\n% Create the filenames.\n%\n sample_node_filename = strcat ( sample_prefix, '_nodes.txt' );\n sample_element_filename = strcat ( sample_prefix, '_elements.txt' );\n sample_value_filename = strcat ( sample_prefix, '_values.txt' );\n\n fem_node_filename = strcat ( fem_prefix, '_nodes.txt' );\n fem_element_filename = strcat ( fem_prefix, '_elements.txt' );\n fem_value_filename = strcat ( fem_prefix, '_values.txt' );\n%\n% Read the SAMPLE NODE, ELEMENT and VALUE data.\n%\n sample_node_xy = load ( sample_node_filename );\n sample_node_xy = sample_node_xy';\n [sample_node_dim, sample_node_num ] = size ( sample_node_xy );\n\n fprintf ( '\\n' );\n fprintf ( ' Sample node spatial dimension is %d\\n', sample_node_dim );\n fprintf ( ' Sample node number is %d\\n', sample_node_num );\n\n if ( sample_node_dim ~= 2 )\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT - Fatal error!\\n' );\n fprintf ( ' Spatial dimension of the sample nodes is not 2.\\n' );\n return\n end\n\n sample_element_node = load ( sample_element_filename );\n sample_element_node = sample_element_node';\n [ sample_element_order, sample_element_num ] = size ( sample_element_node );\n\n fprintf ( '\\n' );\n fprintf ( ' Sample element order is %d\\n', sample_element_order );\n fprintf ( ' Sample element number is %d\\n', sample_element_num );\n\n if ( sample_element_order ~= 3 )\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT - Fatal error!\\n' );\n fprintf ( ' The sample elements must be of order 3.\\n' );\n return\n end\n\n sample_value = load ( sample_value_filename );\n sample_value = sample_value';\n [ sample_value_dim, sample_value_num ] = size ( sample_value );\n\n fprintf ( '\\n' );\n fprintf ( ' Sample value dimension is %d\\n', sample_value_dim );\n fprintf ( ' Sample value number is %d\\n', sample_value_num );\n\n if ( sample_value_num ~= sample_node_num )\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT - Fatal error!\\n' );\n fprintf ( ' Number of sample nodes and values are not equal.\\n' );\n return\n end\n\n sample_value_min = min ( sample_value, [], 2 );\n sample_value_max = max ( sample_value, [], 2 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index SAMPLE Min SAMPLE Max\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : sample_value_dim\n fprintf ( 1, ' %8d %14f %14f\\n', i, sample_value_min(i), sample_value_max(i) );\n end\n%\n% Create the sample element neighbor array.\n%\n sample_element_neighbor = triangulation_order3_neighbor_triangles ( ...\n sample_element_num, sample_element_node );\n\n fprintf ( '\\n' );\n fprintf ( ' The element neighbor array has been computed.\\n' );\n%\n% Read the FEM NODE and ELEMENT data.\n%\n fem_node_xy = load ( fem_node_filename );\n fem_node_xy = fem_node_xy';\n [ fem_node_dim, fem_node_num ] = size ( fem_node_xy );\n\n fprintf ( '\\n' );\n fprintf ( ' The FEM node dimension is %d\\n', fem_node_dim );\n fprintf ( ' The FEM node number is %d\\n', fem_node_num );\n\n if ( fem_node_dim ~= 2 )\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT - Fatal error!\\n' );\n fprintf ( ' Spatial dimension of the nodes is not 2.\\n' );\n return\n end\n\n fem_element_node = load ( fem_element_filename );\n fem_element_node = fem_element_node';\n [ fem_element_order, fem_element_num ] = size ( fem_element_node );\n\n fprintf ( ' The FEM element order is %d\\n', fem_element_order );\n fprintf ( ' The FEM element number is %d\\n', fem_element_num );\n\n if ( fem_element_order ~= 3 )\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT - Fatal error!\\n' );\n fprintf ( ' The FEM elements must be of order 3.\\n' );\n return\n end\n%\n% Compute the FEM values.\n%\n fem_value_dim = sample_value_dim;\n fem_value_num = fem_node_num;\n\n fem_value = fem2d_transfer ( sample_element_order, ...\n sample_element_num, sample_value_dim, ...\n sample_node_xy, sample_element_node, sample_element_neighbor, sample_value, ...\n fem_node_num, fem_element_num, fem_value_dim, fem_node_xy, fem_element_node );\n%\n% Print Min, Max.\n%\n fem_value_min = min ( fem_value, [], 2 );\n fem_value_max = max ( fem_value, [], 2 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index FEM Min FEM Max\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : fem_value_dim\n fprintf ( 1, ' %8d %14f %14f\\n', i, fem_value_min(i), fem_value_max(i) );\n end\n%\n% Write the FEM values.\n%\n r8mat_write ( fem_value_filename, fem_value_dim, fem_value_num, fem_value );\n\n fprintf ( '\\n' );\n fprintf ( ' FEM value data written to \"%s\".\\n', fem_value_filename );\n%\n% Terminate.\n%\n fprintf ( '\\n' );\n fprintf ( 'FEM2D_PROJECT\\n' );\n fprintf ( ' Normal end of execution.\\n' );\n\n fprintf ( '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ phi, dphidx, dphidy ] = basis_mn_t3 ( t, n, p )\n\n%*****************************************************************************80\n%\n%% BASIS_MN_T3: all bases functions at N points for a T3 element.\n%\n% Discussion:\n%\n% The routine is given the coordinates of the vertices of a triangle.\n% It works directly with these coordinates, and does not refer to a \n% reference element.\n%\n% The sides of the triangle DO NOT have to lie along a coordinate\n% axis.\n%\n% The routine evaluates the basis functions associated with each vertex,\n% and their derivatives with respect to X and Y.\n%\n% Physical Element T3:\n%\n% 3\n% / \\\n% / \\\n% / \\\n% / \\\n% 1---------2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the vertices of the triangle. It is common to list \n% these points in counter clockwise order.\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real P(2,N), the coordinates of the evaluation points.\n%\n% Output, real PHI(3,N), the basis functions at the evaluation points.\n%\n% Output, real DPHIDX(3,N), DPHIDY(3,N), the basis derivatives \n% at the evaluation points.\n%\n% Local parameters:\n%\n% Local, real AREA, is (twice) the area of the triangle.\n%\n area = t(1,1) * ( t(2,2) - t(2,3) ) ...\n + t(1,2) * ( t(2,3) - t(2,1) ) ...\n + t(1,3) * ( t(2,1) - t(2,2) );\n\n phi(1,1:n) = ( ( t(1,3) - t(1,2) ) * ( p(2,1:n) - t(2,2) ) ...\n - ( t(2,3) - t(2,2) ) * ( p(1,1:n) - t(1,2) ) );\n dphidx(1,1:n) = - ( t(2,3) - t(2,2) );\n dphidy(1,1:n) = ( t(1,3) - t(1,2) );\n\n phi(2,1:n) = ( ( t(1,1) - t(1,3) ) * ( p(2,1:n) - t(2,3) ) ...\n - ( t(2,1) - t(2,3) ) * ( p(1,1:n) - t(1,3) ) );\n dphidx(2,1:n) = - ( t(2,1) - t(2,3) );\n dphidy(2,1:n) = ( t(1,1) - t(1,3) );\n\n phi(3,1:n) = ( ( t(1,2) - t(1,1) ) * ( p(2,1:n) - t(2,1) ) ...\n - ( t(2,2) - t(2,1) ) * ( p(1,1:n) - t(1,1) ) );\n dphidx(3,1:n) = - ( t(2,2) - t(2,1) );\n dphidy(3,1:n) = ( t(1,2) - t(1,1) );\n%\n% Normalize.\n%\n phi(1:3,1:n) = phi(1:3,1:n) / area;\n dphidx(1:3,1:n) = dphidx(1:3,1:n) / area;\n dphidy(1:3,1:n) = dphidy(1:3,1:n) / area;\n\n return\nend\nfunction [ phi, dphidx, dphidy ] = basis_mn_t6 ( t, n, p )\n\n%*****************************************************************************80\n%\n%% BASIS_MN_T6: all bases for N points in a T6 element.\n%\n% Discussion:\n%\n% The routine is given the coordinates of the vertices and midside\n% nodes of a triangle. It works directly with these coordinates, and does \n% not refer to a reference element.\n%\n% This routine requires that the midside nodes be \"in line\"\n% with the vertices, that is, that the sides of the triangle be\n% straight. However, the midside nodes do not actually have to\n% be halfway along the side of the triangle. \n%\n% Physical element T6:\n%\n% This picture indicates the assumed ordering of the six nodes\n% of the triangle.\n%\n% 3\n% / \\\n% / \\\n% 6 5\n% / \\\n% / \\\n% 1-----4-----2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,6), the nodal oordinates of the element.\n% It is common to list these points in counter clockwise order.\n%\n% Input, real P(2,N), the evaluation points.\n%\n% Output, real PHI(6,N), the basis functions at the evaluation points.\n%\n% Output, real DPHIDX(6,N), DPHIDY(6,N), the basis derivatives at the \n% evaluation points.\n%\n% Local Parameters:\n%\n% Local, real AREA, is (twice) the area of the triangle.\n%\n\n%\n% Basis function 1: PHI(X,Y) = G(3,2) * H(6,4) / normalization.\n%\n gx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...\n - ( t(1,3) - t(1,2) ) * ( p(2,1:n) - t(2,2) );\n\n gn(1:n) = ( t(1,1) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...\n - ( t(1,3) - t(1,2) ) * ( t(2,1) - t(2,2) );\n\n hx(1:n) = ( p(1,1:n) - t(1,4) ) * ( t(2,6) - t(2,4) ) ...\n - ( t(1,6) - t(1,4) ) * ( p(2,1:n) - t(2,4) );\n\n hn(1:n) = ( t(1,1) - t(1,4) ) * ( t(2,6) - t(2,4) ) ...\n - ( t(1,6) - t(1,4) ) * ( t(2,1) - t(2,4) );\n\n phi(1,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );\n\n dphidx(1,1:n) = ( ( t(2,3) - t(2,2) ) * hx(1:n) ...\n + gx(1:n) * ( t(2,6) - t(2,4) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n dphidy(1,1:n) = -( ( t(1,3) - t(1,2) ) * hx(1:n) ...\n + gx * ( t(1,6) - t(1,4) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n%\n% Basis function 2: PHI(X,Y) = G(3,1) * H(4,5) / normalization.\n%\n gx(1:n) = ( p(1,1:n) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( p(2,1:n) - t(2,1) );\n\n gn(1:n) = ( t(1,2) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( t(2,2) - t(2,1) );\n\n hx(1:n) = ( p(1,1:n) - t(1,5) ) * ( t(2,4) - t(2,5) ) ...\n - ( t(1,4) - t(1,5) ) * ( p(2,1:n) - t(2,5) );\n\n hn(1:n) = ( t(1,2) - t(1,5) ) * ( t(2,4) - t(2,5) ) ...\n - ( t(1,4) - t(1,5) ) * ( t(2,2) - t(2,5) );\n\n phi(2,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );\n\n dphidx(2,1:n) = ( ( t(2,3) - t(2,1) ) * hx(1:n) ...\n + gx(1:n) * ( t(2,4) - t(2,5) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n dphidy(2,1:n) = -( ( t(1,3) - t(1,1) ) * hx(1:n) ...\n + gx(1:n) * ( t(1,4) - t(1,5) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n%\n% Basis function 3: PHI(X,Y) = G(1,2) * H(5,6) / normalization.\n%\n gx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,1) - t(2,2) ) ...\n - ( t(1,1) - t(1,2) ) * ( p(2,1:n) - t(2,2) );\n\n gn(1:n) = ( t(1,3) - t(1,2) ) * ( t(2,1) - t(2,2) ) ...\n - ( t(1,1) - t(1,2) ) * ( t(2,3) - t(2,2) );\n\n hx(1:n) = ( p(1,1:n) - t(1,6) ) * ( t(2,5) - t(2,6) ) ...\n - ( t(1,5) - t(1,6) ) * ( p(2,1:n) - t(2,6) );\n\n hn(1:n) = ( t(1,3) - t(1,6) ) * ( t(2,5) - t(2,6) ) ...\n - ( t(1,5) - t(1,6) ) * ( t(2,3) - t(2,6) );\n\n phi(3,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );\n\n dphidx(3,1:n) = ( ( t(2,1) - t(2,2) ) * hx(1:n) ...\n + gx(1:n) * ( t(2,5) - t(2,6) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n dphidy(3,1:n) = -( ( t(1,1) - t(1,2) ) * hx(1:n) ...\n + gx(1:n) * ( t(1,5) - t(1,6) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n%\n% Basis function 4: PHI(X,Y) = G(1,3) * H(2,3) / normalization.\n%\n gx(1:n) = ( p(1,1:n) - t(1,3) ) * ( t(2,1) - t(2,3) ) ...\n - ( t(1,1) - t(1,3) ) * ( p(2,1:n) - t(2,3) );\n\n gn(1:n) = ( t(1,4) - t(1,3) ) * ( t(2,1) - t(2,3) ) ...\n - ( t(1,1) - t(1,3) ) * ( t(2,4) - t(2,3) );\n\n hx(1:n) = ( p(1,1:n) - t(1,3) ) * ( t(2,2) - t(2,3) ) ...\n - ( t(1,2) - t(1,3) ) * ( p(2,1:n) - t(2,3) );\n\n hn(1:n) = ( t(1,4) - t(1,3) ) * ( t(2,2) - t(2,3) ) ...\n - ( t(1,2) - t(1,3) ) * ( t(2,4) - t(2,3) );\n\n phi(4,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );\n\n dphidx(4,1:n) = ( ( t(2,1) - t(2,3) ) * hx(1:n) ...\n + gx(1:n) * ( t(2,2) - t(2,3) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n dphidy(4,1:n) = -( ( t(1,1) - t(1,3) ) * hx(1:n) ...\n + gx(1:n) * ( t(1,2) - t(1,3) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n%\n% Basis function 5: PHI(X,Y) = G(2,1) * H(3,1) / normalization.\n%\n gx(1:n) = ( p(1,1:n) - t(1,1) ) * ( t(2,2) - t(2,1) ) ...\n - ( t(1,2) - t(1,1) ) * ( p(2,1:n) - t(2,1) );\n\n gn(1:n) = ( t(1,5) - t(1,1) ) * ( t(2,2) - t(2,1) ) ...\n - ( t(1,2) - t(1,1) ) * ( t(2,5) - t(2,1) );\n\n hx(1:n) = ( p(1,1:n) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( p(2,1:n) - t(2,1) );\n\n hn(1:n) = ( t(1,5) - t(1,1) ) * ( t(2,3) - t(2,1) ) ...\n - ( t(1,3) - t(1,1) ) * ( t(2,5) - t(2,1) );\n\n phi(5,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );\n\n dphidx(5,1:n) = ( ( t(2,2) - t(2,1) ) * hx(1:n) ...\n + gx(1:n) * ( t(2,3) - t(2,1) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n dphidy(5,1:n) = -( ( t(1,2) - t(1,1) ) * hx(1:n) ...\n + gx(1:n) * ( t(1,3) - t(1,1) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n%\n% Basis function 6: PHI(X,Y) = G(1,2) * H(3,2) / normalization.\n%\n gx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,1) - t(2,2) ) ...\n - ( t(1,1) - t(1,2) ) * ( p(2,1:n) - t(2,2) );\n\n gn(1:n) = ( t(1,6) - t(1,2) ) * ( t(2,1) - t(2,2) ) ...\n - ( t(1,1) - t(1,2) ) * ( t(2,6) - t(2,2) );\n\n hx(1:n) = ( p(1,1:n) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...\n - ( t(1,3) - t(1,2) ) * ( p(2,1:n) - t(2,2) );\n\n hn(1:n) = ( t(1,6) - t(1,2) ) * ( t(2,3) - t(2,2) ) ...\n - ( t(1,3) - t(1,2) ) * ( t(2,6) - t(2,2) );\n\n phi(6,1:n) = ( gx(1:n) .* hx(1:n) ) ./ ( gn(1:n) .* hn(1:n) );\n\n dphidx(6,1:n) = ( ( t(2,1) - t(2,2) ) * hx(1:n) ...\n + gx(1:n) * ( t(2,3) - t(2,2) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n dphidy(6,1:n) = -( ( t(1,1) - t(1,2) ) * hx(1:n) ...\n + gx(1:n) * ( t(1,3) - t(1,2) ) ) ...\n ./ ( gn(1:n) .* hn(1:n) );\n\n return\nend\nfunction fem_value = fem2d_transfer ( sample_element_order, ...\n sample_element_num, sample_value_dim, sample_node_xy, ...\n sample_element_node, sample_element_neighbor, sample_value, fem_node_num, ...\n fem_element_num, fem_value_dim, fem_node_xy, fem_element_node )\n\n%*****************************************************************************80\n%\n%% FEM2D_TRANSFER \"transfers\" from one finite element mesh to another.\n%\n% Discussion:\n%\n% 1) the linear system A*X=B is defined with A being a full storage matrix.\n% This can easily be fixed using MATLAB's SPARSE facility.\n%\n% 2) the quadrature rule used is low order.\n%\n% 3) the triangular elements are assumed to be linear.\n%\n%\n% We are also given a set of \"sample\" finite element function defined\n% by SAMPLE_NODE_XY, SAMPLE_ELEMENT, and SAMPLE_VALUE.\n%\n% We are given a second finite element mesh, FEM_NODE_XY and\n% FEM_ELEMENT_NODE.\n%\n% Our aim is to \"project\" the sample data values into the finite element\n% space, that is, to come up with a finite element function FEM_VALUE which\n% well approximates the sample data.\n%\n% Now let W(x,y) represent a function interpolating the sample data, and\n% let Vk(x,y) represent the finite element basis function associated with\n% node K.\n%\n% Then we seek the coefficient vector U corresponding to a finite element\n% function U(x,y) of the form:\n%\n% U(x,y) = sum ( 1 <= K <= N ) Uk * Vk(x,y)\n%\n% To determine the coefficent vector entries U, we form a set of\n% projection equations. For node K at grid point (I,J), the associated\n% basis function Vk(x,y) is used to pose the equation:\n%\n% Integral U(x,y) Vk(x,y) dx dy = Integral W(x,y) Vk(x,y) dx dy\n%\n% The left hand side is the usual stiffness matrix times the desired\n% coefficient vector U. To complete the system, we simply need to\n% determine the right hand side, that is, the integral of the data function\n% W against the basis function Vk.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer SAMPLE_NODE_NUM, the number of nodes.\n%\n% Input, integer SAMPLE_ELEMENT_ORDER, the element order.\n%\n% Input, integer SAMPLE_ELEMENT_NUM, the number of elements.\n%\n% Input, integer SAMPLE_VALUE_DIM, the value dimension.\n%\n% Input, integer SAMPLE_VALUE_NUM, the number of values.\n%\n% Input, real SAMPLE_NODE_XY(2,SAMPLE_NODE_NUM), the nodes.\n%\n% Input, integer SAMPLE_ELEMENT_NODE(SAMPLE_ELEMENT_ORDER,SAMPLE_ELEMENT_NUM),\n% the nodes that make up each element.\n%\n% Input, integer SAMPLE_ELEMENT_NEIGHBOR(3,SAMPLE_ELEMENT_NUM),\n% the neighbor triangles.\n%\n% Input, real SAMPLE_VALUE(SAMPLE_VALUE_DIM,SAMPLE_NODE_NUM),\n% the values.\n%\n% Input, integer FEM_NODE_NUM, the number of nodes.\n%\n% Input, integer FEM_ELEMENT_ORDER, the element order.\n%\n% Input, integer FEM_ELEMENT_NUM, the number of elements.\n%\n% Input, integer FEM_VALUE_DIM, the value dimension.\n%\n% Input, integer FEM_VALUE_NUM, the number of values.\n%\n% Input, real FEM_NODE_XY(2,FEM_NODE_NUM), the nodes.\n%\n% Input, integer FEM_ELEMENT_NODE(FEM_ELEMENT_ORDER,FEM_ELEMENT_NUM),\n% the nodes that make up each element.\n%\n% Output, real FEM_VALUE(FEM_VALUE_DIM,FEM_VALUE_NUM),\n% the values.\n%\n project_node_num = 1;\n quad_num = 3;\n%\n% Assemble the coefficient matrix A and the right-hand side B.\n%\n b = zeros (fem_node_num,fem_value_dim);\n%\n% Define A as a sparse matrix.\n%\n a = sparse ( [], [], [], fem_node_num, fem_node_num );\n\n% a = zeros (fem_node_num,fem_node_num);\n\n for element = 1 : fem_element_num\n\n i1 = fem_element_node(1,element);\n i2 = fem_element_node(2,element);\n i3 = fem_element_node(3,element);\n\n area = 0.5 * ...\n ( fem_node_xy(1,i1) * ( fem_node_xy(2,i2) - fem_node_xy(2,i3) ) ...\n + fem_node_xy(1,i2) * ( fem_node_xy(2,i3) - fem_node_xy(2,i1) ) ...\n + fem_node_xy(1,i3) * ( fem_node_xy(2,i1) - fem_node_xy(2,i2) ) );\n%\n% Consider each quadrature point.\n% Here, we use the midside nodes as quadrature points.\n%\n for quad = 1 : quad_num\n\n q1 = quad;\n q2 = mod ( quad, quad_num ) + 1;\n\n nq1 = fem_element_node(q1,element);\n nq2 = fem_element_node(q2,element);\n\n xq = 0.5 * ( fem_node_xy(1,nq1) + fem_node_xy(1,nq2) );\n yq = 0.5 * ( fem_node_xy(2,nq1) + fem_node_xy(2,nq2) );\n wq = 1.0 / 3.0;\n%\n% Consider each test function in the element.\n%\n for ti1 = 1 : 3\n\n ti2 = mod ( ti1, 3 ) + 1;\n ti3 = mod ( ti1 + 1, 3 ) + 1;\n\n nti1 = fem_element_node(ti1,element);\n nti2 = fem_element_node(ti2,element);\n nti3 = fem_element_node(ti3,element);\n\n qi = 0.5 * ( ...\n ( fem_node_xy(1,nti3) - fem_node_xy(1,nti2) ) ...\n * ( yq - fem_node_xy(2,nti2) ) ...\n - ( fem_node_xy(2,nti3) - fem_node_xy(2,nti2) ) ...\n * ( xq - fem_node_xy(1,nti2) ) ) / area;\n%\n% The projection takes place here. The finite element code needs the value\n% of the sample function at the point (XQ,YQ). The call to PROJECTION\n% locates (XQ,YQ) in the triangulated mesh of sample data, and returns a\n% value produced by piecewise linear interpolation.\n%\n project_node_xy(1,1) = xq;\n project_node_xy(2,1) = yq;\n\n project_value = projection ( sample_node_xy, ...\n sample_element_order, sample_element_num, sample_element_node, ...\n sample_element_neighbor, sample_value_dim, sample_value, ...\n project_node_num, project_node_xy );\n\n b(nti1,1:fem_value_dim) = b(nti1,1:fem_value_dim) ...\n + area * wq * ( project_value(1:fem_value_dim,1)' * qi );\n%\n% Consider each basis function in the element.\n%\n for tj1 = 1 : 3\n\n tj2 = mod ( tj1, 3 ) + 1;\n tj3 = mod ( tj1 + 1, 3 ) + 1;\n\n ntj1 = fem_element_node(tj1,element);\n ntj2 = fem_element_node(tj2,element);\n ntj3 = fem_element_node(tj3,element);\n\n qj = 0.5 * ( ...\n ( fem_node_xy(1,ntj3) - fem_node_xy(1,ntj2) ) ...\n * ( yq - fem_node_xy(2,ntj2) ) ...\n - ( fem_node_xy(2,ntj3) - fem_node_xy(2,ntj2) ) ...\n * ( xq - fem_node_xy(1,ntj2) ) ) / area;\n\n a(nti1,ntj1) = a(nti1,ntj1) + area * wq * ( qi * qj );\n\n end\n\n end\n\n end\n\n end\n%\n% Solve the linear system A * X = B.\n%\n fem_value = ( a \\ b )';\n\n return\nend\nfunction isgn = i4col_compare ( m, n, a, i, j )\n\n%*****************************************************************************80\n%\n%% I4COL_COMPARE compares columns I and J of a integer array.\n%\n% Example:\n%\n% Input:\n%\n% M = 3, N = 4, I = 2, J = 4\n%\n% A = (\n% 1 2 3 4\n% 5 6 7 8\n% 9 10 11 12 )\n%\n% Output:\n%\n% ISGN = -1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer A(M,N), an array of N columns of vectors of length M.\n%\n% Input, integer I, J, the columns to be compared.\n% I and J must be between 1 and N.\n%\n% Output, integer ISGN, the results of the comparison:\n% -1, column I < column J,\n% 0, column I = column J,\n% +1, column J < column I.\n%\n\n%\n% Check.\n%\n if ( i < 1)\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' Column index I = %d < 1.\\n', i );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n if ( n < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' N = %d < column index I = %d.\\n', n, i );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n if ( j < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' Column index J = %d < 1.\\n', j );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n if ( n < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' N = %d < column index J = %d.\\n', n, j );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n isgn = 0;\n\n if ( i == j )\n return\n end\n\n k = 1;\n\n while ( k <= m )\n\n if ( a(k,i) < a(k,j) )\n isgn = -1;\n return\n elseif ( a(k,j) < a(k,i) )\n isgn = +1;\n return\n end\n\n k = k + 1;\n\n end\n\n return\nend\nfunction a = i4col_sort_a ( m, n, a )\n\n%*****************************************************************************80\n%\n%% I4COL_SORT_A ascending sorts an I4COL.\n%\n% Discussion:\n%\n% In lexicographic order, the statement \"X < Y\", applied to two real\n% vectors X and Y of length M, means that there is some index I, with\n% 1 <= I <= M, with the property that\n%\n% X(J) = Y(J) for J < I,\n% and\n% X(I) < Y(I).\n%\n% In other words, the first time they differ, X is smaller.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of A, and the length of\n% a vector of data.\n%\n% Input, integer N, the number of columns of A.\n%\n% Input, integer A(M,N), the array of N columns of M-vectors.\n%\n% Output, integer A(M,N), the columns of A have been sorted in ascending\n% lexicographic order.\n%\n if ( m <= 0 )\n return\n end\n\n if ( n <= 1 )\n return\n end\n%\n% Initialize.\n%\n indx = 0;\n isgn = 0;\n%\n% Call the external heap sorter.\n%\n while ( 1 )\n\n [ indx, i, j ] = sort_heap_external ( n, indx, isgn );\n%\n% Interchange the I and J objects.\n%\n if ( 0 < indx )\n\n a = i4col_swap ( m, n, a, i, j );\n%\n% Compare the I and J objects.\n%\n elseif ( indx < 0 )\n\n isgn = i4col_compare ( m, n, a, i, j );\n\n elseif ( indx == 0 )\n\n break\n\n end\n\n end\n\n return\nend\nfunction a = i4col_swap ( m, n, a, i, j )\n\n%*****************************************************************************80\n%\n%% I4COL_SWAP swaps columns I and J of a integer array of column data.\n%\n% Example:\n%\n% Input:\n%\n% M = 3, N = 4, I = 2, J = 4\n%\n% A = (\n% 1 2 3 4\n% 5 6 7 8\n% 9 10 11 12 )\n%\n% Output:\n%\n% A = (\n% 1 4 3 2\n% 5 8 7 6\n% 9 12 11 10 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns in the array.\n%\n% Input, integer A(M,N), an array of N columns of length M.\n%\n% Input, integer I, J, the columns to be swapped.\n%\n% Output, integer A(M,N), the array, with columns I and J swapped.\n%\n if ( i < 1 || n < i || j < 1 || n < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_SWAP - Fatal error!\\n' );\n fprintf ( 1, ' I or J is out of bounds.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n fprintf ( 1, ' J = %d\\n', j );\n fprintf ( 1, ' N = %d\\n', n );\n error ( 'I4COL_SWAP - Fatal error!' );\n end\n\n if ( i == j )\n return\n end\n\n col(1:m) = a(1:m,i)';\n a(1:m,i) = a(1:m,j);\n a(1:m,j) = col(1:m)';\n\n return\nend\nfunction sample_value = projection ( fem_node_xy, ...\n fem_element_order, fem_element_num, fem_element_node, ...\n fem_element_neighbor, fem_value_dim, fem_value, sample_node_num, ...\n sample_node_xy )\n\n%*****************************************************************************80\n%\n%% PROJECTION evaluates an FEM function on a T3 or T6 triangulation.\n%\n% Discussion:\n%\n% Note that the sample values returned are true values of the underlying\n% finite element function. They are NOT produced by constructing some\n% other function that interpolates the data at the finite element nodes\n% (something which MATLAB's griddata function can easily do.) Instead,\n% each sampling node is located within one of the associated finite\n% element triangles, and the finite element function is developed and\n% evaluated there.\n%\n% MATLAB's scattered data interpolation is wonderful, but it cannot\n% be guaranteed to reproduce the finite element function corresponding\n% to nodal data. This routine can (or at least tries to%).\n%\n% So if you are using finite elements, then using THIS routine\n% (but not MATLAB's griddata function), what you see is what you have%\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer FEM_NODE_NUM, the number of nodes.\n%\n% Input, real FEM_NODE_XY(2,FEM_NODE_NUM), the coordinates\n% of the nodes.\n%\n% Input, integer FEM_ELEMENT_ORDER, the order of the elements,\n% either 3 or 6.\n%\n% Input, integer FEM_ELEMENT_NUM, the number of triangles.\n%\n% Input, integer FEM_ELEMENT_NODE(FEM_ELEMENT_ORDER,FEM_ELEMENT_NUM), the\n% nodes that make up each triangle.\n%\n% Input, integer FEM_ELEMENT_NEIGHBOR(3,FEM_ELEMENT_NUM), the\n% index of the neighboring triangle on each side, or -1 if no neighbor there.\n%\n% Input, integer FEM_VALUE_DIM, the \"dimension\" of the values.\n%\n% Input, real FEM_VALUE(FEM_VALUE_DIM,FEM_NODE_NUM), the\n% finite element coefficient values at each node.\n%\n% Input, integer SAMPLE_NODE_NUM, the number of sample nodes.\n%\n% Input, real SAMPLE_NODE_XY(2,SAMPLE_NODE_NUM), the sample nodes.\n%\n% Output, real SAMPLE_VALUE(FEM_VALUE_DIM,SAMPLE_NODE_NUM),\n% the sampled values.\n%\n sample_value = zeros(fem_value_dim,sample_node_num);\n%\n% For each sample point: find the triangle T that contains it,\n% and evaluate the finite element function there.\n%\n for j = 1 : sample_node_num\n\n p_xy(1:2,1) = sample_node_xy(1:2,j);\n%\n% Find the triangle T that contains the point.\n%\n t = triangulation_search_delaunay ( ...\n fem_node_xy, fem_element_num, fem_element_node, ...\n fem_element_neighbor, p_xy );\n\n if ( t == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROJECTION - Fatal error!\\n' );\n fprintf ( 1, ' Triangulation search failed!\\n' );\n error ( 'PROJECTION - Fatal error!' );\n end\n%\n% Evaluate the finite element basis functions at the point in T.\n%\n t_node(1:fem_element_order) = fem_element_node(1:fem_element_order,t);\n\n t_xy(1:2,1:fem_element_order) = fem_node_xy(1:2,t_node);\n\n if ( fem_element_order == 3 )\n b = basis_mn_t3 ( t_xy, 1, p_xy );\n elseif ( fem_element_order == 6 )\n b = basis_mn_t6 ( t_xy, 1, p_xy );\n end\n%\n% Multiply by the finite element values to get the sample values.\n%\n for i = 1 : fem_value_dim\n sample_value(i,j) = fem_value(i,t_node(1:fem_element_order)) ...\n * b(1:fem_element_order);\n end\n\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For greater precision, try:\n%\n% fprintf ( output_unit, ' %24,16f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %14f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction [ indx, i, j ] = sort_heap_external ( n, indx, isgn )\n\n%*****************************************************************************80\n%\n%% SORT_HEAP_EXTERNAL externally sorts a list of items into ascending order.\n%\n% Discussion:\n%\n% The actual list of data is not passed to the routine. Hence this\n% routine may be used to sort integers, reals, numbers, names,\n% dates, shoe sizes, and so on. After each call, the routine asks\n% the user to compare or interchange two items, until a special\n% return value signals that the sorting is completed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2004\n%\n% Author:\n%\n% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf.\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer N, the number of items to be sorted.\n%\n% Input, integer INDX, the main communication signal.\n% The user must set INDX to 0 before the first call.\n% Thereafter, the user should set the input value of INDX\n% to the output value from the previous call.\n%\n% Input, integer ISGN, results of comparison of elements I and J.\n% (Used only when the previous call returned INDX less than 0).\n% ISGN <= 0 means I is less than or equal to J;\n% 0 <= ISGN means I is greater than or equal to J.\n%\n% Output, integer INDX, the main communication signal.\n% If INDX is\n%\n% greater than 0, the user should:\n% * interchange items I and J;\n% * call again.\n%\n% less than 0, the user should:\n% * compare items I and J;\n% * set ISGN = -1 if I < J, ISGN = +1 if J < I;\n% * call again.\n%\n% equal to 0, the sorting is done.\n%\n% Output, integer I, J, the indices of two items.\n% On return with INDX positive, elements I and J should be interchanged.\n% On return with INDX negative, elements I and J should be compared, and\n% the result reported in ISGN on the next call.\n%\n persistent i_save;\n persistent j_save;\n persistent k;\n persistent k1;\n persistent n1;\n \n if ( isempty ( i_save ) )\n i_save = -1;\n end\n \n if ( isempty ( j_save ) )\n j_save = -1;\n end\n%\n% INDX = 0: This is the first call.\n%\n if ( indx == 0 )\n \n k = floor ( n / 2 );\n k1 = k;\n n1 = n;\n%\n% INDX < 0: The user is returning the results of a comparison.\n%\n elseif ( indx < 0 )\n\n if ( indx == -2 )\n\n if ( isgn < 0 )\n i_save = i_save + 1;\n end\n\n j_save = k1;\n k1 = i_save;\n indx = -1;\n i = i_save;\n j = j_save;\n return;\n end\n\n if ( 0 < isgn )\n indx = 2;\n i = i_save;\n j = j_save;\n return;\n end\n\n if ( k <= 1 )\n\n if ( n1 == 1 )\n i_save = 0;\n j_save = 0;\n indx = 0;\n else\n i_save = n1;\n n1 = n1 - 1;\n j_save = 1;\n indx = 1;\n end\n\n i = i_save;\n j = j_save;\n return;\n\n end\n\n k = k - 1;\n k1 = k;\n%\n% 0 < INDX, the user was asked to make an interchange.\n%\n elseif ( indx == 1 )\n\n k1 = k;\n\n end\n\n while ( 1 )\n\n i_save = 2 * k1;\n\n if ( i_save == n1 )\n j_save = k1;\n k1 = i_save;\n indx = -1;\n i = i_save;\n j = j_save;\n return;\n elseif ( i_save <= n1 )\n j_save = i_save + 1;\n indx = -2;\n i = i_save;\n j = j_save;\n return;\n end\n\n if ( k <= 1 )\n break;\n end\n\n k = k - 1;\n k1 = k;\n\n end\n\n if ( n1 == 1 )\n i_save = 0;\n j_save = 0;\n indx = 0;\n i = i_save;\n j = j_save;\n else\n i_save = n1;\n n1 = n1 - 1;\n j_save = 1;\n indx = 1;\n i = i_save;\n j = j_save;\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\nfunction triangle_neighbor = triangulation_order3_neighbor_triangles ( ...\n triangle_num, triangle_node )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER3_NEIGHBOR_TRIANGLES determines triangle neighbors.\n%\n% Discussion:\n%\n% A triangulation of a set of nodes can be completely described by\n% the coordinates of the nodes, and the list of nodes that make up\n% each triangle. However, in some cases, it is necessary to know\n% triangle adjacency information, that is, which triangle, if any,\n% is adjacent to a given triangle on a particular side.\n%\n% This routine creates a data structure recording this information.\n%\n% The primary amount of work occurs in sorting a list of 3 * TRIANGLE_NUM\n% data items.\n%\n% This routine was modified to use columns instead of rows.\n%\n% Example:\n%\n% The input information from TRIANGLE_NODE:\n%\n% Triangle Nodes\n% -------- ---------------\n% 1 3 4 1\n% 2 3 1 2\n% 3 3 2 8\n% 4 2 1 5\n% 5 8 2 13\n% 6 8 13 9\n% 7 3 8 9\n% 8 13 2 5\n% 9 9 13 7\n% 10 7 13 5\n% 11 6 7 5\n% 12 9 7 6\n% 13 10 9 6\n% 14 6 5 12\n% 15 11 6 12\n% 16 10 6 11\n%\n% The output information in TRIANGLE_NEIGHBOR:\n%\n% Triangle Neighboring Triangles\n% -------- ---------------------\n%\n% 1 -1 -1 2\n% 2 1 4 3\n% 3 2 5 7\n% 4 2 -1 8\n% 5 3 8 6\n% 6 5 9 7\n% 7 3 6 -1\n% 8 5 4 10\n% 9 6 10 12\n% 10 9 8 11\n% 11 12 10 14\n% 12 9 11 13\n% 13 -1 12 16\n% 14 11 -1 15\n% 15 16 14 -1\n% 16 13 15 -1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 February 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer TRIANGLE_NUM, the number of triangles.\n%\n% Input, integer TRIANGLE_NODE(3,TRIANGLE_NUM), the nodes that make up each triangle.\n%\n% Output, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the three triangles that are direct\n% neighbors of a given triangle. TRIANGLE_NEIGHBOR(1,I) is the index of the triangle\n% which touches side 1, defined by nodes 2 and 3, and so on. TRIANGLE_NEIGHBOR(1,I)\n% is negative if there is no neighbor on that side. In this case, that\n% side of the triangle lies on the boundary of the triangulation.\n%\n\n%\n% Step 1.\n% From the list of nodes for triangle T, of the form: (I,J,K)\n% construct the three neighbor relations:\n%\n% (I,J,1,T) or (J,I,1,T),\n% (J,K,2,T) or (K,J,2,T),\n% (K,I,3,T) or (I,K,3,T)\n%\n% where we choose (I,J,1,T) if I < J, or else (J,I,1,T)\n%\n col = zeros ( 4, 3 * triangle_num );\n \n for tri = 1 : triangle_num\n\n i = triangle_node(1,tri);\n j = triangle_node(2,tri);\n k = triangle_node(3,tri);\n\n if ( i < j )\n col(1:4,1+3*(tri-1)) = [ i, j, 1, tri ]';\n else\n col(1:4,1+3*(tri-1)) = [ j, i, 1, tri ]';\n end\n\n if ( j < k )\n col(1:4,2+3*(tri-1)) = [ j, k, 2, tri ]';\n else\n col(1:4,2+3*(tri-1)) = [ k, j, 2, tri ]';\n end\n\n if ( k < i )\n col(1:4,3+3*(tri-1)) = [ k, i, 3, tri ]';\n else\n col(1:4,3+3*(tri-1)) = [ i, k, 3, tri ]';\n end\n\n end\n%\n% Step 2. Perform an ascending dictionary sort on the neighbor relations.\n% We only intend to sort on rows 1 and 2; the routine we call here\n% sorts on rows 1 through 4 but that won't hurt us.\n%\n% What we need is to find cases where two triangles share an edge.\n% Say they share an edge defined by the nodes I and J. Then there are\n% two columns of COL that start out ( I, J, ?, ? ). By sorting COL,\n% we make sure that these two columns occur consecutively. That will\n% make it easy to notice that the triangles are neighbors.\n%\n col = i4col_sort_a ( 4, 3*triangle_num, col );\n%\n% Step 3. Neighboring triangles show up as consecutive columns with\n% identical first two entries. Whenever you spot this happening,\n% make the appropriate entries in TRIANGLE_NEIGHBOR.\n%\n triangle_neighbor(1:3,1:triangle_num) = -1;\n\n icol = 1;\n\n while ( 1 )\n\n if ( 3 * triangle_num <= icol )\n break\n end\n\n if ( col(1,icol) ~= col(1,icol+1) || col(2,icol) ~= col(2,icol+1) )\n icol = icol + 1;\n continue\n end\n\n side1 = col(3,icol);\n tri1 = col(4,icol);\n side2 = col(3,icol+1);\n tri2 = col(4,icol+1);\n\n triangle_neighbor(side1,tri1) = tri2;\n triangle_neighbor(side2,tri2) = tri1;\n\n icol = icol + 2;\n\n end\n\n return\nend\nfunction [ triangle_index, edge ] = ...\n triangulation_search_delaunay ( node_xy, ...\n triangle_num, triangle_node, triangle_neighbor, p )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_SEARCH_DELAUNAY searches a Delaunay triangulation for a point.\n%\n% Purpose:\n%\n% The algorithm \"walks\" from one triangle to its neighboring triangle,\n% and so on, until a triangle is found containing point P, or P is found \n% to be outside the convex hull. \n%\n% The algorithm computes the barycentric coordinates of the point with \n% respect to the current triangle. If all three quantities are positive,\n% the point is contained in the triangle. If the I-th coordinate is\n% negative, then P lies on the far side of edge I, which is opposite\n% from vertex I. This gives a hint as to where to search next.\n%\n% For a Delaunay triangulation, the search is guaranteed to terminate.\n% For other triangulations, a cycle may occur.\n%\n% Note the surprising fact that, even for a Delaunay triangulation of\n% a set of points, the nearest point to P need not be one of the\n% vertices of the triangle containing P. \n%\n% The code can be called for triangulations of any order, but only\n% the first three nodes in each triangle are considered. Thus, if\n% higher order triangles are used, and the extra nodes are intended\n% to give the triangle a polygonal shape, these will have no effect,\n% and the results obtained here might be misleading.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Barry Joe.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Barry Joe,\n% GEOMPACK - a software package for the generation of meshes\n% using geometric algorithms,\n% Advances in Engineering Software,\n% Volume 13, pages 325-331, 1991.\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the vertices.\n%\n% Input, integer TRIANGLE_ORDER, the order of the triangles.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles in the triangulation.\n%\n% Input, integer TRIANGLE_NODE(TRIANGLE_ORDER,TRIANGLE_NUM), \n% the nodes that make up each triangle.\n%\n% Input, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the triangle \n% neighbor list.\n%\n% Input, real P(2), the coordinates of a point.\n%\n% Output, integer TRIANGLE_INDEX, the index of the triangle where the \n% search ended. If a cycle occurred, then TRIANGLE_INDEX = -1.\n%\n% Output, integer EDGE, indicates the position of the point P in\n% triangle TRIANGLE_INDEX:\n% 0, the interior or boundary of the triangle;\n% -1, outside the convex hull of the triangulation, past edge 1;\n% -2, outside the convex hull of the triangulation, past edge 2;\n% -3, outside the convex hull of the triangulation, past edge 3.\n%\n persistent triangle_index_save;\n\n if ( isempty ( triangle_index_save ) )\n triangle_index_save = -1;\n end\n\n count = 0;\n edge = 0;\n\n if ( triangle_index_save < 1 || triangle_num < triangle_index_save )\n triangle_index = floor ( ( triangle_num + 1 ) / 2 );\n else\n triangle_index = triangle_index_save;\n end\n\n while ( 1 )\n\n count = count + 1;\n\n if ( triangle_num < count )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATION_SEARCH_DELAUNAY - Fatal error!\\n' );\n fprintf ( 1, ' The algorithm seems to be cycling.\\n' );\n triangle_index = -1;\n edge = -1;\n return\n end\n%\n% Get the vertices of triangle TRIANGLE_INDEX.\n%\n a = triangle_node(1,triangle_index);\n b = triangle_node(2,triangle_index);\n c = triangle_node(3,triangle_index);\n%\n% Using vertex C as a base, compute the distances to vertices A and B,\n% and the point P.\n%\n dxa = node_xy(1,a) - node_xy(1,c);\n dya = node_xy(2,a) - node_xy(2,c);\n\n dxb = node_xy(1,b) - node_xy(1,c);\n dyb = node_xy(2,b) - node_xy(2,c);\n\n dxp = p(1) - node_xy(1,c);\n dyp = p(2) - node_xy(2,c);\n\n det = dxa * dyb - dya * dxb;\n%\n% Compute the barycentric coordinates of the point P with respect\n% to this triangle.\n%\n alpha = ( dxp * dyb - dyp * dxb ) / det;\n beta = ( dxa * dyp - dya * dxp ) / det;\n gamma = 1.0 - alpha - beta;\n%\n% If the barycentric coordinates are all positive, then the point\n% is inside the triangle and we're done.\n%\n if ( 0.0 <= alpha && 0.0 <= beta && 0.0 <= gamma )\n break\n end\n%\n% At least one barycentric coordinate is negative.\n%\n% If there is a negative barycentric coordinate for which there exists\n% an opposing triangle neighbor closer to the point, move to that triangle.\n%\n% (Two coordinates could be negative, in which case we could go for the\n% most negative one, or the most negative one normalized by the actual\n% distance it represents).\n%\n if ( alpha < 0.0 && 0 < triangle_neighbor(2,triangle_index) )\n triangle_index = triangle_neighbor(2,triangle_index);\n continue;\n elseif ( beta < 0.0 && 0 < triangle_neighbor(3,triangle_index) )\n triangle_index = triangle_neighbor(3,triangle_index);\n continue;\n elseif ( gamma < 0.0 && 0 < triangle_neighbor(1,triangle_index) )\n triangle_index = triangle_neighbor(1,triangle_index);\n continue;\n end\n%\n% All negative barycentric coordinates correspond to vertices opposite\n% sides on the convex hull.\n%\n% Note the edge and exit.\n%\n if ( alpha < 0.0 )\n edge = -2;\n break\n elseif ( beta < 0.0 )\n edge = -3;\n break\n elseif ( gamma < 0.0 )\n edge = -1;\n break\n end\n\n end\n\n triangle_index_save = triangle_index;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_project/fem2d_project.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.398452816687293}}
{"text": "%% Selecting Grains\n%\n%%\n% In this section we discuss how to select grains by properties. We start\n% our discussion by reconstructing the grain structure from a sample EBSD\n% data set.\n\n% load sample EBSD data set\nmtexdata forsterite silent\n\n% restrict it to a subregion of interest.\nebsd = ebsd(inpolygon(ebsd,[5 2 10 5]*10^3));\n\n% remove all not indexed pixels\nebsd = ebsd('indexed');\n\n% reconstruct grains\n[grains, ebsd.grainId] = calcGrains(ebsd,'angle',5*degree);\n\n% smooth them\ngrains = smooth(grains,5);\n\n% plot the orientation data of the Forsterite phase\nplot(ebsd('fo'),ebsd('fo').orientations)\n\n% plot the grain boundary on top of it\nhold on\nplot(grains.boundary,'lineWidth',2)\nhold off\n\n%% Selecting grains by mouse\n% The most easiest way to select a grain is by using the mouse and the\n% command which allows\n% you to select an arbitrary amount of grains. The index of the selected\n% grains appear as the global variable |indSelected| in your workspace\n\nselectInteractive(grains,'lineColor','gold')\n\n% this simulates a mouse click\npause(0.1)\nsimulateClick(9000,3500)\npause(0.1)\n\nglobal indSelected;\ngrains(indSelected)\n\nhold on\nplot(grains(indSelected).boundary,'lineWidth',4,'lineColor','gold')\nhold off\n\n%% Indexing by orientation or position\n% One can also to select a grain by spatial coordinates without user\n% interaction. This is done using the syntax |grains(x,y)|, i.e.,\n\nx = 12000; y = 4000;\n\nhold on\nplot(grains(x,y).boundary,'linewidth',4,'linecolor','blue')\n\nplot(x,y,'marker','s','markerfacecolor','k',...\n 'markersize',10,'markeredgecolor','w')\nhold off\n\n%%\n% Alternatively one can also select all grains with a certain orientation.\n% Lets find all grains with a similar orientation as the one marked in\n% gold. As threshold we shall use 20 degree\n\n% select grains by orientation\ngrains_selected = grains.findByOrientation(grains(indSelected).meanOrientation,20*degree)\n\nhold on\nplot(grains_selected.boundary,'linewidth',4,'linecolor','gold')\nhold off\n\n%% Indexing by a Property\n% In order the generalize the above concept lets remember that the variable\n% |grains| is essentially a large vector of grains. Thus when applying a\n% function like to this variable we obtain a\n% vector of the same lenght with numbers representing the area of each\n% grain\n\ngrain_area = grains.area;\n\n%%\n% As a first rather simple application we could colorize the grains\n% according to their area, i.e., according to the numbers stored in\n% |grain_area|\n\nplot(grains,grain_area)\n\n%%\n% As a second application, we can ask for the largest grain within our data\n% set. The maximum value and its position within a vector are found by the\n% Matlab command |max|.\n\n[max_area,max_id] = max(grain_area)\n\n%%\n% The number |max_id| is the position of the grain with a maximum area within\n% the variable |grains|. We can access this specific grain by direct\n% indexing\n\ngrains(max_id)\n\n%%\n% and so we can plot it\n\nhold on\nplot(grains(max_id).boundary,'linecolor','red','linewidth',4)\nhold off\n\n%%\n% Note that this way of addressing individual grains can be generalized to\n% many grains. E.g. assume we are interested in the largest 5 grains. Then\n% we can sort the vector |grain_area| and take the indices of the 5 largest\n% grains.\n\n[sorted_area,sorted_id] = sort(grain_area,'descend');\n\nlarge_grain_id = sorted_id(2:5);\n\nhold on\nplot(grains(large_grain_id).boundary,'linecolor','Orange','linewidth',4)\nhold off\n\n\n%% Indexing by a Condition\n% By the same syntax as above we can also single out grains that satisfy a\n% certain condition. I.e., to access are grains that are at least one\n% quarter as large as the largest grain we can do\n\ncondition = grain_area > max_area/4;\n\nhold on\nplot(grains(condition).boundary,'linecolor','Yellow','linewidth',4)\nhold off\n\n%%\n% This is a very powerful way of accessing grains as the condition can be\n% build up using any grain property. As an example let us consider the\n% phase. The phase of the first five grains we get by\n\ngrains(1:5).phase\n\n%%\n% Now we can access or grains of the first phase Forsterite by the\n% condition\n\ncondition = grains.phase == 1;\nplot(grains(condition))\n\n%%\n% To make the above more directly you can use the mineral name for indexing\n\ngrains('forsterite')\n\n%%\n% Logical indexing allows also for more complex queries, e.g. selecting all\n% grains perimeter larger than 6000 and at least 600 measurements within\n\ncondition = grains.perimeter>6000 & grains.grainSize >= 600;\n\nselected_grains = grains(condition)\n\nplot(selected_grains)\n\n\n%% The grainId and how to select EBSD inside specific grains\n%\n% Besides, the list of grains the command \n% returns also two other output arguments. \n\nplot(grains)\nlargeGrains = grains(grains.grainSize > 50);\n\ntext(largeGrains,largeGrains.id)\n\n%%\n% The second output argument grainId is a list with the same size as the\n% EBSD measurements that stores for each measurement the corresponding\n% grainId. The above syntax stores this list directly inside the ebsd\n% variable. This enables MTEX to select EBSD data by grains. The following\n% command returns all the EBSD data that belong to grain number 33.\n\nebsd(grains(33))\n\n%%\n% and is equivalent to the command\n\nebsd(ebsd.grainId == 33) \n\n%%\n% The following picture plots the largest grains together with its\n% individual orientation measurements. \n\nplot(ebsd(grains(max_id)),ebsd(grains(max_id)).orientations)\nhold on\nplot(grains(max_id).boundary,'lineWidth',2)\nhold off\n\n\n%% Boundary grains\n% Sometimes it is desirable to remove all boundary grains as they might\n% distort grain statistics. To do so one should remember that each grain\n% boundary has a property |grainId| which stores the ids of the neigbouring\n% grains. In the case of an outer grain boundary, one of the neighbouring\n% grains has the id zero. We can filter out all these boundary segments by\n\n% ids of the outer boundary segment\nouterBoundary_id = any(grains.boundary.grainId==0,2);\n\n% plot the outer boundary segments\nplot(grains)\nhold on\nplot(grains.boundary(outerBoundary_id),'linecolor','red','linewidth',2)\nhold off\n\n%%\n% Now |grains.boundary(outerBoundary_id).grainId| is a list of grain ids\n% where the first column is zero, indicating the outer boundary, and the\n% second column contains the id of the boundary grain. Hence, it remains to\n% remove all grains with these ids.\n\n% next we compute the corresponding grain_id\ngrain_id = grains.boundary(outerBoundary_id).grainId;\n\n% remove all zeros\ngrain_id(grain_id==0) = [];\n\n% and plot the boundary grains\nplot(grains(grain_id))\n\n%%\n% finally, we could remove the boundary grains by\n%\n% grains(grain_id) = []\n%\n% However, boundary grains can be selected more easily be the command\n% ||. \n\nplot(grains(~grains.isBoundary))\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/Grains/SelectingGrains.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.39845280832262786}}
{"text": "function [NV,NF,OV,OE,OV1,OE1,epsilon] = remesh_at_handles(V,F,C,P,BE,CE)\n % REMESH_AT_HANDLES remesh a given mesh using its outline and constraining\n % interrior controls at given handles. Point handles are met exactly and\n % bones are sample at the given rate.\n %\n % [NV,NF] = remesh_at_handles(V,F,C,P,BE,CE)\n %\n % Inputs:\n % V list of vertex positions\n % F list of face indices\n % C list of control vertex positions\n % P list of indices into C for point controls, { 1:size(C,1) }\n % BE list of bones, pairs of indices into C, connecting control vertices, \n % { [] }\n % CE list of \"cage edges\", pairs of indices into ***P***, connecting\n % control ***points***. A \"cage edge\" just tells point boundary conditions \n % to vary linearly along straight lines between the end points, and to be\n % zero for all other handles. { [] }\n % Outputs\n % NV new list of vertex positions\n % NF new list of face indices\n % OV list of vertex positions sent to triangle\n % OE list of edges sent to triangle\n % OV1 list of vertex positions before performing close point collapses and\n % edge splits\n % OE1 list of edges before performing close point collapses and edge splits\n % epsilon used to collapse points and split edges\n %\n % Example:\n % [NV,NF,OV,OE,OV1,OE1] = remesh_at_handles(V,F,C,P,BE,CE);\n % % show a plot of what's sent to triangle\n % subplot(3,1,1);\n % plot([OV1(OE1(:,1),1) OV1(OE1(:,2),1)]',[OV1(OE1(:,1),2) OV1(OE1(:,2),2)]','-','LineWidth',1);\n % hold on;\n % plot(OV1(:,1),OV1(:,2),'.');\n % hold off;\n % axis equal;\n % title('Outline + handle samples');\n % subplot(3,1,2);\n % plot([OV(OE(:,1),1) OV(OE(:,2),1)]',[OV(OE(:,1),2) OV(OE(:,2),2)]','-','LineWidth',1);\n % hold on;\n % plot(OV(:,1),OV(:,2),'.');\n % hold off;\n % axis equal;\n % title('Input to triangle (collapsed points + split edges)');\n % % show a plot of the result\n % subplot(3,1,3);\n % tsurf(NF,NV);\n % hold on;\n % plot([OV(OE(:,1),1) OV(OE(:,2),1)]',[OV(OE(:,1),2) OV(OE(:,2),2)]','-','LineWidth',2);\n % hold off;\n % axis equal;\n % title('Output of triangle');\n\n %% THIS DOES NOT WORK FOR MESHES THAT AREN\"T TOPOLOGICAL DISKS!! HOLES WILL\n %% BE CLOSED\n\n dim = size(V,2);\n assert(dim == size(C,2));\n % only work with 2D\n assert(dim == 2);\n\n % Find all edges in mesh, note internal edges are repeated\n E = sort([F(:,1) F(:,2); F(:,2) F(:,3); F(:,3) F(:,1)]')';\n % determine uniqueness of edges\n [u,m,n] = unique(E,'rows');\n % determine counts for each unique edge\n counts = accumarray(n(:), 1);\n % extract edges that only occurred once\n O = u(counts==1,:);\n % extract unique vertex indices on outline\n [u,m,n] = unique(O(:));\n % original map O = IM(O)\n IM = 1:size(V,1);\n IM(O(:)) = n;\n OV = V(u,:);\n OE = IM(O);\n\n\n\n samples_per_edge = 10;\n % Bone samples\n [BES,BESE] = sample_edges(C,BE,samples_per_edge);\n % Cage edge samples\n [CES,CESE] = sample_edges(C(P,:),CE,samples_per_edge);\n % Append handle samples\n OV = [OV;C(P,:);BES;CES];\n OE = [ ...\n OE; ...\n (size(OV,1)-size(BES,1)-size(CES,1))+BESE; ...\n (size(OV,1)-size(CES,1))+CESE];\n\n % save old values\n OV1 = OV;\n OE1 = OE;\n\n % phony counts to enter while loop\n prev_v_count = size(OV,1)+1;\n prev_e_count = size(OE,1)+1;\n % this epsilon is a parameter that probably needs to be tweaked and should at\n % least be exposed.\n % Use fraction of average edge length\n epsilon = mean(sqrt(sum((OV(OE(:,1),:) - OV(OE(:,2),:)).^2,2)))/8;\n % continue to collapse points and split edges until nothing more to do\n while( prev_v_count ~= size(OV,1) || prev_e_count ~= size(OE,1))\n prev_v_count = size(OV,1);\n prev_e_count = size(OE,1);\n [OV,OE] = collapse_close_points(OV,OE,epsilon);\n [OV,OE] = snap_points_to_close_edges(OV,OE,epsilon);\n end\n\n % Again, max area term here is a heuristic\n %sum((OV(OE(:,1)) - OV(OE(:,2))).^2,2)\n % use a multiple of min edge length\n %max_area = 2*(sqrt(3)/4)*min(sum((OV(OE(:,1),:) - OV(OE(:,2),:)).^2,2));\n max_area = 8*(sqrt(3)/4)*min(sum((OV(OE(:,1),:) - OV(OE(:,2),:)).^2,2));\n [NV,NF] = triangle(OV,OE,[],'Quality',30,'MaxArea',max_area);\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/remesh_at_handles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3984393669667184}}
{"text": "function Rob = createRobots(Robot)\n\n% CREATEROBOTS Create robots structure array.\n% Rob = CREATEROBOTS(Robot) creates the Rob() structure array to be used\n% as SLAM data. The input Robot{} is a cell array of structures as\n% specified by the user in userData.m. There must be one Robot{} per each\n% robot considered in the simulation. See userData.m for details.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nfor rob = 1:numel(Robot)\n \n Ri = Robot{rob}; % input robot structure\n \n % identification\n Ro.rob = rob;\n Ro.id = Ri.id;\n Ro.name = Ri.name;\n Ro.type = Ri.type;\n Ro.motion = Ri.motion;\n \n Ro.sensors = [];\n \n % Robot frame in quaternion form\n ep = [Ri.position;deg2rad(Ri.orientationDegrees)];\n EP = diag([Ri.positionStd;deg2rad(Ri.orientationStd)].^2);\n [qp,QP] = propagateUncertainty(ep,EP,@epose2qpose); % frame and cov. in quaternion\n\n % control and rest of the state\n switch Ri.motion\n \n case {'constVel'}\n % control\n Ro.con.u = [Ri.dv;deg2rad(Ri.dwDegrees)];\n Ro.con.uStd = [Ri.dvStd;deg2rad(Ri.dwStd)];\n Ro.con.U = diag(Ro.con.uStd.^2);\n Ro.com.W = 1/Ro.con.U; % Information matrix\n \n % velocity states\n v = [Ri.velocity;deg2rad(Ri.angularVelDegrees)];\n V = diag([Ri.velStd;deg2rad(Ri.angVelStd)].^2);\n \n % state\n Ro.state.x = [qp;v]; % state\n Ro.state.P = blkdiag(QP,V);\n Ro.state.dx = zeros(12,1);\n \n case {'odometry'}\n % control\n Ro.con.u = [Ri.dx;deg2rad(Ri.daDegrees)];\n Ro.con.uStd = [Ri.dxStd;deg2rad(Ri.daStd)];\n Ro.con.U = diag(Ro.con.uStd.^2);\n Ro.com.W = Ro.con.U^-1; % Information matrix\n \n % state\n Ro.state.x = qp; % state\n Ro.state.P = EP;\n Ro.state.dx = zeros(6,1);\n \n otherwise\n error('Unknown motion model ''%s'' for robot %d.',Robot{rob}.motion,Robot{rob}.id);\n end\n \n Ro.state.r = []; % Points Map.x into state.dx\n Ro.state.size = numel(Ro.state.x); % state size\n Ro.state.dsize = numel(Ro.state.dx);\n\n Ro.frame.r = [];\n Ro.frame.x = qp;\n Ro.frame.P = QP;\n Ro.frame = updateFrame(Ro.frame);\n \n Rob(rob) = Ro; % output robot structure\n \nend\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/createRobots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.39810589200511176}}
{"text": "function cx = cscal ( n, ca, cx, incx )\n\n%*****************************************************************************80\n%\n%% CSCAL scales a complex vector by a constant.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for Fortran Usage,\n% Algorithm 539,\n% ACM Transactions on Mathematical Software,\n% Volume 5, Number 3, September 1979, pages 308-323.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, complex CA, the multiplier.\n%\n% Input, complex CX(*), the vector to be scaled.\n%\n% Input, integer INCX, the increment between successive entries of CX.\n%\n% Output, complex CX(*), the scaled vector.\n%\n cx(1:incx:1+(n-1)*incx) = ca * cx(1:incx:1+(n-1)*incx);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas1_c/cscal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.3979554151424857}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% SPHARM-MAT is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with SPHARM-MAT. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Goal: Fix a binary image by removing bad connectivities\n% inObject: filename string of a binary object in .MAT format\n% info = varargin{1}: connectivity \n% info can be one of four values between 1 and 4 - '1=(6+,18), 2=(18,6+),\n% 3=(6,26), 4=(26,6)'\n% epsilon = varargin{2}: hole size, holes bigger than epsilon won't be\n% filled\n%\n% 04/15/2002 - created by Li Shen\n% Modified by Sungeun Kim (10-09-08)\n\nfunction [bim, origin, vxsize, new_name] = fix_bad_topology(inObject, confs)\n\nepsilon = confs.Epsilon;\nswitch deblank(char(confs.Connectivity))\n case '(6+,18)'\n conn = 1;\n case '(18,6+)'\n conn = 2; \n case '(6,26)'\n conn = 3; \n case '(26,6)'\n conn = 4; \nend\n\n% Read input object dataset\nif ischar(inObject)\n [path,name,ext] = fileparts(inObject);\n\n if ~strcmp(ext, '.mat')\n disp('Input object data should be Matlab data file (*.mat)');\n return;\n end\n\n load(inObject);\n roi = bim; \nelse\n disp('Input Object should be the filename of a binary object (_bim.mat).');\n return;\nend\n\ntic;\n\ninfostr{1} = 'outlier or hole';\ninfostr{2} = 'vertex conn.';\ninfostr{3} = 'edge conn.';\ninfostr{4} = 'ring or hole';\ninfostr{5} = 'single ring';\n\n% display information\ndisp('Make a simply connected volume by removing bad voxels');\ndisp(sprintf('(1) %s, (2) %s, (3) %s, (4) %s, (5) s', ...\n infostr{1}, infostr{2}, infostr{3}, infostr{4}, infostr{5}));\n\n% Make binary image, in case reslice generates 2's\nind = find(roi>0); roi(ind) = 1;\nvol = length(ind);\nind = find(roi<1); roi(ind) = 0;\n\n% routine fix\nroi = routine_fix(roi);\n[vertices, faces] = gen_surf_data(roi,origin,vxsize);\n\n% fill 3d holes\nfor k=1:3\n if (size(vertices,1)-size(faces,1)==2)\n disp('===> No 3D holes, skip');\n break;\n end\n disp('===> fixing 3D holes ...');\n roi = fill3dholes(roi,conn,epsilon,name);\n disp('===> routine fix again ...');\n roi = routine_fix(roi);\n [vertices, faces] = gen_surf_data(roi,origin,vxsize);\nend\n\nfvn = length(find(roi~=bim));\nbim = roi;\n\ndisp(sprintf('fix_vox_num (%d) / vol (%d) = %f%%, save ...', ...\n fvn, vol, fvn*100/vol));\n \n% Save surface object to a new file\npostfix = name(end-2:end);\nif strcmp(postfix, 'bim') | strcmp(postfix,'fix')\n new_name = [confs.OutDirectory '/' name(1:end-3) 'fix'];\nelse\n new_name = [confs.OutDirectory '/' name '_fix'];\nend \n\nif exist(new_name,'file')\n prompt = {'Enter new filename:'};\n dlg_title = 'New File Name';\n num_lines = 1;\n def = {new_name};\n answer = inputdlg(prompt,dlg_title,num_lines,def); \n new_name = answer{1};\nend\n\nsave(new_name, 'bim', 'origin', 'vxsize');\n\nseconds = toc;\nhours = seconds/3600;\ndisp(['seconds=', num2str(seconds), ' hours=', num2str(hours)]);\n\nreturn;\n\n\n%\n% routine fix\n%\n\nfunction roi = routine_fix(roi)\n\nDIM = size(roi);\n\nfixset = [];\n\nfor j = 1:10\n [roi, fs1] = outl_hole(roi, DIM,1);\n [roi, fs2] = vertex_conn(roi, DIM,2);\n [roi, fs3] = edge_conn(roi, DIM,3);\n if (isempty(fs1) & isempty(fs2) & isempty(fs3))\n break;\n else\n if (~isempty(fs1))\n fixset(end+1:end+size(fs1,1),:) = fs1;\n end\n if (~isempty(fs2))\n fixset(end+1:end+size(fs2,1),:) = fs2;\n end\n if (~isempty(fs3))\n fixset(end+1:end+size(fs3,1),:) = fs3;\n end\n end\nend\n\n[roi, fs4] = ring_hole(roi, DIM, 4);\nif (~isempty(fs4))\n fixset(end+1:end+size(fs4,1),:) = fs4; \n for j = 1:10\n [roi, fs1] = outl_hole(roi, DIM,1);\n [roi, fs2] = vertex_conn(roi, DIM,2);\n [roi, fs3] = edge_conn(roi, DIM,3);\n [roi, fs4] = ring_hole(roi, DIM,4);\n if (isempty(fs1) & isempty(fs2) & isempty(fs3) & isempty(fs4))\n break;\n else\n if (~isempty(fs1))\n fixset(end+1:end+size(fs1,1),:) = fs1;\n end\n if (~isempty(fs2))\n fixset(end+1:end+size(fs2,1),:) = fs2;\n end\n if (~isempty(fs3))\n fixset(end+1:end+size(fs3,1),:) = fs3;\n end\n if (~isempty(fs4))\n fixset(end+1:end+size(fs4,1),:) = fs4;\n end\n end\n end\nend\n\nfix_vox_num = size(fixset,1);\n\nreturn;\n\n\n%\n% remove disconnected small components and holes\n%\n\nfunction [roi, fixset] = outl_hole(roi, d, infoid)\n\nroi = reshape(roi,d);\n\nfixset = [];\n\n% check seperated small components (k=1)\n% and then check holes\nval = [0 1];\nfor k = 1:2\n\t[L, num] = bwlabeln(roi,6);\n\t\n\tif num>1\n\t\t% find the background\n\t\tfor i = 1:num\n cnt(i) = length(find(L == i));\n\t\tend\n\t\t[bkgd_size, bkgd_ind] = max(cnt);\n sigind = find(L~=0 & L~=bkgd_ind);\n roi(sigind) = 0;\n [xs,ys,zs] = ind2sub(d, sigind); \n fixset(end+1:end+length(xs),:) = [[xs,ys,zs], xs*0+val(k), xs*0+infoid];\n\tend\n\t\n\troi = 1-roi;\nend\n\nreturn;\n\n\n%\n% fix bad vertex connectivities\n%\n\nfunction [roi, fixset] = vertex_conn(roi, d, infoid)\n\nroi = reshape(roi,d);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% work on 0 vertex connectivies\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% make a work area so that all border voxels belong to the background\nw = ones(d+2);\nw(2:d(1)+1,2:d(2)+1,2:d(3)+1) = roi;\nwd = d+2;\nind = find(w == 0);\nw = zeros(d+2);\nw(2:d(1)+1,2:d(2)+1,2:d(3)+1) = roi;\n\n[xs,ys,zs] = ind2sub(wd,ind);\n\nh = sum([w(sub2ind(wd,xs-1,ys,zs)), ...\n w(sub2ind(wd,xs+1,ys,zs)), ...\n w(sub2ind(wd,xs,ys-1,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs-1)), ...\n w(sub2ind(wd,xs,ys,zs+1))]')';\n\nfixset = [];\n\n% fix ring 0 voxels (single ring)\nind1 = ind(find(h==4 & ...\n w(sub2ind(wd,xs-1,ys,zs))==0 & ...\n w(sub2ind(wd,xs+1,ys,zs))==0 ...\n ));\nind2 = ind(find(h==4 & ...\n w(sub2ind(wd,xs,ys-1,zs))==0 & ...\n w(sub2ind(wd,xs,ys+1,zs))==0 ...\n ));\nind3 = ind(find(h==4 & ...\n w(sub2ind(wd,xs,ys,zs-1))==0 & ...\n w(sub2ind(wd,xs,ys,zs+1))==0 ...\n ));\nind1 = [ind1;ind2;ind3];\nn4 = length(ind1);\nif (n4~=0)\t\n\tw(ind1) = 1;\n [a, b, c] = ind2sub(wd,ind1);\n\tfixset(end+1:end+n4,:) = [[a, b, c]-1, ind1*0+1, ind1*0+5];\nend\n\n% right up forward, right up backward, right down forward, right down backward\nruf = find(w(sub2ind(wd,xs-1,ys+1,zs+1)) == 0 & ...\n sum([w(sub2ind(wd,xs-1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs-1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs+1)), ...\n w(sub2ind(wd,xs-1,ys,zs+1)), ...\n w(sub2ind(wd,xs,ys+1,zs+1))]')' == 6);\n\nrub = find(w(sub2ind(wd,xs-1,ys+1,zs-1)) == 0 & ...\n sum([w(sub2ind(wd,xs-1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs-1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs-1)), ...\n w(sub2ind(wd,xs-1,ys,zs-1)), ...\n w(sub2ind(wd,xs,ys+1,zs-1))]')' == 6);\n\nrdf = find(w(sub2ind(wd,xs+1,ys+1,zs+1)) == 0 & ...\n sum([w(sub2ind(wd,xs+1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs+1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs+1)), ...\n w(sub2ind(wd,xs+1,ys,zs+1)), ...\n w(sub2ind(wd,xs,ys+1,zs+1))]')' == 6);\n\nrdb = find(w(sub2ind(wd,xs+1,ys+1,zs-1)) == 0 & ...\n sum([w(sub2ind(wd,xs+1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs+1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs-1)), ...\n w(sub2ind(wd,xs+1,ys,zs-1)), ...\n w(sub2ind(wd,xs,ys+1,zs-1))]')' == 6);\n\ncube = [];\n\nif (~isempty(ruf))\n cube(end+1:end+length(ruf),:) = ...\n [xs(ruf),ys(ruf),zs(ruf), ...\n xs(ruf)-1,ys(ruf)+1,zs(ruf)+1];\nend\n \nif (~isempty(rub))\n cube(end+1:end+length(rub),:) = ...\n [xs(rub),ys(rub),zs(rub), ...\n xs(rub)-1,ys(rub)+1,zs(rub)-1];\nend\n\nif (~isempty(rdf))\n cube(end+1:end+length(rdf),:) = ...\n [xs(rdf),ys(rdf),zs(rdf), ...\n xs(rdf)+1,ys(rdf)+1,zs(rdf)+1];\nend\n\nif (~isempty(rdb))\n cube(end+1:end+length(rdb),:) = ...\n [xs(rdb),ys(rdb),zs(rdb), ...\n xs(rdb)+1,ys(rdb)+1,zs(rdb)-1];\nend\n\n% adjust according to cube (3: fix bad 0 vertex connectivities)\nif (~isempty(cube))\n len = size(cube,1);\n for i = 1:len\n k = cube(i,:);\n if (w(k(1),k(2),k(3))==0 & w(k(4),k(5),k(6))==0)\n if (nb_sum(w,k(1),k(2),k(3)) >= nb_sum(w,k(4),k(5),k(6)))\n w(k(1),k(2),k(3)) = 1; \n fixset(end+1,:) = [[k(1), k(2), k(3)]-1, 1, infoid];\n else\n w(k(4),k(5),k(6)) = 1; \n fixset(end+1,:) = [[k(4), k(5), k(6)]-1, 1, infoid];\n end\n end\n end\nend\n\ncnts = [length(ruf), length(rub), length(rdf), length(rdb)];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% work on 1 vertex connectivies\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nind = find(w);\n[xs,ys,zs] = ind2sub(wd,ind);\n\n% right up forward, right up backward, right down forward, right down backward\nruf = find(w(sub2ind(wd,xs-1,ys+1,zs+1)) == 1 & ...\n sum([w(sub2ind(wd,xs-1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs-1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs+1)), ...\n w(sub2ind(wd,xs-1,ys,zs+1)), ...\n w(sub2ind(wd,xs,ys+1,zs+1))]')' == 0);\n\nrub = find(w(sub2ind(wd,xs-1,ys+1,zs-1)) == 1 & ...\n sum([w(sub2ind(wd,xs-1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs-1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs-1)), ...\n w(sub2ind(wd,xs-1,ys,zs-1)), ...\n w(sub2ind(wd,xs,ys+1,zs-1))]')' == 0);\n \nrdf = find(w(sub2ind(wd,xs+1,ys+1,zs+1)) == 1 & ...\n sum([w(sub2ind(wd,xs+1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs+1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs+1)), ...\n w(sub2ind(wd,xs+1,ys,zs+1)), ...\n w(sub2ind(wd,xs,ys+1,zs+1))]')' == 0);\n\nrdb = find(w(sub2ind(wd,xs+1,ys+1,zs-1)) == 1 & ...\n sum([w(sub2ind(wd,xs+1,ys,zs)), ...\n w(sub2ind(wd,xs,ys+1,zs)), ...\n w(sub2ind(wd,xs+1,ys+1,zs)), ...\n w(sub2ind(wd,xs,ys,zs-1)), ...\n w(sub2ind(wd,xs+1,ys,zs-1)), ...\n w(sub2ind(wd,xs,ys+1,zs-1))]')' == 0);\n\ncube = [];\n\nif (~isempty(ruf))\n cube(end+1:end+length(ruf),:) = ...\n [xs(ruf),ys(ruf),zs(ruf), ...\n xs(ruf)-1,ys(ruf)+1,zs(ruf)+1];\nend\n \nif (~isempty(rub))\n cube(end+1:end+length(rub),:) = ...\n [xs(rub),ys(rub),zs(rub), ...\n xs(rub)-1,ys(rub)+1,zs(rub)-1];\nend\n\nif (~isempty(rdf))\n cube(end+1:end+length(rdf),:) = ...\n [xs(rdf),ys(rdf),zs(rdf), ...\n xs(rdf)+1,ys(rdf)+1,zs(rdf)+1];\nend\n\nif (~isempty(rdb))\n cube(end+1:end+length(rdb),:) = ...\n [xs(rdb),ys(rdb),zs(rdb), ...\n xs(rdb)+1,ys(rdb)+1,zs(rdb)-1];\nend\n\n% adjust according to cube (4: remove bad 1 voxel connectivities)\nif (~isempty(cube))\n len = size(cube,1);\n for i = 1:len\n k = cube(i,:);\n if (w(k(1),k(2),k(3))==1 & w(k(4),k(5),k(6))==1)\n if (nb_sum(w,k(1),k(2),k(3)) <= nb_sum(w,k(4),k(5),k(6)))\n w(k(1),k(2),k(3)) = 0; \n fixset(end+1,:) = [[k(1), k(2), k(3)]-1, 0, infoid];\n else\n w(k(4),k(5),k(6)) = 0; \n fixset(end+1,:) = [[k(4), k(5), k(6)]-1, 0, infoid];\n end\n end\n end\nend\n\ncnts = [length(ruf), length(rub), length(rdf), length(rdb)];\n\n% make roi consistent with w\nroi = w(2:d(1)+1,2:d(2)+1,2:d(3)+1);\n\nreturn;\n\n\n%\n% fix bad edge connectivities\n%\n\nfunction [roi, fixset] = edge_conn(roi, d, infoid)\n\nroi = reshape(roi,d);\n\n% make a work area so that all border voxels belong to the background\nw = zeros(d+2);\nw(2:d(1)+1,2:d(2)+1,2:d(3)+1) = roi;\nwd = d+2;\n\nind = find(w);\n[xs,ys,zs] = ind2sub(wd,ind);\n\nsqua = [];\n\n% right up and right down\nru = find(w(sub2ind(wd,xs-1,ys,zs)) == 0 & ...\n w(sub2ind(wd,xs,ys+1,zs)) == 0 & ...\n w(sub2ind(wd,xs-1,ys+1,zs)) == 1);\n \nif (~isempty(ru))\n squa(end+1:end+length(ru),:) = ... \n [xs(ru),ys(ru),zs(ru),...\n xs(ru)-1,ys(ru)+1,zs(ru),...\n xs(ru)-1,ys(ru),zs(ru),...\n xs(ru),ys(ru)+1,zs(ru)];\nend\n\nrd = find(w(sub2ind(wd,xs+1,ys,zs)) == 0 & ...\n w(sub2ind(wd,xs,ys+1,zs)) == 0 & ...\n w(sub2ind(wd,xs+1,ys+1,zs)) == 1);\n\nif (~isempty(rd))\n squa(end+1:end+length(rd),:) = ... \n [xs(rd),ys(rd),zs(rd),...\n xs(rd)+1,ys(rd)+1,zs(rd),...\n xs(rd)+1,ys(rd),zs(rd),...\n xs(rd),ys(rd)+1,zs(rd)];\nend\n\n% forward up and forward down\nfu = find(w(sub2ind(wd,xs-1,ys,zs)) == 0 & ...\n w(sub2ind(wd,xs,ys,zs+1)) == 0 & ...\n w(sub2ind(wd,xs-1,ys,zs+1)) == 1);\n\nif (~isempty(fu))\n squa(end+1:end+length(fu),:) = ... \n [xs(fu),ys(fu),zs(fu),...\n xs(fu)-1,ys(fu),zs(fu)+1,...\n xs(fu)-1,ys(fu),zs(fu),...\n xs(fu),ys(fu),zs(fu)+1];\nend\n \nfd = find(w(sub2ind(wd,xs+1,ys,zs)) == 0 & ...\n w(sub2ind(wd,xs,ys,zs+1)) == 0 & ...\n w(sub2ind(wd,xs+1,ys,zs+1)) == 1);\n \nif (~isempty(fd))\n squa(end+1:end+length(fd),:) = ... \n [xs(fd),ys(fd),zs(fd),...\n xs(fd)+1,ys(fd),zs(fd)+1,...\n xs(fd)+1,ys(fd),zs(fd),...\n xs(fd),ys(fd),zs(fd)+1];\nend\n \n% left forward and right forward\nlf = find(w(sub2ind(wd,xs,ys-1,zs)) == 0 & ...\n w(sub2ind(wd,xs,ys,zs+1)) == 0 & ...\n w(sub2ind(wd,xs,ys-1,zs+1)) == 1);\n\nif (~isempty(lf))\n squa(end+1:end+length(lf),:) = ... \n [xs(lf),ys(lf),zs(lf),...\n xs(lf),ys(lf)-1,zs(lf)+1,...\n xs(lf),ys(lf)-1,zs(lf),...\n xs(lf),ys(lf),zs(lf)+1];\nend\n \nrf = find(w(sub2ind(wd,xs,ys+1,zs)) == 0 & ...\n w(sub2ind(wd,xs,ys,zs+1)) == 0 & ...\n w(sub2ind(wd,xs,ys+1,zs+1)) == 1);\n\nif (~isempty(rf))\n squa(end+1:end+length(rf),:) = ... \n [xs(rf),ys(rf),zs(rf),...\n xs(rf),ys(rf)+1,zs(rf)+1,...\n xs(rf),ys(rf)+1,zs(rf),...\n xs(rf),ys(rf),zs(rf)+1];\nend\n\n% adjust according to squa (5: remove bad edge connectivities)\nfixset = [];\nif (~isempty(squa))\n len = size(squa,1);\n for i = 1:len\n k = squa(i,:);\n if (sum([w(k(1),k(2),k(3)) ...\n w(k(4),k(5),k(6)) ...\n w(k(7),k(8),k(9)) ...\n w(k(10),k(11),k(12)) ...\n ]==[1 1 0 0])==4)\n [start, val] = decide_squa(w,k);\n w(k(start),k(start+1),k(start+2)) = val;\n fixset(end+1,:) = [[k(start), k(start+1), k(start+2)]-1, val, infoid];\n end\n end\nend\n\ncnts = [length(ru),length(rd),length(fu),length(fd),length(lf),length(rf)];\n\n% make roi consistent with w\nroi = w(2:d(1)+1,2:d(2)+1,2:d(3)+1);\n\nreturn;\n\n\n%\n% check ring on one slice, and hole between two slices\n%\n\nfunction [roi, fixset] = ring_hole(roi, d, infoid)\n\nroi = reshape(roi,d);\n\n% make a work area so that all border voxels belong to the background\nw = zeros(d+2);\nw(2:d(1)+1,2:d(2)+1,2:d(3)+1) = roi;\nwd = d+2;\n\n% exchange background and object\nw = 1-w;\n\nfixset = [];\n\nfor k = 1:3\n % label each slice\n\tfor i = 1:wd(k)\n switch k\n case 1\n im = reshape(w(i,:,:),wd(2),wd(3)); \n case 2\n im = reshape(w(:,i,:),wd(1),wd(3)); \n case 3\n im = reshape(w(:,:,i),wd(1),wd(2)); \n end\n [lab, num(i)] = bwlabel(im,4);\n L{i} = lab; \n\tend\n % original roi background should be labeled as '1'\n ind = find(num>1);\n for i = 1:length(ind);\n lab = L{ind(i)};\n for j = 1:num(ind(i))\n cnt(j) = length(find(lab == j));\n end\n [mval, mind] = max(cnt);\n if (mind > 1)\n disp('Make background labeled as 1');\n ind1 = find(lab == 1);\n ind2 = find(lab == mind);\n lab(ind2) = 1; % background\n lab(ind1) = mind;\n L{ind(i)} = lab;\n end\n end\n % check multiple component slices\n for i = 1:length(ind);\n lab = L{ind(i)};\n for j = 2:num(ind(i))\n % connect to background in the previous slice\n con_prev = find(lab == j & L{ind(i)-1} == 1);\n % connect to background in the next slice\n con_next = find(lab == j & L{ind(i)+1} == 1);\n if (~isempty(con_prev) & ~isempty(con_next))\n [xs, ys] = find(lab == j); \n switch k\n case 1\n im = reshape(w(ind(i),:,:),wd(2),wd(3));\n sigind = sub2ind(wd,xs*0+ind(i),xs,ys);\n case 2\n im = reshape(w(:,ind(i),:),wd(1),wd(3)); \n sigind = sub2ind(wd,xs,xs*0+ind(i),ys);\n case 3\n im = reshape(w(:,:,ind(i)),wd(1),wd(2)); \n sigind = sub2ind(wd,xs,ys,xs*0+ind(i));\n end\n w(sigind) = 0; % note that really it is assigned 1 to roi\n [xs,ys,zs] = ind2sub(wd,sigind);\n fixset(end+1:end+length(xs),:) = [[xs,ys,zs]-1, xs*0+1, xs*0+infoid];\n end\n end \n end\n % check hole between slices\n for i = 2:(wd(k)-2)\n overlap = L{i}*0;\n overlap_bkgd = find(L{i} == 1 & L{i+1} == 1);\n overlap(overlap_bkgd) = 1;\n [lab, m] = bwlabel(overlap,4);\n if (m>1)\n % deal with only the minimum one;\n for j = 1:m\n cnt(j) = length(find(lab == j));\n end\n [mval, mind] = min(cnt);\n % connect to background in the previous slice\n con_prev = find(lab == mind & L{i-1} == 1);\n % connect to background in the current slice\n con_curr = find(lab == mind & L{i} == 1);\n % connect to background in the next slice\n con_next = find(lab == mind & L{i+1} == 1);\n % connect to background in the next next slice\n con_next_next = find(lab == mind & L{i+2} == 1);\n if ((~isempty(con_curr) | ~isempty(con_prev)) & ...\n (~isempty(con_next) | ~isempty(con_next_next)))\n [xs, ys] = find(lab == mind); \n switch k\n case 1\n sigind = [sub2ind(wd,xs*0+i,xs,ys);sub2ind(wd,xs*0+i+1,xs,ys)];\n case 2\n sigind = [sub2ind(wd,xs,xs*0+i,ys);sub2ind(wd,xs,xs*0+i+1,ys)];\n case 3\n sigind = [sub2ind(wd,xs,ys,xs*0+i);sub2ind(wd,xs,ys,xs*0+i+1)];\n end\n w(sigind) = 0; % note that really it is assigned 1 to roi\n [xs,ys,zs] = ind2sub(wd,sigind);\n fixset(end+1:end+length(xs),:) = [[xs,ys,zs]-1, xs*0+1, xs*0+infoid];\n end\n end \n end\n L = [];\n num = [];\nend\n\n% make roi consistent with w\nroi = 1 - w(2:d(1)+1,2:d(2)+1,2:d(3)+1);\n\nreturn;\n\n\n%\n% select a point to change its value \n% according to maximum number of different neighbours\n%\n\nfunction [start, val] = decide_squa(w,k)\n\nfor i = 1:3:10\n cnt((i-1)/3+1) = nb_sum(w, k(i), k(i+1), k(i+2));\nend\n\ncnt(1:2) = 6 - cnt(1:2);\n\n[v, in] = max(cnt);\n\nstart = (in-1)*3+1;\nif (in < 3)\n val = 0;\nelse\n val = 1;\nend\n\nreturn;\n\n\n%\n% calculate the sum of the direct neighbour\n%\nfunction b = nb_sum(w, x, y, z)\n\nb = sum([w(x-1,y,z), ...\n w(x+1,y,z), ...\n w(x,y-1,z), ...\n w(x,y+1,z), ...\n w(x,y,z-1), ...\n w(x,y,z+1)]);\n\nreturn;\n\n\n\n\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/fix_bad_topology.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3979504208070132}}
{"text": "%% Efficacy of coadministration of Drug X with Statin on cholesterol reduction \n% Copyright 2010 - 2011 MathWorks, Inc.\n\n%% Abstract\n% Statins are the most common class of drugs used for treating\n% hyperlipdemia. However, studies have shown that even at their maximum\n% dosage of 80 mg, many patients do not reach LDL cholesterol goals\n% recommended by the National Cholesterol Education Program Adult Treatment\n% Panel. Combination therapy, in which a second cholesterol-reducing agent that\n% acts via a complementary pathway is coadmininstered with statin, is one\n% alternative of achieving higher efficacy at lower statin dosage. \n%\n% In this example, we test the primary hypothesis that coadminstering drug\n% X with statin is more effective at reducing cholesterol levels than\n% statin monotherapy. \n%\n% *NOTE The dataset used in this example is purely fictitious*.\n%\n% The analysis presented in this example is adapted from the following\n% publication. \n% \n% *Reference* Ballantyne CM, Houri J, Notarbartolo A, Melani L, Lipka LJ,\n% Suresh R, Sun S, LeBeaut AP, Sager PT, Veltri EP; _Ezetimibe Study Group.\n% Effect of ezetimibe coadministered with atorvastatin in 628 patients with\n% primary hypercholesterolemia: a prospective, randomized, double-blind\n% trial._ Circulation. 2003 May 20;107(19):2409-15. \n\n\n%% Data \n% 650 patients were randomly assigned to one of the following 10 treatment\n% groups (65 subjects per group)\n% \n% * Placebo \n% * Drug X (10 mg)\n% * Statin (10, 20, 40 or 80 mg)\n% * Drug X (10 mg) + Statin (10, 20, 40 or 80 mg)\n% \n% Lipid profile (LDL cholesterol, HDL CHolesterol and Triglycerides) was\n% measured at baseline (BL) and at 12 weeks (after the start of treatment).\n% In addition to the lipid profile, patients age, gender and Cardiac Heart\n% Disease (CHD) risk category was also logged at baseline. \n%\n% The data from the study is stored in a Microsoft Excel (R) file. Note\n% that the data could also be imported from other sources such as text\n% files, any JDBC/ODBC compliant database, SAS transport files, etc. \n%\n% The columns in the data are as follows:\n%\n% * ID - Patient ID\n% * Group - Treatment group\n% * Dose_A - Dosage of Statin (mg) \n% * Dose_X - Dosage of Drug X (mg)\n% * Age - Patient Age\n% * Gender - Patient Gender\n% * Risk - Patient CHD risk category (1 is high risk, and 3 is low risk)\n% * LDL_BL - HDL_BL & TC_BL - Lipid levels at baseline\n% * LDL_12wks , HDL_12wks & TC_12wks - Lipid levels after treatment\n\n%% \n% We will import the data into a dataset array that affords better data\n% managemment and organization. \n\n% Import data from an Excel file\n ds = dataset('xlsfile', 'Data.xls') ;\n \n%% Preliminary analysis\n% Our primary efficacy endpoint is the level of LDL cholesterol. Let us\n% compare the LDL C levels at baseline to LDL C levels after treatment\n\n% Use custom scatter plot\n LDLplot(ds.LDL_BL, ds.LDL_12wk, 50, 'g')\n \n%% \n% The mean LDL C level at baseline is around 4.2 and mean level after\n% treatment is 2.5. So, at least for the data pooled across all the\n% treatment groups, it seems that the treatment causes lowering of the LDL\n% cholesterol levels \n\n% Use a grouped scatter plot\n figure \n gscatter(ds.LDL_BL, ds.LDL_12wk, ds.Group) \n\n%%\n% The grouped plot shows that LDL C levels before the start of treatment\n% have similar means. However, the LDL C levels after treatment show\n% difference across treatment groups. The Placebo group show no\n% improvement. Statin monotherapy seems to outperform the Drug X\n% monotherapy. There is overlap between the Statin and Statin + X groups;\n% however, it the combination treatment does seem to perform better that\n% the statin monotherapy. Remember that the \"Statin\" and \"Statin + X\"\n% groups are further split based on Statin dose.\n%\n% In this example, we will use percentage change of LDL C from the baseline\n% level as the primary metric of efficacy. \n\n% Calculate the percentage improvement over baseline level\n\n ds.Change_LDL = ( ds.LDL_BL - ds.LDL_12wk ) ./ ds.LDL_BL * 100 ;\n \n%% \n% In the following graph, we can see that \n% \n% # In the \"Statin\" and \"Statin + X\" group, there appears to be a positive\n% linear correlation between percentage improvement and statin dose \n% # Even at the smallest dose of 10 mg, monotherapy with statin seems to be\n% better than the Drug X monotherapy group\n\n% Visualize effect of treatment and statin dose on perecentage LDL reduction\n figure\n gscatter(ds.ID, ds.Change_LDL, {ds.Group, ds.Dose_S})\n legend('Location', 'Best')\n \n%% Pooled comparison: Is the combination therapy better than statin monotherapy ?\n%\n% First, we will extract percent change in LDL C level for the Statin and\n% the Statin + X groups only. We will test the null hypothesis that the\n% percent change in LDL C level for the \"Statin + X\" groups is greater than\n% that in the \"Statin + X\" using pooled data. We use a 2 sample t-test to\n% test this hypothesis. \n\n% Convert Group into a categorical variable\nds.Group = nominal(ds.Group) ;\n\ngrp1 = ds.Change_LDL(ds.Group == 'Statin') ;\ngrp2 = ds.Change_LDL(ds.Group == 'Statin + X') ;\n\n[h, p] = ttest2(grp1, grp2, .01, 'left')\n\n%% \n% We performed a tailed hypothesis to see if Statin + X group (grp2) is\n% better than the Statin group (grp1). We test against the alternative that\n% that mean LDL change of grp1 (Statin only) is less than mean LDL change\n% of grp2 (Statin + X)\n% \n% The null hypothesis is rejected (p < 0.01), implying that grp1 mean is\n% less that grp2 mean, i.e. the Statin group is less effective at lowering\n% LDL C levels than the Statin + X group. \n% \n% The pooled analysis shows that coadministering drug X with statin is more\n% effective than statin monotherapy. \n\n%% Effect of Treatment, Statin Dose and Dose by Treatment interaction\n% Our analysis so far was done on pooled data. We analysed the effect of\n% treatment (statin alone (X = 0) vs. statin + 10 mg X) on the LDL C\n% levels. We ignored levels of statin dose within each treatment group\n% \n% Next, we will perform a 2-way ANOVA (analysis of variance) to\n% simultaneously understand the effect of both factors - statin dose (4\n% levels - 10 20, 40, 80 mg) and Treatment (2 level - statin only or\n% Statin + 10 mg X ) - on the percentage change of LDL C levels. \n% \n\n% First, we filter the data to include only the Statin and Statin + X groups \nds1 = ds(ds.Group == 'Statin' | ds.Group == 'Statin + X', :) ;\n\nanovan(ds1.Change_LDL , {ds1.Dose_S, ds1.Group } , ...\n 'varnames' , {'Statin Dose', 'Treatment'} ) ; \n \n \n%% Effect of Statin Dose on incremental increase in percentage LDL reduction\n% The ANOVA results indicate that statin dose is a significant factor, but\n% it doesn't compare means across individual dose-treatment level\n% combination. Let's look at the individual cell means. \n\nds2 = grpstats(ds1 , {'Dose_X', 'Dose_S'}, '', 'DataVars', 'Change_LDL') \n\n\n%%\n% Convert to wide format\nds2 = unstack(ds2, 'mean_Change_LDL' , 'Dose_X', ...\n 'NewDataVarNames' , {'Change_LDL_St', 'Change_LDL_St_X'} )\n\n \n \n \n%%\n% From the above table, we can clearly see that the average efficacy of the\n% combination therapy is better than statin monotherapy at all statin\n% dosages. \n% \n% In the plot of the individual means, notice that the percentage reduction\n% in LDL C levels achieved in the low dose combination therapy group (~50.5\n% %) is comparable to that achieved in the higher dose Statin monotherapy\n% group (~ 49.4 %). Thus combination therapy with Drug X could help\n% patients that cannot tolerate high statin doses. \n\nfigure\nbar([ds2.Change_LDL_St, ds2.Change_LDL_St_X])\nset(gca, 'XTickLabel', [10, 20 40, 80])\ncolormap summer\nxlabel('Statin Dose Groups(mg)')\nylabel('Percentage reduction of LDL C from Baseline (mmol/L)')\nlegend('Statin', 'Statin + X')\n\n%% Regression analysis: Effect of statin dose on percent LDL C reduction \n% In the above graph, there appears to be linear improvement in the\n% effectiveness metric for both treatment groups. In general it seems that\n% for every doubling of the statin dose, there is a 5-6 point improvement\n% in the percentage LDL C reduction. Let's fit a linear regression line to\n% the entire dataset, instead of to the mean level.\n% \nx = ds1.Dose_S ( ds1.Group == 'Statin' ) ;\ny = ds1.Change_LDL( ds1.Group == 'Statin' ) ; \n\nx1 = ds1.Dose_S (ds1.Group == 'Statin + X') ;\ny1 = ds1.Change_LDL(ds1.Group == 'Statin + X') ; \n\n%% \n\ncftool\n\n%% \n% The regression line for the Statin and the Statin + X group run almost\n% parallel. This probably indicates mechanism of actions of drug X and\n% statins are independent. \n\n% Fit \n[m1, m2] = createFit(x,y,x1, y1)\n\n%% Secondary Analysis: Consistency of effect across subgroups, age and gender\n% Finally, we will make a visual check to ensure that the efficacy of the\n% Statin + X treatment at various statin doses is consistent across gender\n% and age subgroups. We will perform this check for only the Statin + X\n% treatment group.\n\nidx = ds.Group == 'Statin + X' ; \nboxplot(ds.Change_LDL(idx), { ds.Dose_S(idx), ds.Gender(idx)} )\n\n%% \n% We will convert the continuous age variable into a catergorical variable,\n% with 2 categories: Age < 65 and Age >= 65 \n\n% Convert age into a ordinal array\nds.AgeGroup = ordinal(ds.Age ,{'< 65', '>= 65'} , [] ,[0 65 100] ) ;\n\n% Plot\nboxplot(ds.Change_LDL(idx), { ds.Dose_S(idx), ds.AgeGroup(idx)} )\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30291-matlab-tools-for-scientists-introduction-to-statistical-analysis/Demo/analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.3976392897628519}}
{"text": "function [taumat, thetamat] ...\n = SimulateControl(thetalist, dthetalist, g, Ftipmat, Mlist, ...\n Glist, Slist, thetamatd, dthetamatd, ...\n ddthetamatd, gtilde, Mtildelist, Gtildelist, ...\n Kp, Ki, Kd, dt, intRes)\n% *** CHAPTER 11: ROBOT CONTROL *** \n% Takes thetalist: n-vector of initial joint variables,\n% dthetalist: n-vector of initial joint velocities,\n% g: Actual gravity vector g,\n% Ftipmat: An N x 6 matrix of spatial forces applied by the\n% end-effector (If there are no tip forces, the user should \n% input a zero and a zero matrix will be used),\n% Mlist: Actual list of link frames i relative to i? at the home \n% position,\n% Glist: Actual spatial inertia matrices Gi of the links,\n% Slist: Screw axes Si of the joints in a space frame, in the format\n% of a matrix with the screw axes as the columns,\n% thetamatd: An Nxn matrix of desired joint variables from the \n% reference trajectory,\n% dthetamatd: An Nxn matrix of desired joint velocities,\n% ddthetamatd: An Nxn matrix of desired joint accelerations,\n% gtilde: The gravity vector based on the model of the actual robot\n% (actual values given above),\n% Mtildelist: The link frame locations based on the model of the \n% actual robot (actual values given above),\n% Gtildelist: The link spatial inertias based on the model of the \n% actual robot (actual values given above),\n% Kp: The feedback proportional gain (identical for each joint),\n% Ki: The feedback integral gain (identical for each joint),\n% Kd: The feedback derivative gain (identical for each joint),\n% dt: The timestep between points on the reference trajectory.\n% intRes: Integration resolution is the number of times integration \n% (Euler) takes places between each time step. Must be an \n% integer value greater than or equal to 1.\n% Returns taumat: An Nxn matrix of the controller commanded joint \n% forces/torques, where each row of n forces/torques \n% corresponds to a single time instant,\n% thetamat: An Nxn matrix of actual joint angles.\n% The end of this function plots all the actual and desired joint angles.\n% Example Usage\n% \n% clc; clear;\n% thetalist = [0.1; 0.1; 0.1];\n% dthetalist = [0.1; 0.2; 0.3];\n% %Initialize robot description (Example with 3 links)\n% g = [0; 0; -9.8];\n% M01 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.089159]; [0, 0, 0, 1]];\n% M12 = [[0, 0, 1, 0.28]; [0, 1, 0, 0.13585]; [-1, 0 ,0, 0]; [0, 0, 0, 1]];\n% M23 = [[1, 0, 0, 0]; [0, 1, 0, -0.1197]; [0, 0, 1, 0.395]; [0, 0, 0, 1]];\n% M34 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.14225]; [0, 0, 0, 1]];\n% G1 = diag([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]);\n% G2 = diag([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]);\n% G3 = diag([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]);\n% Glist = cat(3, G1, G2, G3);\n% Mlist = cat(3, M01, M12, M23, M34); \n% Slist = [[1; 0; 1; 0; 1; 0], ...\n% [0; 1; 0; -0.089; 0; 0], ...\n% [0; 1; 0; -0.089; 0; 0.425]];\n% dt = 0.01;\n% %Create a trajectory to follow\n% thetaend =[pi / 2; pi; 1.5 * pi];\n% Tf = 1;\n% N = Tf / dt;\n% method = 5;\n% thetamatd = JointTrajectory(thetalist, thetaend, Tf, N, method);\n% dthetamatd = zeros(N, 3);\n% ddthetamatd = zeros(N, 3);\n% dt = Tf / (N - 1);\n% for i = 1: N - 1\n% dthetamatd(i + 1, :) = (thetamatd(i + 1, :) - thetamatd(i, :)) / dt;\n% ddthetamatd(i + 1, :) = (dthetamatd(i + 1, :) ...\n% - dthetamatd(i, :)) / dt;\n% end\n% %Possibly wrong robot description (Example with 3 links)\n% gtilde = [0.8; 0.2; -8.8];\n% Mhat01 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.1]; [0, 0, 0, 1]];\n% Mhat12 = [[0, 0, 1, 0.3]; [0, 1, 0, 0.2]; [-1, 0 ,0, 0]; [0, 0, 0, 1]];\n% Mhat23 = [[1, 0, 0, 0]; [0, 1, 0, -0.2]; [0, 0, 1, 0.4]; [0, 0, 0, 1]];\n% Mhat34 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.2]; [0, 0, 0, 1]];\n% Ghat1 = diag([0.1, 0.1, 0.1, 4, 4, 4]);\n% Ghat2 = diag([0.3, 0.3, 0.1, 9, 9, 9]);\n% Ghat3 = diag([0.1, 0.1, 0.1, 3, 3, 3]);\n% Gtildelist = cat(3, Ghat1, Ghat2, Ghat3);\n% Mtildelist = cat(4, Mhat01, Mhat12, Mhat23, Mhat34); \n% Ftipmat = ones(N, 6);\n% Kp = 20;\n% Ki = 10;\n% Kd = 18;\n% intRes = 8;\n% [taumat, thetamat] ...\n% = SimulateControl(thetalist, dthetalist, g, Ftipmat, Mlist, Glist, ...\n% Slist, thetamatd, dthetamatd, ddthetamatd, gtilde, ...\n% Mtildelist, Gtildelist, Kp, Ki, Kd, dt, intRes);\n% \n\nFtipmat = Ftipmat';\nthetamatd = thetamatd';\ndthetamatd = dthetamatd';\nddthetamatd = ddthetamatd';\nn = size(thetamatd, 2);\ntaumat = zeros(size(thetamatd));\nthetamat = zeros(size(thetamatd));\nthetacurrent = thetalist;\ndthetacurrent = dthetalist;\neint = zeros(size(thetamatd, 1), 1);\nfor i=1: n\n taulist ...\n = ComputedTorque(thetacurrent, dthetacurrent, eint, gtilde, ...\n Mtildelist, Gtildelist, Slist, thetamatd(:, i), ...\n dthetamatd(:, i), ddthetamatd(:, i), Kp, Ki, Kd);\n for j=1: intRes\n ddthetalist ...\n = ForwardDynamics(thetacurrent, dthetacurrent, taulist, g, ...\n Ftipmat(:, i), Mlist, Glist, Slist); \n [thetacurrent, dthetacurrent] ...\n = EulerStep(thetacurrent, dthetacurrent, ddthetalist, ...\n (dt / intRes));\n end\n taumat(:, i) = taulist;\n thetamat(:, i) = thetacurrent; \n eint = eint + (dt*(thetamatd(:, i) - thetacurrent));\nend\n%Output using matplotlib\nlinks = size(thetamat, 1);\nleg = cell(1, 2 * links);\ntime=0: dt: dt * n - dt;\ntimed=0: dt: dt * n - dt;\nfigure\nhold on\nfor i=1: links\n col = rand(1, 3);\n plot(time, (thetamat(i, :)'), '-', 'Color', col)\n plot(timed, (thetamatd(i, :)'), '.', 'Color', col)\n leg{2 * i - 1} = (strcat('ActualTheta', num2str(i)));\n leg{2 * i} = (strcat('DesiredTheta', num2str(i)));\nend\ntitle('Plot of Actual and Desired Joint Angles')\nxlabel('Time')\nylabel('Joint Angles')\nlegend(leg, 'Location', 'NorthWest')\ntaumat = taumat';\nthetamat = thetamat';\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/SimulateControl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.39738824839680414}}
{"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%\tlengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us %to add a specific muscle model, please let Nick (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the BEAM-EXAMPLE geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction BeamCurve()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 256; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nNy = 256; % # of Eulerian Grid Pts. in y-Direction (MUST BE EVEN!!!)\nLx = 1.0; % Length of Eulerian Grid in x-Direction\nLy = 1.0; % Length of Eulerian Grid in y-Direction\n\n\n% Immersed Structure Geometric / Dynamic Parameters %\nN = 1.5*Nx; % Number of Lagrangian Pts. (2x resolution of Eulerian grid)\na = 0.5; % Length of beam (only in x-coordinate)\nstruct_name = 'BeamCurve'; % Name for .vertex, .spring, .beam, .target, etc files.\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(N,Lx,a);\n\n\n% Plot Geometry to test\nplot(xLag,yLag,'r-'); hold on;\nplot(xLag,yLag,'*'); hold on;\nxlabel('x'); ylabel('y');\naxis square;\n\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .beam file!\nk_Beam = 5e11; C = 0.0;\nprint_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name);\n\n% Prints .target file! \nk_Target = 1.75e8;\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name)\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called rubberband.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag);\n\n vertex_fid = fopen([struct_name '.vertex'], 'w');\n\n fprintf(vertex_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n X_v = xLag(s);\n Y_v = yLag(s);\n fprintf(vertex_fid, '%1.16e %1.16e\\n', X_v, Y_v);\n end\n\n fclose(vertex_fid); \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints Vertex points to a file called rubberband.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name)\n\n N = length(xLag);\n\n target_fid = fopen([struct_name '.target'], 'w');\n\n fprintf(target_fid, '%d\\n', 2 );\n\n fprintf(target_fid, '%d %1.16e\\n', 1, k_Target);\n fprintf(target_fid, '%d %1.16e\\n', N, k_Target);\n\n fclose(target_fid); \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints BEAM (Torsional Spring) points to a file called rubberband.beam\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name)\n\n % k_Beam: beam stiffness\n % C: beam curvature\n \n N = length(xLag); % NOTE: Total number of beams = Number of Total Lag Pts. - 2\n\n beam_fid = fopen([struct_name '.beam'], 'w');\n\n fprintf(beam_fid, '%d\\n', N-2 );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %BEAMS BETWEEN VERTICES\n for s = 2:N-1\n if s <= N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C); \n else\n %Case s=N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, 1, k_Beam, C); \n end\n end\n fclose(beam_fid); \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called rubberband.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Rest,struct_name)\n\n N = length(xLag);\n\n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', N );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %SPRINGS BETWEEN VERTICES\n for s = 1:N\n if s < N \n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n else\n %Case s=N\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, 1, k_Spring, ds_Rest); \n end\n end\n fclose(spring_fid); \n \n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(N,Lx,a)\n\n% The immsersed structure is a curved line %\nds = a/(N-1);\n\nxLag(1) = -a/2;%Lx/2-a/2;\nyLag(1) = 0.0;\nfor i=2:N\n \n xLag(i) = xLag(i-1) + ds;\n x = xLag(i);\n yLag(i) = -2*( (x)^2 - (a/2)^2 );\n\nend\n\nxLag = xLag + Lx/2;\nyLag = yLag + Lx/2;\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_Wobbly_Beam/Beam_256/BeamCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39735374981948346}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% FANUC MATE M710iC/50, FANUC Robotics Europe.\n%\n% Authors: Carlos Carrazoni Perez, Juan Jose Perez Hernandez & David\n% Martinez Pascual\n% Universidad Miguel Hernandez de Elche. \n% date: 7/1/2019\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% Copyright (C) 2019, by Carlos Carrazoni Perez, Juan Jose Perez Hernandez\n% & David Martinez Pascual\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction robot = parameters()\n\n\nrobot.name= 'Fanuc_M_710iC_50';\n\n%Path where everything is stored for this robot\nrobot.path = 'robots/fanuc/M_710iC_50';\n%Tabla de D-H\nrobot.DH.theta= '[q(1)+pi/2 q(2)+pi/2 q(3) q(4) q(5) q(6)]';\nrobot.DH.d='[0.565 0 0 1.016 0 0.175]';\nrobot.DH.a='[0.15 0.87 0.17 0 0 0]';\nrobot.DH.alpha= '[pi/2 0 pi/2 pi/2 -pi/2 0]';\nrobot.J=[];\n\nrobot.inversekinematic_fn = 'inversekinematic_fanuc_m710(robot, T)';\n\n%number of degrees of freedom\nrobot.DOF = 6;\n\n%rotational: 0, translational: 1\nrobot.kind=['R' 'R' 'R' 'R' 'R' 'R'];\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum\n deg2rad(-135) deg2rad(90); %Axis 2, minimum, maximum\n deg2rad(-160) deg2rad(280); %Axis 3\n deg2rad(-360) deg2rad(360); %Axis 4\n deg2rad(-125) deg2rad(125); %Axis 5\n deg2rad(-360) deg2rad(360)]; %Axis 6\n\n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(175); %Axis 1, rad/s\n deg2rad(175); %Axis 2, rad/s\n deg2rad(175); %Axis 3, rad/s\n deg2rad(250); %Axis 4, rad/s\n deg2rad(250); %Axis 5, rad/s\n deg2rad(355)];%Axis 6, rad/s\n% end effectors maximum velocity\nrobot.linear_velmax = 1.0; %m/s, not specified\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\nrobot.tool_activated=1;\n\n% GRAPHICS\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [0.9 0.9 0]%./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-1.5 1.5 -1.5 1.5 0 2];\n%read graphics files\nrobot = read_graphics(robot);\n\n%robot.tool=load_robot('equipment/end_tools','water_cutter');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DYNAMIC PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrobot.has_dynamics=1;\n\n%consider friction in the computations\nrobot.dynamics.friction=0;\n\n%link masses (kg)\nrobot.dynamics.masses=[191.865 71.802 111.5 27.55 5.705 0.674];\n\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[-0.109 -0.099 0.053; %(rx, ry, rz) link 1\n -0.466 -0.001 -0.287; %(rx, ry, rz) link 2\n -0.086 0.032 0.007; %(rx, ry, rz) link 3\n 0 0.342 0.011; %(rx, ry, rz) link 4\n 0 -0.015 0.076 ; %(rx, ry, rz) link 5\n 0 0 0.010];%(rx, ry, rz) link 6\n\n%Inertia matrices of each link with respect to its D-H reference system.\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, for each row\nrobot.dynamics.Inertia=[8.411 9.434\t9.499 -2.810\t0.691\t1.396;\n 6.297 28.162\t22.396 -0.049\t-0.012\t-9.398;\n 2.313 3.367\t2.986\t0.467\t0.232\t-0.285;\n 4.863\t0.072\t4.846\t-0.002\t0\t0;\n 0.065\t0.058\t0.022\t0\t0.004 0;\n 0.000768\t0.000767\t0.001368\t0\t0\t0];\n\n%Speed reductor at each joint\nrobot.motors.G=[10 20 120 200 300 1];\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/FANUC/M_710iC_50/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3968648601865095}}
{"text": "%%*****************************************************************************\n%% sqlp: solve an semidefinite-quadratic-linear program\n%% by infeasible path-following method.\n%%\n%% [obj,X,y,Z,info,runhist] = sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0);\n%%\n%% Input: blk: a cell array describing the block diagonal structure of SQL data.\n%% At: a cell array with At{p} = [svec(Ap1) ... svec(Apm)]\n%% b,C: data for the SQL instance.\n%% (X0,y0,Z0): an initial iterate (if it is not given, the default is used).\n%% OPTIONS: a structure that specifies parameters required in sqlp.m,\n%% (if it is not given, the default in sqlparameters.m is used).\n%%\n%% Output: obj = [].\n%% (X,y,Z): an approximately optimal solution or a primal or dual\n%% infeasibility certificate.\n%% info.termcode = termination-code\n%% info.iter = number of iterations\n%% info.obj = [primal-obj, dual-obj]\n%% info.cputime = total-time\n%% info.gap = gap\n%% info.pinfeas = primal_infeas\n%% info.dinfeas = dual_infeas\n%% runhist.pobj = history of primal objective value.\n%% runhist.dobj = history of dual objective value.\n%% runhist.gap = history of .\n%% runhist.pinfeas = history of primal infeasibility.\n%% runhist.dinfeas = history of dual infeasibility.\n%% runhist.cputime = history of cputime spent.\n%%----------------------------------------------------------------------------\n%% The OPTIONS structure specifies the required parameters:\n%% vers gam predcorr expon gaptol inftol steptol\n%% maxit printlevel scale_data ...\n%% (all have default values set in sqlparameters.m).\n%%*************************************************************************\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*************************************************************************\n\nfunction [obj,X,y,Z,info,runhist] = sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0)\n\nif (nargin < 5); OPTIONS = []; end\n\nisemptyAtb = 0;\nif isempty(At) && isempty(b);\n %% Add redundant constraint: <-I,X> <= 0\n b = 0;\n At = ops(ops(blk,'identity'),'*',-1);\n numblk = size(blk,1);\n blk{numblk+1,1} = 'l'; blk{numblk+1,2} = 1;\n At{numblk+1,1} = 1; C{numblk+1,1} = 0;\n isemptyAtb = 1;\nend\n%%\n%%-----------------------------------------\n%% get parameters from the OPTIONS structure.\n%%-----------------------------------------\n%%\n\nmatlabversion = sscanf(version,'%f');\nif strcmp(computer,'PCWIN64') || strcmp(computer,'GLNXA64')\n par.computer = 64;\nelse\n par.computer = 32;\nend\npar.matlabversion = matlabversion(1);\npar.vers = 0;\npar.predcorr = 1;\npar.gam = 0;\npar.expon = 1;\npar.gaptol = 1e-8;\npar.inftol = 1e-8;\npar.steptol = 1e-6;\npar.maxit = 100;\npar.printlevel = 3;\npar.stoplevel = 1;\npar.scale_data = 0;\npar.spdensity = 0.4;\npar.rmdepconstr = 0;\npar.smallblkdim = 50;\npar.schurfun = cell(size(blk,1),1);\npar.schurfun_par = cell(size(blk,1),1);\n%%\nparbarrier = cell(size(blk,1),1);\nfor p = 1:size(blk,1)\n pblk = blk(p,:);\n if strcmp(pblk{1},'s') || strcmp(pblk{1},'q')\n parbarrier{p} = zeros(1,length(pblk{2}));\n elseif strcmp(pblk{1},'l') || strcmp(pblk{1},'u' )\n parbarrier{p} = zeros(1,sum(pblk{2}));\n end\nend\nparbarrier_0 = parbarrier;\n%%\nif nargin > 4,\n if isfield(OPTIONS,'vers'); par.vers = OPTIONS.vers; end\n if isfield(OPTIONS,'predcorr'); par.predcorr = OPTIONS.predcorr; end\n if isfield(OPTIONS,'gam'); par.gam = OPTIONS.gam; end\n if isfield(OPTIONS,'expon'); par.expon = OPTIONS.expon; end\n if isfield(OPTIONS,'gaptol'); par.gaptol = OPTIONS.gaptol; end\n if isfield(OPTIONS,'inftol'); par.inftol = OPTIONS.inftol; end\n if isfield(OPTIONS,'steptol'); par.steptol = OPTIONS.steptol; end\n if isfield(OPTIONS,'maxit'); par.maxit = OPTIONS.maxit; end\n if isfield(OPTIONS,'printlevel'); par.printlevel = OPTIONS.printlevel; end\n if isfield(OPTIONS,'stoplevel'); par.stoplevel = OPTIONS.stoplevel; end\n if isfield(OPTIONS,'scale_data'); par.scale_data = OPTIONS.scale_data; end\n if isfield(OPTIONS,'spdensity'); par.spdensity = OPTIONS.spdensity; end\n if isfield(OPTIONS,'rmdepconstr'); par.rmdepconstr = OPTIONS.rmdepconstr; end\n if isfield(OPTIONS,'smallblkdim'); par.smallblkdim = OPTIONS.smallblkdim; end\n if isfield(OPTIONS,'parbarrier');\n parbarrier = OPTIONS.parbarrier;\n if isempty(parbarrier); parbarrier = parbarrier_0; end\n if ~iscell(parbarrier);\n tmp = parbarrier; clear parbarrier; parbarrier{1} = tmp;\n end\n if (length(parbarrier) < size(blk,1))\n len = length(parbarrier);\n parbarrier(len+1:size(blk,1)) = parbarrier_0(len+1:size(blk,1));\n end\n end\n if isfield(OPTIONS,'schurfun');\n par.schurfun = OPTIONS.schurfun;\n if ~isempty(par.schurfun); par.scale_data = 0; end\n end\n if isfield(OPTIONS,'schurfun_par'); par.schurfun_par = OPTIONS.schurfun_par; end\n if isempty(par.schurfun); par.schurfun = cell(size(blk,1),1); end\n if isempty(par.schurfun_par); par.schurfun_par = cell(size(blk,1),1); end\nend\nif (size(blk,2) > 2); par.smallblkdim = 0; end\n%%\n%%-----------------------------------------\n%% convert matrices to cell arrays.\n%%-----------------------------------------\n%%\nif ~iscell(At); At = {At}; end;\nif ~iscell(C); C = {C}; end;\nif all(size(At) == [size(blk,1), length(b)]);\n convertyes = zeros(size(blk,1),1);\n for p = 1:size(blk,1)\n if strcmp(blk{p,1},'s') && all(size(At{p,1}) == sum(blk{p,2}))\n convertyes(p) = 1;\n end\n end\n if any(convertyes)\n if (par.printlevel);\n fprintf('\\n sqlp: converting At into required format');\n end\n At = svec(blk,At,ones(size(blk,1),1));\n end\nend\n%%\n%%-----------------------------------------\n%% validate SQLP data.\n%%-----------------------------------------\n%%\n% tstart = cputime;\n[blk,At,C,b,blkdim,numblk,parbarrier] = validate(blk,At,C,b,par,parbarrier);\n[blk,At,C,b,iscmp] = convertcmpsdp(blk,At,C,b);\nif (iscmp) && (par.printlevel>=2);\n fprintf('\\n SQLP has complex data');\nend\nif (nargin <= 5) || (isempty(X0) || isempty(y0) || isempty(Z0));\n par.startpoint = 1;\n [X0,y0,Z0] = infeaspt(blk,At,C,b);\nelse\n par.startpoint = 2;\n if ~iscell(X0); X0 = {X0}; end;\n if ~iscell(Z0); Z0 = {Z0}; end;\n y0 = real(y0);\n if (length(y0) ~= length(b));\n error('sqlp: length of b and y0 not compatible');\n end\n [X0,Z0] = validate_startpoint(blk,X0,Z0,par.spdensity,iscmp);\nend\nif (par.printlevel>=2)\n fprintf('\\n num. of constraints = %2.0d',length(b));\n if blkdim(1);\n fprintf('\\n dim. of sdp var = %2.0d,',blkdim(1));\n fprintf(' num. of sdp blk = %2.0d',numblk(1));\n end\n if blkdim(2);\n fprintf('\\n dim. of socp var = %2.0d,',blkdim(2));\n fprintf(' num. of socp blk = %2.0d',numblk(2));\n end\n if blkdim(3); fprintf('\\n dim. of linear var = %2.0d',blkdim(3)); end\n if blkdim(4); fprintf('\\n dim. of free var = %2.0d',blkdim(4)); end\nend\n%%\n%%-----------------------------------------\n%% detect unrestricted blocks in linear blocks\n%%-----------------------------------------\n%%\nuser_supplied_schurfun = 0;\nfor p = 1:size(blk,1)\n if ~isempty(par.schurfun{p}); user_supplied_schurfun = 1; end\nend\nif (user_supplied_schurfun == 0)\n [blk2,At2,C2,ublkinfo,parbarrier2,X02,Z02] = ...\n detect_ublk(blk,At,C,parbarrier,X0,Z0,par.printlevel);\nelse\n blk2 = blk; At2 = At; C2 = C;\n parbarrier2 = parbarrier; X02 = X0; Z02 = Z0;\n ublkinfo = cell(size(blk2,1),1);\nend\nublksize = blkdim(4);\nfor p = 1:size(ublkinfo,1)\n ublksize = ublksize + length(ublkinfo{p});\nend\n%%\n%%-----------------------------------------\n%% detect diagonal blocks in semidefinite blocks\n%%-----------------------------------------\n%%\nif (user_supplied_schurfun==0)\n [blk3,At3,C3,diagblkinfo,diagblkchange,parbarrier3,X03,Z03] = ...\n detect_lblk(blk2,At2,C2,b,parbarrier2,X02,Z02,par.printlevel);\nelse\n blk3 = blk2; At3 = At2; C3 = C2;\n parbarrier3 = parbarrier2; X03 = X02; Z03 = Z02;\n diagblkchange = 0;\n diagblkinfo = cell(size(blk3,1),1);\nend\n%%\n%%-----------------------------------------\n%% main solver\n%%-----------------------------------------\n%%\n% exist_analytic_term = 0;\n% for p = 1:size(blk3,1);\n% idx = find(parbarrier3{p} > 0);\n% if ~isempty(idx); exist_analytic_term = 1; end\n% end\n%\nif (par.vers == 0);\n if blkdim(1); par.vers = 1; else par.vers = 2; end\nend\npar.blkdim = blkdim;\npar.ublksize = ublksize;\n[obj,X3,y,Z3,info,runhist] = ...\n sqlpmain(blk3,At3,C3,b,par,parbarrier3,X03,y0,Z03);\n%%\n%%-----------------------------------------\n%% recover semidefinite blocks from linear blocks\n%%-----------------------------------------\n%%\nif any(diagblkchange)\n X2 = cell(size(blk2,1),1); Z2 = cell(size(blk2,1),1);\n count = 0;\n for p = 1:size(blk2,1)\n pblk = blk2(p,:);\n n = sum(pblk{2});\n blkno = diagblkinfo{p,1};\n idxdiag = diagblkinfo{p,2};\n idxnondiag = diagblkinfo{p,3};\n if ~isempty(idxdiag)\n len = length(idxdiag);\n Xtmp = [idxdiag,idxdiag,X3{end}(count+1:count+len); n, n, 0];\n Ztmp = [idxdiag,idxdiag,Z3{end}(count+1:count+len); n, n, 0];\n if ~isempty(idxnondiag)\n [ii,jj,vv] = find(X3{blkno});\n Xtmp = [Xtmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok\n [ii,jj,vv] = find(Z3{blkno});\n Ztmp = [Ztmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok\n end\n X2{p} = spconvert(Xtmp);\n Z2{p} = spconvert(Ztmp);\n count = count + len;\n else\n X2(p) = X3(blkno); Z2(p) = Z3(blkno);\n end\n end\nelse\n X2 = X3; Z2 = Z3;\nend\n%%\n%%-----------------------------------------\n%% recover linear block from unrestricted block\n%%-----------------------------------------\n%%\nnumblk = size(blk,1);\nnumblknew = numblk;\nX = cell(numblk,1); Z = cell(numblk,1);\nfor p = 1:numblk\n n = blk{p,2};\n if isempty(ublkinfo{p,1})\n X{p} = X2{p}; Z{p} = Z2{p};\n else\n Xtmp = zeros(n,1); Ztmp = zeros(n,1);\n Xtmp(ublkinfo{p,1}) = max(0,X2{p});\n Xtmp(ublkinfo{p,2}) = max(0,-X2{p});\n Ztmp(ublkinfo{p,1}) = max(0,Z2{p});\n Ztmp(ublkinfo{p,2}) = max(0,-Z2{p});\n if ~isempty(ublkinfo{p,3})\n numblknew = numblknew + 1;\n Xtmp(ublkinfo{p,3}) = X2{numblknew};\n Ztmp(ublkinfo{p,3}) = Z2{numblknew};\n end\n X{p} = Xtmp; Z{p} = Ztmp;\n end\nend\n%%\n%%-----------------------------------------\n%% recover complex solution\n%%-----------------------------------------\n%%\nif (iscmp)\n for p = 1:numblk\n pblk = blk(p,:);\n n = sum(pblk{2})/2;\n if strcmp(pblk{1},'s');\n X{p} = X{p}(1:n,1:n) + sqrt(-1)*X{p}(n+1:2*n,1:n);\n Z{p} = Z{p}(1:n,1:n) + sqrt(-1)*Z{p}(n+1:2*n,1:n);\n X{p} = 0.5*(X{p}+X{p}');\n Z{p} = 0.5*(Z{p}+Z{p}');\n end\n end\nend\nif (isemptyAtb)\n X = X(1:end-1); Z = Z(1:end-1);\nend\n%%*****************************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/Solver/sqlp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3965936967940687}}
{"text": "function sdn = utc2sdn(utc)\n% UTC2SDN - Convert UTC seconds to matlab date format\n%\n% Use as: sdn = utc2sdn(utc);\n%\n% sdn = Matlab datenumber (se DATENUM and DATESTR)\n% utc = Seconds since 01 Jan 1970 00:00:00\n\n% Brian Schlining\n% 12 Apr 2000\n\n%datenum('01 Jan 1970 00:00:00') = 719529\nsdn = utc/60/60/24 + 719529;", "meta": {"author": "nctoolbox", "repo": "nctoolbox", "sha": "af757acccfcac373e35fde89fc8ed7e64b67de82", "save_path": "github-repos/MATLAB/nctoolbox-nctoolbox", "path": "github-repos/MATLAB/nctoolbox-nctoolbox/nctoolbox-af757acccfcac373e35fde89fc8ed7e64b67de82/cdm/utilities/misc/utc2sdn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.3965934846983578}}
{"text": "function hmm = states_supdate(hmm,hmm_noisy,rho,update)\n% update==1, W; update==2, Omega; update==3, sigma; update==4, alpha\nK = length(hmm_noisy.state);\nSind = hmm.train.Sind==1;\nregressed = sum((hmm.train.Sind==1),1)>0;\n\nfor k = 1:K\n if any(update==1) && isfield(hmm_noisy.state(1),'W') && ~isempty(hmm_noisy.state(1).W.Mu_W)\n hmm.state(k).W.Mu_W = (1-rho) * hmm.state(k).W.Mu_W + ...\n rho * hmm_noisy.state(k).W.Mu_W;\n hmm.state(k).W.iS_W = (1-rho) * hmm.state(k).W.iS_W + ...\n rho * hmm_noisy.state(k).W.iS_W;\n if length(size(hmm.state(k).W.S_W))==2 && ... % full, uniquefull, uniqueAR or 1 dimension \n size(hmm.state(k).W.S_W,1)==size(hmm.state(k).W.S_W,2)\n hmm.state(k).W.S_W = inv(hmm.state(k).W.iS_W);\n else % diag or shareddiag\n for n = 1:size(hmm.state(k).W.S_W,1)\n hmm.state(k).W.S_W(n,Sind(:,n),Sind(:,n)) = ...\n inv(permute(hmm.state(k).W.iS_W(n,Sind(:,n),Sind(:,n)),[2 3 1]));\n end\n end\n elseif any(update==2) && isfield(hmm_noisy.state(1),'Omega')\n hmm.state(k).Omega.Gam_rate = (1-rho) * hmm.state(k).Omega.Gam_rate + ...\n rho * hmm_noisy.state(k).Omega.Gam_rate;\n hmm.state(k).Omega.Gam_shape = (1-rho) * hmm.state(k).Omega.Gam_shape + ...\n rho * hmm_noisy.state(k).Omega.Gam_shape;\n if strcmp(hmm_noisy.train.covtype,'full') || ...\n strcmp(hmm_noisy.train.covtype,'uniquefull') || ...\n strcmp(hmm_noisy.train.covtype,'sharedfull')\n hmm.state(k).Omega.Gam_irate(regressed,regressed) = ...\n inv(hmm.state(k).Omega.Gam_rate(regressed,regressed));\n end\n elseif any(update==3) && isfield(hmm_noisy.state(1),'sigma')\n hmm.state(k).sigma.Gam_rate = (1-rho) * hmm.state(k).sigma.Gam_rate + ...\n rho * hmm_noisy.state(k).sigma.Gam_rate;\n hmm.state(k).sigma.Gam_shape = (1-rho) * hmm.state(k).sigma.Gam_shape + ...\n rho * hmm_noisy.state(k).sigma.Gam_shape;\n elseif any(update==4) && isfield(hmm_noisy.state(1),'alpha')\n hmm.state(k).alpha.Gam_rate = (1-rho) * hmm.state(k).alpha.Gam_rate + ...\n rho * hmm_noisy.state(k).alpha.Gam_rate;\n hmm.state(k).alpha.Gam_shape = (1-rho) * hmm.state(k).alpha.Gam_shape + ...\n rho * hmm_noisy.state(k).alpha.Gam_shape;\n elseif any(update==5) && isfield(hmm_noisy.state(1),'beta')\n hmm.state(k).beta.Gam_rate = (1-rho) * hmm.state(k).beta.Gam_rate + ...\n rho * hmm_noisy.state(k).beta.Gam_rate;\n hmm.state(k).beta.Gam_shape = (1-rho) * hmm.state(k).beta.Gam_shape + ...\n rho * hmm_noisy.state(k).beta.Gam_shape; \n end\nend\n\nif any(update==2) && isfield(hmm_noisy,'Omega')\n hmm.Omega.Gam_rate = (1-rho) * hmm.Omega.Gam_rate + ...\n rho * hmm_noisy.Omega.Gam_rate;\n hmm.Omega.Gam_shape = (1-rho) * hmm.Omega.Gam_shape + ...\n rho * hmm_noisy.Omega.Gam_shape;\n if strcmp(hmm_noisy.train.covtype,'uniquefull') || ...\n strcmp(hmm_noisy.train.covtype,'sharedfull')\n hmm.Omega.Gam_irate(regressed,regressed) = ...\n inv(hmm.Omega.Gam_rate(regressed,regressed));\n end\nend\n\nend", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/stochastic/states_supdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.39655309248075893}}
{"text": "function [c, v, n] = ft_connectivity_psi(input, varargin)\n\n% FT_CONNECTIVITY_PSI computes the phase slope index from a data-matrix\n% containing the cross-spectral density. It implements the method described\n% in: Nolte et al., Robustly estimating the flow direction of information\n% in complex physical systems. Physical Review Letters, 2008; 100; 234101.\n%\n% Use as\n% [c, v, n] = ft_connectivity_psi(input, ...)\n%\n% The input data input should be organized as\n% Repetitions x Channel x Channel (x Frequency) (x Time)\n% or\n% Repetitions x Channelcombination (x Frequency) (x Time)\n%\n% The first dimension should be singleton if the input already contains an\n% average.\n%\n% Additional optional input arguments come as key-value pairs:\n% nbin\t\t\t=\tscalar, half-bandwidth parameter: the number of frequency bins\n%\t\t\t\t\t\t\t\tacross which to integrate\n% hasjack\t\t= 0 or 1, specifying whether the repetitions represent\n% leave-one-out samples (allowing for a variance estimate)\n% feedback\t= 'none', 'text', 'textbar' type of feedback showing progress of\n% computation\n% dimord\t\t= string, specifying how the input matrix should be interpreted\n% powindx =\n% normalize =\n%\n% The output p contains the phase slope index, v is a variance estimate\n% which only can be computed if the data contains leave-one-out samples,\n% and n is the number of repetitions in the input data. If the phase slope\n% index is positive, then the first chan (1st dim) becomes more lagged (or\n% less leading) with higher frequency, indicating that it is causally\n% driven by the second channel (2nd dim)\n%\n% See also FT_CONNECTIVITYANALYSIS\n\n% Copyright (C) 2009-2010 Donders Institute, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% FIXME: interpretation of the slope\n\nhasjack = ft_getopt(varargin, 'hasjack', 0);\nfeedback = ft_getopt(varargin, 'feedback', 'none');\ndimord = ft_getopt(varargin, 'dimord');\npowindx = ft_getopt(varargin, 'powindx');\nnormalize = ft_getopt(varargin, 'normalize', 'no');\nnbin = ft_getopt(varargin, 'nbin');\n\nif isempty(dimord)\n ft_error('input parameters should contain a dimord');\nend\n\nif (length(strfind(dimord, 'chan'))~=2 || contains(dimord, 'pos')>0) && ~isempty(powindx)\n %crossterms are not described with chan_chan_therest, but are linearly indexed\n \n siz = size(input);\n \n outsum = zeros(siz(2:end));\n outssq = zeros(siz(2:end));\n pvec = [2 setdiff(1:numel(siz),2)];\n \n ft_progress('init', feedback, 'computing metric...');\n %first compute coherency and then phaseslopeindex\n for j = 1:siz(1)\n ft_progress(j/siz(1), 'computing metric for replicate %d from %d\\n', j, siz(1));\n c = reshape(input(j,:,:,:,:), siz(2:end));\n p1 = abs(reshape(input(j,powindx(:,1),:,:,:), siz(2:end)));\n p2 = abs(reshape(input(j,powindx(:,2),:,:,:), siz(2:end)));\n \n p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec);\n \n outsum = outsum + p;\n outssq = outssq + p.^2;\n end\n ft_progress('close');\n \nelseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2\n %crossterms are described by chan_chan_therest\n \n siz = size(input);\n \n outsum = zeros(siz(2:end));\n outssq = zeros(siz(2:end));\n pvec = [3 setdiff(1:numel(siz),3)];\n \n ft_progress('init', feedback, 'computing metric...');\n for j = 1:siz(1)\n ft_progress(j/siz(1), 'computing metric for replicate %d from %d\\n', j, siz(1));\n p1 = zeros([siz(2) 1 siz(4:end)]);\n p2 = zeros([1 siz(3) siz(4:end)]);\n for k = 1:siz(2)\n p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:);\n p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:);\n end\n c = reshape(input(j,:,:,:,:,:,:), siz(2:end));\n p1 = p1(:,ones(1,siz(3)),:,:,:,:);\n p2 = p2(ones(1,siz(2)),:,:,:,:,:);\n p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec);\n p(isnan(p)) = 0;\n outsum = outsum + p;\n outssq = outssq + p.^2;\n end\n ft_progress('close');\n \nend\n\nn = siz(1);\nc = outsum./n;\n\nif n>1\n n = shiftdim(sum(~isnan(input),1),1);\n if hasjack\n bias = (n-1).^2;\n else\n bias = 1;\n end\n v = bias.*(outssq - (outsum.^2)./n)./(n - 1);\nelse\n v = [];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [y] = phaseslope(x, n, norm)\n\nm = size(x, 1); %total number of frequency bins\ny = zeros(size(x));\nx(1:end-1,:,:,:,:) = conj(x(1:end-1,:,:,:,:)).*x(2:end,:,:,:,:);\n\nif strcmp(norm, 'yes')\n coh = zeros(size(x));\n coh(1:end-1,:,:,:,:) = (abs(x(1:end-1,:,:,:,:)) .* abs(x(2:end,:,:,:,:))) + 1;\n %FIXME why the +1? get the coherence\n for k = 1:m\n begindx = max(1,k-n);\n endindx = min(m,k+n);\n y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:)./coh(begindx:endindx,:,:,:,:),1));\n end\nelse\n for k = 1:m\n begindx = max(1,k-n);\n endindx = min(m,k+n);\n y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:),1));\n end\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/connectivity/ft_connectivity_psi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3965530870226457}}
{"text": "function [flowx,flowy] = specific_wind(x,y,nel)\n%constant_wind Reference problem 3.3 convective wind \n% [flowx,flowy] = specific_wind(x,y,nel);\n% input\n% x x coordinate vector\n% y y coordinate vector \n% nel number of elements\n% specifies constant wind at angle theta to vertical\n% IFISS function: DJS; 5 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n theta= -pi/6;\n flowx = sin(theta)*ones(nel,1); \n flowy = cos(theta)*ones(nel,1);\n return\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/convection/specific_wind.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.622459324198198, "lm_q1q2_score": 0.3965257578257005}}
{"text": "function [x, cost, info, options] = trustregions(problem, x, options)\n% Riemannian trust-regions solver for optimization on manifolds.\n%\n% function [x, cost, info, options] = trustregions(problem)\n% function [x, cost, info, options] = trustregions(problem, x0)\n% function [x, cost, info, options] = trustregions(problem, x0, options)\n% function [x, cost, info, options] = trustregions(problem, [], options)\n%\n% This is the Riemannian Trust-Region solver (with tCG inner solve), named\n% RTR. This solver will attempt to minimize the cost function described in\n% the problem structure. It requires the availability of the cost function\n% and of its gradient. It will issue calls for the Hessian. If no Hessian\n% nor approximate Hessian is provided, a standard approximation of the\n% Hessian based on the gradient will be computed. If a preconditioner for\n% the Hessian is provided, it will be used.\n%\n% For a description of the algorithm and theorems offering convergence\n% guarantees, see the references below. Documentation for this solver is\n% available online at:\n%\n% http://www.manopt.org/solver_documentation_trustregions.html\n%\n%\n% The initial iterate is x0 if it is provided. Otherwise, a random point on\n% the manifold is picked. To specify options whilst not specifying an\n% initial iterate, give x0 as [] (the empty matrix).\n%\n% The two outputs 'x' and 'cost' are the last reached point on the manifold\n% and its cost. Notice that x is not necessarily the best reached point,\n% because this solver is not forced to be a descent method. In particular,\n% very close to convergence, it is sometimes preferable to accept very\n% slight increases in the cost value (on the order of the machine epsilon)\n% in the process of reaching fine convergence. In practice, this is not a\n% limiting factor, as normally one does not need fine enough convergence\n% that this becomes an issue.\n% \n% The output 'info' is a struct-array which contains information about the\n% iterations:\n% iter (integer)\n% The (outer) iteration number, or number of steps considered\n% (whether accepted or rejected). The initial guess is 0.\n%\tcost (double)\n% The corresponding cost value.\n%\tgradnorm (double)\n% The (Riemannian) norm of the gradient.\n%\tnuminner (integer)\n% The number of inner iterations executed to compute this iterate.\n% Inner iterations are truncated-CG steps. Each one requires a\n% Hessian (or approximate Hessian) evaluation.\n%\ttime (double)\n% The total elapsed time in seconds to reach the corresponding cost.\n%\trho (double)\n% The performance ratio for the iterate.\n%\trhonum, rhoden (double)\n% Regularized numerator and denominator of the performance ratio:\n% rho = rhonum/rhoden. See options.rho_regularization.\n%\taccepted (boolean)\n% Whether the proposed iterate was accepted or not.\n%\tstepsize (double)\n% The (Riemannian) norm of the vector returned by the inner solver\n% tCG and which is retracted to obtain the proposed next iterate. If\n% accepted = true for the corresponding iterate, this is the size of\n% the step from the previous to the new iterate. If accepted is\n% false, the step was not executed and this is the size of the\n% rejected step.\n%\tDelta (double)\n% The trust-region radius at the outer iteration.\n%\tcauchy (boolean)\n% Whether the Cauchy point was used or not (if useRand is true).\n% And possibly additional information logged by options.statsfun.\n% For example, type [info.gradnorm] to obtain a vector of the successive\n% gradient norms reached at each (outer) iteration.\n%\n% The options structure is used to overwrite the default values. All\n% options have a default value and are hence optional. To force an option\n% value, pass an options structure with a field options.optionname, where\n% optionname is one of the following and the default value is indicated\n% between parentheses:\n%\n% tolgradnorm (1e-6)\n% The algorithm terminates if the norm of the gradient drops below\n% this. For well-scaled problems, a rule of thumb is that you can\n% expect to reduce the gradient norm by 8 orders of magnitude\n% (sqrt(eps)) compared to the gradient norm at a \"typical\" point (a\n% rough initial iterate for example). Further decrease is sometimes\n% possible, but inexact floating point arithmetic will eventually\n% limit the final accuracy. If tolgradnorm is set too low, the\n% algorithm may end up iterating forever (or at least until another\n% stopping criterion triggers).\n% maxiter (1000)\n% The algorithm terminates if maxiter (outer) iterations were executed.\n% maxtime (Inf)\n% The algorithm terminates if maxtime seconds elapsed.\n%\tminiter (3)\n% Minimum number of outer iterations (used only if useRand is true).\n%\tmininner (1)\n% Minimum number of inner iterations (for tCG).\n%\tmaxinner (problem.M.dim() : the manifold's dimension)\n% Maximum number of inner iterations (for tCG).\n%\tDelta_bar (problem.M.typicaldist() or sqrt(problem.M.dim()))\n% Maximum trust-region radius. If you specify this parameter but not\n% Delta0, then Delta0 will be set to 1/8 times this parameter.\n% Delta0 (Delta_bar/8)\n% Initial trust-region radius. If you observe a long plateau at the\n% beginning of the convergence plot (gradient norm VS iteration), it\n% may pay off to try to tune this parameter to shorten the plateau.\n% You should not set this parameter without setting Delta_bar.\n%\tuseRand (false)\n% Set to true if the trust-region solve is to be initiated with a\n% random tangent vector. If set to true, no preconditioner will be\n% used. This option is set to true in some scenarios to escape saddle\n% points, but is otherwise seldom activated.\n%\tkappa (0.1)\n% Inner kappa convergence tolerance.\n%\ttheta (1.0)\n% Inner theta convergence tolerance.\n%\trho_prime (0.1)\n% Accept/reject ratio : if rho is at least rho_prime, the outer\n% iteration is accepted. Otherwise, it is rejected. In case it is\n% rejected, the trust-region radius will have been decreased.\n% To ensure this, rho_prime must be strictly smaller than 1/4.\n% rho_regularization (1e3)\n% Close to convergence, evaluating the performance ratio rho is\n% numerically challenging. Meanwhile, close to convergence, the\n% quadratic model should be a good fit and the steps should be\n% accepted. Regularization lets rho go to 1 as the model decrease and\n% the actual decrease go to zero. Set this option to zero to disable\n% regularization (not recommended). See in-code for the specifics.\n% statsfun (none)\n% Function handle to a function that will be called after each\n% iteration to provide the opportunity to log additional statistics.\n% They will be returned in the info struct. See the generic Manopt\n% documentation about solvers for further information. statsfun is\n% called with the point x that was reached last, after the\n% accept/reject decision. See comment below.\n% stopfun (none)\n% Function handle to a function that will be called at each iteration\n% to provide the opportunity to specify additional stopping criteria.\n% See the generic Manopt documentation about solvers for further\n% information.\n% verbosity (2)\n% Integer number used to tune the amount of output the algorithm\n% generates during execution (mostly as text in the command window).\n% The higher, the more output. 0 means silent. 3 and above includes a\n% display of the options structure at the beginning of the execution.\n% debug (false)\n% Set to true to allow the algorithm to perform additional\n% computations for debugging purposes. If a debugging test fails, you\n% will be informed of it, usually via the command window. Be aware\n% that these additional computations appear in the algorithm timings\n% too.\n% storedepth (20)\n% Maximum number of different points x of the manifold for which a\n% store structure will be kept in memory in the storedb. If the\n% caching features of Manopt are not used, this is irrelevant. If\n% memory usage is an issue, you may try to lower this number.\n% Profiling may then help to investigate if a performance hit was\n% incured as a result.\n%\n% Notice that statsfun is called with the point x that was reached last,\n% after the accept/reject decision. Hence: if the step was accepted, we get\n% that new x, with a store which only saw the call for the cost and for the\n% gradient. If the step was rejected, we get the same x as previously, with\n% the store structure containing everything that was computed at that point\n% (possibly including previous rejects at that same point). Hence, statsfun\n% should not be used in conjunction with the store to count operations for\n% example. Instead, you could use a global variable and increment that\n% variable directly from the cost related functions. It is however possible\n% to use statsfun with the store to compute, for example, alternate merit\n% functions on the point x.\n%\n% See also: steepestdescent conjugategradient manopt/examples\n\n% This file is part of Manopt: www.manopt.org.\n% This code is an adaptation to Manopt of the original GenRTR code:\n% RTR - Riemannian Trust-Region\n% (c) 2004-2007, P.-A. Absil, C. G. Baker, K. A. Gallivan\n% Florida State University\n% School of Computational Science\n% (http://www.math.fsu.edu/~cbaker/GenRTR/?page=download)\n% See accompanying license file.\n% The adaptation was executed by Nicolas Boumal.\n%\n% Change log: \n%\n% NB April 3, 2013:\n% tCG now returns the Hessian along the returned direction eta, so\n% that we do not compute that Hessian redundantly: some savings at\n% each iteration. Similarly, if the useRand flag is on, we spare an\n% extra Hessian computation at each outer iteration too, owing to\n% some modifications in the Cauchy point section of the code specific\n% to useRand = true.\n%\n% NB Aug. 22, 2013:\n% This function is now Octave compatible. The transition called for\n% two changes which would otherwise not be advisable. (1) tic/toc is\n% now used as is, as opposed to the safer way:\n% t = tic(); elapsed = toc(t);\n% And (2), the (formerly inner) function savestats was moved outside\n% the main function to not be nested anymore. This is arguably less\n% elegant, but Octave does not (and likely will not) support nested\n% functions.\n%\n% NB Dec. 2, 2013:\n% The in-code documentation was largely revised and expanded.\n%\n% NB Dec. 2, 2013:\n% The former heuristic which triggered when rhonum was very small and\n% forced rho = 1 has been replaced by a smoother heuristic which\n% consists in regularizing rhonum and rhoden before computing their\n% ratio. It is tunable via options.rho_regularization. Furthermore,\n% the solver now detects if tCG did not obtain a model decrease\n% (which is theoretically impossible but may happen because of\n% numerical errors and/or because of a nonlinear/nonsymmetric Hessian\n% operator, which is the case for finite difference approximations).\n% When such an anomaly is detected, the step is rejected and the\n% trust region radius is decreased.\n%\n% NB Dec. 3, 2013:\n% The stepsize is now registered at each iteration, at a small\n% additional cost. The defaults for Delta_bar and Delta0 are better\n% defined. Setting Delta_bar in the options will automatically set\n% Delta0 accordingly. In Manopt 1.0.4, the defaults for these options\n% were not treated appropriately because of an incorrect use of the\n% isfield() built-in function.\n\n\n% Verify that the problem description is sufficient for the solver.\nif ~canGetCost(problem)\n warning('manopt:getCost', ...\n 'No cost provided. The algorithm will likely abort.'); \nend\nif ~canGetGradient(problem)\n warning('manopt:getGradient', ...\n 'No gradient provided. The algorithm will likely abort.'); \nend\nif ~canGetHessian(problem)\n warning('manopt:getHessian:approx', ...\n 'No Hessian provided. Using an approximation instead.');\nend\n\n% Define some strings for display\ntcg_stop_reason = {'negative curvature',...\n 'exceeded trust region',...\n 'reached target residual-kappa',...\n 'reached target residual-theta',...\n 'dimension exceeded',...\n 'model increased'};\n\n% Set local defaults here\nlocaldefaults.verbosity = 2;\nlocaldefaults.maxtime = inf;\nlocaldefaults.miniter = 3;\nlocaldefaults.maxiter = 1000;\nlocaldefaults.mininner = 1;\nlocaldefaults.maxinner = problem.M.dim();\nlocaldefaults.tolgradnorm = 1e-6;\nlocaldefaults.kappa = 0.1;\nlocaldefaults.theta = 1.0;\nlocaldefaults.rho_prime = 0.1;\nlocaldefaults.useRand = false;\nlocaldefaults.rho_regularization = 1e3;\n\n% Merge global and local defaults, then merge w/ user options, if any.\nlocaldefaults = mergeOptions(getGlobalDefaults(), localdefaults);\nif ~exist('options', 'var') || isempty(options)\n options = struct();\nend\noptions = mergeOptions(localdefaults, options);\n\n% Set default Delta_bar and Delta0 separately to deal with additional\n% logic: if Delta_bar is provided but not Delta0, let Delta0 automatically\n% be some fraction of the provided Delta_bar.\nif ~isfield(options, 'Delta_bar')\n if isfield(problem.M, 'typicaldist')\n options.Delta_bar = problem.M.typicaldist();\n else\n options.Delta_bar = sqrt(problem.M.dim());\n end \nend\nif ~isfield(options,'Delta0')\n options.Delta0 = options.Delta_bar / 8;\nend\n\n% Check some option values\nassert(options.rho_prime < 1/4, ...\n 'options.rho_prime must be strictly smaller than 1/4.');\nassert(options.Delta_bar > 0, ...\n 'options.Delta_bar must be positive.');\nassert(options.Delta0 > 0 && options.Delta0 < options.Delta_bar, ...\n 'options.Delta0 must be positive and smaller than Delta_bar.');\n\n% It is sometimes useful to check what the actual option values are.\nif options.verbosity >= 3\n disp(options);\nend\n\n% Create a store database\nstoredb = struct();\n\ntic();\n\n% If no initial point x is given by the user, generate one at random.\nif ~exist('x', 'var') || isempty(x)\n x = problem.M.rand();\nend\n\n%% Initializations\n\n% k counts the outer (TR) iterations. The semantic is that k counts the\n% number of iterations fully executed so far.\nk = 0;\n\n% initialize solution and companion measures: f(x), fgrad(x)\n[fx fgradx storedb] = getCostGrad(problem, x, storedb);\nnorm_grad = problem.M.norm(x, fgradx);\n\n% initialize trust-region radius\nDelta = options.Delta0;\n\n% Save stats in a struct array info, and preallocate\n% (see http://people.csail.mit.edu/jskelly/blog/?x=entry:entry091030-033941)\nif ~exist('used_cauchy', 'var')\n used_cauchy = [];\nend\nstats = savestats(problem, x, storedb, options, k, fx, norm_grad, Delta);\ninfo(1) = stats;\ninfo(min(10000, options.maxiter+1)).iter = [];\n\n% ** Display:\nif options.verbosity == 2\n fprintf(['%3s %3s %5s %5s ',...\n 'f: %e |grad|: %e\\n'],...\n ' ',' ',' ',' ', fx, norm_grad);\nelseif options.verbosity > 2\n fprintf('************************************************************************\\n');\n fprintf('%3s %3s k: %5s num_inner: %5s %s\\n',...\n '','','______','______','');\n fprintf(' f(x) : %e |grad| : %e\\n', fx, norm_grad);\n fprintf(' Delta : %f\\n', Delta);\nend\n\n\n% **********************\n% ** Start of TR loop **\n% **********************\nwhile true\n \n\t% Start clock for this outer iteration\n tic();\n\n % Run standard stopping criterion checks\n [stop reason] = stoppingcriterion(problem, x, options, info, k+1);\n \n % If the stopping criterion that triggered is the tolerance on the\n % gradient norm but we are using randomization, make sure we make at\n % least miniter iterations to give randomization a chance at escaping\n % saddle points.\n if stop == 2 && options.useRand && k < options.miniter\n stop = 0;\n end\n \n if stop\n if options.verbosity >= 1\n fprintf([reason '\\n']);\n end\n break;\n end\n\n if options.verbosity > 2 || options.debug > 0\n fprintf('************************************************************************\\n');\n end\n\n % *************************\n % ** Begin TR Subproblem **\n % *************************\n \n % Determine eta0\n if ~options.useRand\n % Pick the zero vector\n eta = problem.M.zerovec(x);\n else\n % Random vector in T_x M (this has to be very small)\n eta = problem.M.lincomb(x, 1e-6, problem.M.randvec(x));\n % Must be inside trust-region\n while problem.M.norm(x, eta) > Delta\n eta = problem.M.lincomb(x, sqrt(sqrt(eps)), eta);\n end\n end\n\n % solve TR subproblem\n [eta Heta numit stop_inner storedb] = ...\n tCG(problem, x, fgradx, eta, Delta, options, storedb);\n srstr = tcg_stop_reason{stop_inner};\n \n % This is only computed for logging purposes, because it may be useful\n % for some user-defined stopping criteria. If this is not cheap for\n % specific application (compared to evaluating the cost), we should\n % reconsider this.\n norm_eta = problem.M.norm(x, eta);\n \n if options.debug > 0\n testangle = problem.M.inner(x, eta, fgradx) / (norm_eta*norm_grad);\n end\n\n % If using randomized approach, compare result with the Cauchy point.\n % Convergence proofs assume that we achieve at least the reduction of\n % the Cauchy point. After this if-block, either all eta-related\n % quantities have been changed consistently, or none of them have\n % changed.\n if options.useRand\n used_cauchy = false;\n % Check the curvature,\n [Hg storedb] = getHessian(problem, x, fgradx, storedb);\n g_Hg = problem.M.inner(x, fgradx, Hg);\n if g_Hg <= 0\n tau_c = 1;\n else\n tau_c = min( norm_grad^3/(Delta*g_Hg) , 1);\n end\n % and generate the Cauchy point.\n eta_c = problem.M.lincomb(x, -tau_c * Delta / norm_grad, fgradx);\n Heta_c = problem.M.lincomb(x, -tau_c * Delta / norm_grad, Hg);\n\n % Now that we have computed the Cauchy point in addition to the\n % returned eta, we might as well keep the best of them.\n mdle = fx + problem.M.inner(x, fgradx, eta) ...\n + .5*problem.M.inner(x, Heta, eta);\n mdlec = fx + problem.M.inner(x, fgradx, eta_c) ...\n + .5*problem.M.inner(x, Heta_c, eta_c);\n if mdle > mdlec\n eta = eta_c;\n Heta = Heta_c; % added April 11, 2012\n used_cauchy = true;\n end\n end \n\n\t% Compute the retraction of the proposal\n\tx_prop = problem.M.retr(x, eta);\n\n\t% Compute the function value of the proposal\n\t[fx_prop storedb] = getCost(problem, x_prop, storedb);\n\n\t% Will we accept the proposed solution or not?\n % Check the performance of the quadratic model against the actual cost.\n rhonum = fx - fx_prop;\n rhoden = -problem.M.inner(x, fgradx, eta) ...\n -.5*problem.M.inner(x, eta, Heta);\n \n % Heuristic -- added Dec. 2, 2013 (NB) to replace the former heuristic.\n % This heuristic is documented in the book by Conn Gould and Toint on\n % trust-region methods, section 17.4.2.\n % rhonum measures the difference between two numbers. Close to\n % convergence, these two numbers are very close to each other, so\n % that computing their difference is numerically challenging: there may\n % be a significant loss in accuracy. Since the acceptance or rejection\n % of the step is conditioned on the ratio between rhonum and rhoden,\n % large errors in rhonum result in a large error in rho, hence in\n % erratic acceptance / rejection. Meanwhile, close to convergence,\n % steps are usually trustworthy and we should transition to a Newton-\n % like method, with rho=1 consistently. The heuristic thus shifts both\n % rhonum and rhoden by a small amount such that far from convergence,\n % the shift is irrelevant and close to convergence, the ratio rho goes\n % to 1, effectively promoting acceptance of the step.\n % The rationale is that close to convergence, both rhonum and rhoden\n % are quadratic in the distance between x and x_prop. Thus, when this\n % distance is on the order of sqrt(eps), the value of rhonum and rhoden\n % is on the order of eps, which is indistinguishable from the numerical\n % error, resulting in badly estimated rho's.\n % For abs(fx) < 1, this heuristic is invariant under offsets of f but\n % not under scaling of f. For abs(fx) > 1, the opposite holds. This\n % should not alarm us, as this heuristic only triggers at the very last\n % iterations if very fine convergence is demanded.\n rho_reg = max(1, abs(fx)) * eps * options.rho_regularization;\n rhonum = rhonum + rho_reg;\n rhoden = rhoden + rho_reg;\n \n if options.debug > 0\n fprintf('DBG: rhonum : %e\\n', rhonum);\n fprintf('DBG: rhoden : %e\\n', rhoden);\n end\n \n % This is always true if a linear, symmetric operator is used for the\n % Hessian (approximation) and if we had infinite numerical precision.\n % In practice, nonlinear approximations of the Hessian such as the\n % built-in finite difference approximation and finite numerical\n % accuracy can cause the model to increase. In such scenarios, we\n % decide to force a rejection of the step and a reduction of the\n % trust-region radius. We test the sign of the regularized rhoden since\n % the regularization is supposed to capture the accuracy to which\n % rhoden is computed: if rhoden were negative before regularization but\n % not after, that should not be (and is not) detected as a failure.\n model_decreased = (rhoden >= 0);\n \n if ~model_decreased \n srstr = [srstr ', model did not decrease']; %#ok\n end\n \n rho = rhonum / rhoden;\n \n if options.debug > 0\n m = @(x, eta) ...\n getCost(problem, x, storedb) + ...\n getDirectionalDerivative(problem, x, eta, storedb) + ...\n .5*problem.M.inner(x, getHessian(problem, x, eta, storedb), eta);\n zerovec = problem.M.zerovec(x);\n actrho = (fx - fx_prop) / (m(x, zerovec) - m(x, eta));\n fprintf('DBG: new f(x) : %e\\n', fx_prop);\n fprintf('DBG: actual rho : %e\\n', actrho);\n fprintf('DBG: used rho : %e\\n', rho);\n end\n\n % Choose the new TR radius based on the model performance\n trstr = ' ';\n % If the actual decrease is smaller than 1/4 of the predicted decrease,\n % then reduce the TR radius.\n if rho < 1/4 || ~model_decreased\n trstr = 'TR-';\n Delta = Delta/4;\n % If the actual decrease is at least 3/4 of the precicted decrease and\n % the tCG (inner solve) hit the TR boundary, increase the TR radius.\n elseif rho > 3/4 && (stop_inner == 1 || stop_inner == 2)\n trstr = 'TR+';\n Delta = min(2*Delta, options.Delta_bar);\n end\n % Otherwise, keep the TR radius constant.\n\n % Choose to accept or reject the proposed step based on the model\n % performance.\n if model_decreased && rho > options.rho_prime\n accept = true;\n accstr = 'acc';\n x = x_prop;\n fx = fx_prop;\n [fgradx storedb] = getGradient(problem, x, storedb);\n norm_grad = problem.M.norm(x, fgradx);\n else\n accept = false;\n accstr = 'REJ';\n end\n \n \n % Make sure we don't use too much memory for the store database\n storedb = purgeStoredb(storedb, options.storedepth);\n \n % k is the number of iterations we have accomplished.\n k = k + 1;\n\n % Log statistics for freshly executed iteration.\n % Everything after this in the loop is not accounted for in the timing.\n stats = savestats(problem, x, storedb, options, k, fx, norm_grad, ...\n Delta, info, rho, rhonum, rhoden, accept, numit, ...\n norm_eta, used_cauchy);\n info(k+1) = stats; %#ok\n\n \n % ** Display:\n if options.verbosity == 2,\n fprintf(['%3s %3s k: %5d num_inner: %5d ', ...\n 'f: %e |grad|: %e %s\\n'], ...\n accstr,trstr,k,numit,fx,norm_grad,srstr);\n elseif options.verbosity > 2,\n if options.useRand && used_cauchy,\n fprintf('USED CAUCHY POINT\\n');\n end\n\t\tfprintf('%3s %3s k: %5d num_inner: %5d %s\\n', ...\n\t\t\t\taccstr, trstr, k, numit, srstr);\n\t\tfprintf(' f(x) : %e |grad| : %e\\n',fx,norm_grad);\n\t\tif options.debug > 0\n\t\t\tfprintf(' Delta : %f |eta| : %e\\n',Delta,norm_eta);\n\t\tend\n\t\tfprintf(' rho : %e\\n',rho);\n end\n if options.debug > 0,\n fprintf('DBG: cos ang(eta,gradf): %d\\n',testangle);\n if rho == 0\n fprintf('DBG: rho = 0, this will likely hinder further convergence.\\n');\n end\n end\n\nend % of TR loop (counter: k)\n\n% Restrict info struct-array to useful part\ninfo = info(1:k+1);\n\n\nif (options.verbosity > 2) || (options.debug > 0),\n fprintf('************************************************************************\\n');\nend\nif (options.verbosity > 0) || (options.debug > 0)\n fprintf('Total time is %f [s] (excludes statsfun)\\n', info(end).time);\nend\n\n% Return the best cost reached\ncost = fx;\n\nend\n\n\n\n \n\n% Routine in charge of collecting the current iteration stats\nfunction stats = savestats(problem, x, storedb, options, k, fx, ...\n norm_grad, Delta, info, rho, rhonum, ...\n rhoden, accept, numit, norm_eta, used_cauchy)\n stats.iter = k;\n stats.cost = fx;\n stats.gradnorm = norm_grad;\n stats.Delta = Delta;\n if k == 0\n stats.time = toc();\n stats.rho = inf;\n stats.rhonum = NaN;\n stats.rhoden = NaN;\n stats.accepted = true;\n stats.numinner = NaN;\n stats.stepsize = NaN;\n if options.useRand\n stats.cauchy = false;\n end\n else\n stats.time = info(k).time + toc();\n stats.rho = rho;\n stats.rhonum = rhonum;\n stats.rhoden = rhoden;\n stats.accepted = accept;\n stats.numinner = numit;\n stats.stepsize = norm_eta;\n if options.useRand,\n stats.cauchy = used_cauchy;\n end\n end\n \n % See comment about statsfun above: the x and store passed to statsfun\n % are that of the most recently accepted point after the iteration\n % fully executed.\n stats = applyStatsfun(problem, x, storedb, options, stats);\n \nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/solvers/trustregions/trustregions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.39652575336415563}}
{"text": "function [ cluass,cluNRG ] = bz_GradDescCluster( simMat, varargin )\n%[cluass] = bz_GradDescCluster(simMat) clusters recording sites given a pairwise \n%similarity matrix using gradient descent to find minimize within-cluster \n%interaction energy. (i.e. maximize within-cluster coherence, see Berenyi \n%et al 2014 for details). \n% \n%INPUT\n% simMat undirected similarity matrix (coherence, correlation, or other)\n%\n% (optional parameters)\n% 'numsteps' number of steps (default: 5e5)\n% 'numinit' number of initial clusters, should be larger than the \n% number of clusters you expect (default: 20)\n% 'stopthresh' stability threshold to stop descending. probability of\n% selected site changing cluster identity, P(switch)\n% (default: 0.001)\n% 'stopwin' window of time for which the P(switch) must stay below\n% stopthresh (default: 10000 steps) \n% 'showplot' true or false, to show the update plot as it goes\n% 'brainmap' cell array with two cells: {1} = linear indices, {2} = size map; 2 dim vector x and y dimensions of map\n\n%OUTPUT\n% cluass cluster assignments for each \n% cluNRG negative energy (i.e. mean within-cluster coherence) for each cluster\n%\n%From Berenyi et al. (2014). Large-scale, high-density (up to 512 \n% channels) recording of local circuits in behaving animals. Journal of \n% Neurophysiology, 111(5), 1132?1149. http://doi.org/10.1152/jn.00785.2013\n%\n%Code implementation by DLevenstein 2016. Updates DL and RS May 2017.\n%\n% TO DO\n% - make brainmap general to any 2D ephys/imaging data \n% - develop method for stopping num iterations\n% - add consensus clustering option? \n\n%% Parse the input parameters\nparms = inputParser;\naddParameter(parms,'numsteps',500000,@isnumeric);\naddParameter(parms,'numinit',20,@isnumeric);\naddParameter(parms,'showplot',true,@islogical);\naddParameter(parms,'brainmap',{},@iscell); \naddParameter(parms,'stopthresh',0.001,@(x) x>0 && x<=1)\naddParameter(parms,'stopwin',10000,@isnumeric)\n\nparse(parms,varargin{:})\nnumsteps = parms.Results.numsteps;\nnuminit = parms.Results.numinit;\nSHOWPLOT = parms.Results.showplot;\nLinearInds = parms.Results.brainmap{1};\nSizeVid = parms.Results.brainmap{2};\nstopthresh = parms.Results.stopthresh;\nstopwin = parms.Results.stopwin;\n\n%% Initialize and Run\nnumsites = size(simMat,1);\nrng('shuffle') %Shuffle the random number generator seed... just in case\ncluass = randi(numinit,numsites,1); %Start from random initial assignments\n\nif SHOWPLOT; figure; switchtracker = zeros(numsteps,1); end \nfor ss = 1:numsteps\n %The time ticker...\n if mod(ss,1000)==1\n display(['Step: ',num2str(ss),' of ',num2str(numsteps)])\n [~,clusort] = sort(cluass);\n \n % Visuals\n if SHOWPLOT\n % plot changing clusters over time\n subplot(2,2,1) \n imagesc(simMat(clusort,clusort)) \n %plot switching behavior\n subplot(2,2,2)\n plot(log10(smooth(switchtracker(1:ss),1000,'moving'))) \n hold on\n plot(get(gca,'xlim'),log10(stopthresh).*[1 1],'r--')\n xlabel('Step #');ylabel('P(switch)')\n ylim([log10(stopthresh)-1 0])\n LogScale('y',10)\n hold off\n % plot map \n if ~isempty(LinearInds) \n map = ExpandVid(cluass, LinearInds, SizeVid);\n subplot(2,2,3)\n imagesc(map)\n end;\n %plot number of clusters\n subplot(2,2,4)\n plot(ss,length(unique(cluass)),'ko') %number clusters\n hold on\n xlabel('Step #');ylabel('# Clusters')\n drawnow\n end;\n end;\n \n % Fx meat\n [cluass,switchtracker(ss)] = DescOneStep(cluass,simMat);\n \n %Decide to exit the loop - if you've been consistent for a certain window\n if mean(switchtracker(max(ss-stopwin,1):ss)) <= stopthresh\n disp('Clustering has descended to the bottom of the (local) pit!')\n break\n end\nend\n\n%Calculate -Energy (mean similarity) for each final cluster\nfinalclus = unique(cluass);\nnumfinalclus = length(finalclus);\nfor ff = 1:numfinalclus\n %N = sum(cluass == finalclus(ff)); \n clusmat = simMat(cluass == finalclus(ff),cluass == finalclus(ff));\n cluspairs = triu(clusmat,1);\n E(ff) = mean(cluspairs(:));\nend\ncluNRG = [finalclus,E'];\n\n\n\n%% FUNCTION: OneStep\n function [newcluass,diditswitch] = DescOneStep(oldcluass,simMat)\n clus = unique(oldcluass);\n numclus = length(clus);\n\n %Pick a random site and calculate the energy for it's current cluster\n sitepick = randi(length(oldcluass),1);\n clu_A = oldcluass(sitepick); %Cluster the current site is in \n othersites = setdiff(1:length(oldcluass),sitepick);\n N_A = sum(oldcluass == clu_A)-1; %ALl OTHER elements of current cluster\n E_A = -(1./N_A).*sum(simMat(sitepick,oldcluass(othersites)==clu_A));\n \n %If only one site in cluster, energy is 0\n if N_A == 0\n E_A = 0;\n end\n \n %Calculate energy gap for switching site to other clusters\n energygap = zeros(size(clus));\n for cc = 1:numclus\n clu_B = clus(cc);\n if clu_B==clu_A\n continue\n end\n N_B = sum(oldcluass == clu_B); \n E_B = -(1./N_B).*(sum(simMat(sitepick,oldcluass==clu_B)));\n energygap(cc) = E_A - E_B;\n end\n\n %Switch site to cluster with largest energy gap\n newcluass = oldcluass;\n newcluass(sitepick) = clus(energygap==max(energygap));\n \n %Keep Track of switching - 1 if the channel stays in its cluster\n diditswitch = clus(energygap==max(energygap))~=clu_A;\n end\nend\n\n%% FUNCTION: ExpandVid\n\nfunction map = ExpandVid(cluass, LinearInds, SizeVid)\n\n % Intialize\n map = single(nan(SizeVid(1)*SizeVid(2),1));\n\n % Put tmpR values int initialized 2D matrix\n map(LinearInds) = cluass;\n\n % Reshape into video\n map = reshape(map,SizeVid(1),SizeVid(2));\n\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/analysis/lfp/bz_GradDescCluster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3963560269375907}}
{"text": "%IMATCH Template matching\n%\n% XM = IMATCH(IM1, IM2, U, V, H, S) is the position of the matching subimage of\n% IM1 (template) within the image IM2. The template in IM1 is centred at (U,V)\n% and its half-width is H. \n%\n% The template is searched for within IM2 inside a rectangular region, centred \n% at (U,V) and whose size is a function of S. If S is a scalar the search \n% region is [-S, S, -S, S] relative to (U,V). More generally S is a 4-vector \n% S=[umin, umax, vmin, vmax] relative to (U,V).\n%\n% The return value is XM=[DU,DV,CC] where (DU,DV) are the u- and v-offsets \n% relative to (U,V) and CC is the similarity score for the best match in the\n% search region.\n%\n% [XM,SCORE] = IMATCH(IM1, IM2, U, V, H, S) as above but also returns a matrix\n% of matching score values for each template position tested. The rows \n% correspond to horizontal positions of the template, and columns the vertical\n% position. The centre element corresponds to (U,V).\n%\n% Example::\n% Consider a sequence of images im(:,:,N) and we find corner points in the\n% k'th image\n% corners = icorner(im(:,:,k), 'nfeat', 20);\n% Now, for each corner we look for the 11x11 patch of surrounding pixels\n% in the next image, by searching within a 21x21 region\n% for corner=corners\n% xm = imatch(im(:,:,k), im(:,:,k+1), 5, 10);\n% if xm(3) > 0.8\n% fprintf('feature (%f,%f) moved by (%f,%f) pixels)\\n', ...\n% corner.u, corner.v, xm(1), xm(2) );\n% end\n% end\n%\n% Notes::\n% - Useful for tracking a template in an image sequence where IM1 and IM2\n% are consecutive images in a template and (U,V) is the coordinate of\n% a corner point in IM1.\n% - Is a MEX file.\n% - IM1 and IM2 must be the same size.\n% - ZNCC (zero-mean normalized cross correlation) matching is used as the \n% similarity measure. A perfect match score is 1.0 but anything above 0.8\n% is typically considered to be a good match.\n%\n% See also ISIMILARITY.\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\nif ~exist('imatch', 'file')\n error('you need to build the MEX version of imatch, see vision/mex/README');\nend\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/imatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3963142417246546}}
{"text": "function [ vX ] = EstimateSignalSamples( vX, vH, vY, convShape, paramLambda, hSumLogProb )\n% ----------------------------------------------------------------------------------------------- %\n% [ mK ] = CreateConvMtx1D( vK, numElements, convShape )\n% Generates a Convolution Matrix for 1D Kernel (The Vector vK) with\n% support for different convolution shapes (Full / Same / Valid). The\n% matrix is build such that for a signal 'vS' with 'numElements = size(vS\n% ,1)' the following are equiavlent: 'mK * vS' and conv(vS, vK,\n% convShapeString);\n% Input:\n% - vK - Input 1D Convolution Kernel.\n% Structure: Vector.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - numElements - Number of Elements.\n% Number of elements of the vector to be\n% convolved with the matrix. Basically set the\n% number of columns of the Convolution Matrix.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ...}.\n% - convShape - Convolution Shape.\n% The shape of the convolution which the output\n% convolution matrix should represent. The\n% options should match MATLAB's conv2() function\n% - Full / Same / Valid.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3}.\n% Output:\n% - mK - Convolution Matrix.\n% The output convolution matrix. The product of\n% 'mK' and a vector 'vS' ('mK * vS') is the\n% convolution between 'vK' and 'vS' with the\n% corresponding convolution shape.\n% Structure: Matrix (Sparse).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References:\n% 1. MATLAB's 'convmtx()' - https://www.mathworks.com/help/signal/ref/convmtx.html.\n% Remarks:\n% 1. The output matrix is sparse data type in order to make the\n% multiplication by vectors to more efficient.\n% 2. In caes the same convolution is applied on many vectors, stacking\n% them into a matrix (Each signal as a vector) and applying\n% convolution on each column by matrix multiplication might be more\n% efficient than applying classic convolution per column.\n% TODO:\n% 1. \n% Release Notes:\n% - 1.0.000 20/01/2019 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nCONVOLUTION_SHAPE_FULL = 1;\nCONVOLUTION_SHAPE_SAME = 2;\nCONVOLUTION_SHAPE_VALID = 3;\n\nswitch(convShape)\n case(CONVOLUTION_SHAPE_FULL)\n convShapeString = 'full';\n case(CONVOLUTION_SHAPE_SAME)\n convShapeString = 'same';\n case(CONVOLUTION_SHAPE_VALID)\n convShapeString = 'valid';\nend\n\nvXX = vX;\n\nhObjFun = @(vX) 0.5 * sum((conv(vX, vH, convShapeString) - vY) .^ 2) - (paramLambda * hSumLogProb(vX));\n\nvX = fminunc(hObjFun, vX);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q64035/EstimateSignalSamples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3963142287263329}}
{"text": "function [dStates, contactForces] = dynamics_singleStanceTwo(States, Actuators, Parameters)\n% function [dStates, Actuators] = dynamics_singleStanceTwo(States, Actuators, Parameters)\n%\n% Computer Generated File -- DO NOT EDIT \n%\n% This function was created by the function Write_ContinuousDynamics()\n% 10-Dec-2013 19:40:47\n%\n% Dymanics Model: retractable double pendulum biped\n% Motion Phase: Single Stance Two\n%\n% Matthew Kelly \n% Cornell University \n% \n\nx = States(1,:); % (m) Foot One horizontal position\ny = States(2,:); % (m) Foot One vertical position\nth1 = States(3,:); % (rad) Leg One absolute angle\nth2 = States(4,:); % (rad) Leg Two absolute angle\nL1 = States(5,:); % (m) Leg One length\nL2 = States(6,:); % (m) Leg Two length\ndx = States(7,:); % (m/s) Foot One horizontal velocity\ndy = States(8,:); % (m/s) Foot One vertical velocity\ndth1 = States(9,:); % (rad/s) Leg One absolute angular rate\ndth2 = States(10,:); % (rad/s) Leg Two absolute angular rate\ndL1 = States(11,:); % (m/s) Leg One extension rate\ndL2 = States(12,:); % (m/s) Leg Two extensioin rate\n\nF1 = Actuators(1,:); % (N) Compresive axial force in Leg One\nF2 = Actuators(2,:); % (N) Compresive axial force in Leg Two\nT1 = 0; %Foot One not in contact with ground!\nT2 = Actuators(4,:); % (Nm) External torque applied to Leg Two\nThip = Actuators(5,:); % (Nm) Torque acting on Leg Two from Leg One\n\nm1 = Parameters.m1; % (kg) Foot One mass\nm2 = Parameters.m2; % (kg) Foot Two mass\nM = Parameters.M; % (kg) Hip mass\ng = Parameters.g; % (m/s^2) Gravity\n\n% Constraints for this phase: \nH1 = 0; %(N) Foot One, horizontal contact force\nV1 = 0; %(N) Foot One, vertical contact force\n\ndStates = zeros(size(States));\ndStates(1:6,:) = States((1+6):(6+6),:);\ndStates(7,:) = (T1.*sin(th1) - Thip.*sin(th1) + H1.*L1 - F1.*L1.*cos(th1))./(L1.*m1);\ndStates(8,:) = -(T1.*cos(th1) - L1.*V1 - Thip.*cos(th1) + L1.*g.*m1 + F1.*L1.*sin(th1))./(L1.*m1);\ndStates(9,:) = -(L2.*Thip.*m1 - L2.*T1.*m1 + L1.*T2.*m1.*cos(th1 - th2) + L1.*Thip.*m1.*cos(th1 - th2) - L2.*M.*T1.*cos(th1).^2 + L2.*M.*Thip.*cos(th1).^2 - L2.*M.*T1.*sin(th1).^2 + L2.*M.*Thip.*sin(th1).^2 + L1.*L2.*M.*V1.*cos(th1) - H1.*L1.*L2.*M.*sin(th1) - F2.*L1.*L2.*m1.*sin(th1 - th2) + 2.*L1.*L2.*M.*dL1.*dth1.*m1)./(L1.^2.*L2.*M.*m1);\ndStates(10,:) = (L2.*M.*T1.*sin(th1).*sin(th2) - L2.*T1.*m1.*cos(th1).*cos(th2) - L2.*M.*Thip.*sin(th1).*sin(th2) + L2.*Thip.*m1.*cos(th1).*cos(th2) - L2.*T1.*m1.*sin(th1).*sin(th2) + L2.*Thip.*m1.*sin(th1).*sin(th2) - L2.*M.*T1.*cos(th1).^3.*cos(th2) + L2.*M.*Thip.*cos(th1).^3.*cos(th2) - L1.*L2.*M.*V1.*cos(th2) + H1.*L1.*L2.*M.*sin(th2) - L2.*M.*T1.*sin(th1).^3.*sin(th2) + L2.*M.*Thip.*sin(th1).^3.*sin(th2) + L2.*M.*T1.*cos(th1).*cos(th2) - L2.*M.*Thip.*cos(th1).*cos(th2) + L1.*T2.*m1.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*Thip.*m1.*cos(th1 - th2).*cos(th1).*cos(th2) - L2.*M.*T1.*cos(th1).*cos(th2).*sin(th1).^2 + L2.*M.*Thip.*cos(th1).*cos(th2).*sin(th1).^2 + L1.*T2.*m1.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*T2.*m1.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*T2.*m1.*sin(th1 - th2).*cos(th2).*sin(th1) + L1.*Thip.*m1.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*Thip.*m1.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*Thip.*m1.*sin(th1 - th2).*cos(th2).*sin(th1) - F1.*L1.*L2.*M.*cos(th1).*sin(th2) + F1.*L1.*L2.*M.*cos(th2).*sin(th1) - L2.*M.*T1.*cos(th1).^2.*sin(th1).*sin(th2) + L2.*M.*Thip.*cos(th1).^2.*sin(th1).*sin(th2) + F1.*L1.*L2.*m1.*cos(th1).*sin(th2) - F1.*L1.*L2.*m1.*cos(th2).*sin(th1) - F1.*L1.*L2.*M.*cos(th2).*sin(th1).^3 + F1.*L1.*L2.*M.*cos(th1).^3.*sin(th2) + L1.*L2.*M.*V1.*cos(th1).^2.*cos(th2) - H1.*L1.*L2.*M.*cos(th1).^2.*sin(th2) + L1.*L2.*M.*V1.*cos(th2).*sin(th1).^2 - H1.*L1.*L2.*M.*sin(th1).^2.*sin(th2) + L1.*L2.*M.*g.*m1.*cos(th2) - F2.*L1.*L2.*m1.*cos(th1 - th2).*cos(th1).*sin(th2) + F2.*L1.*L2.*m1.*cos(th1 - th2).*cos(th2).*sin(th1) - F2.*L1.*L2.*m1.*sin(th1 - th2).*cos(th1).*cos(th2) - F1.*L1.*L2.*M.*cos(th1).^2.*cos(th2).*sin(th1) + F1.*L1.*L2.*M.*cos(th1).*sin(th1).^2.*sin(th2) - F2.*L1.*L2.*m1.*sin(th1 - th2).*sin(th1).*sin(th2) - 2.*L1.*L2.*M.*dL2.*dth2.*m1.*cos(th2).^2 - 2.*L1.*L2.*M.*dL2.*dth2.*m1.*sin(th2).^2)./(L1.*L2.^2.*M.*m1.*(cos(th2).^2 + sin(th2).^2));\ndStates(11,:) = -(T2.*m1.*sin(th1 - th2) + Thip.*m1.*sin(th1 - th2) - F1.*L2.*m1 + H1.*L2.*M.*cos(th1) + L2.*M.*V1.*sin(th1) + F2.*L2.*m1.*cos(th1 - th2) - F1.*L2.*M.*cos(th1).^2 - F1.*L2.*M.*sin(th1).^2 - L1.*L2.*M.*dth1.^2.*m1)./(L2.*M.*m1);\ndStates(12,:) = (L2.*M.*T1.*cos(th1).*sin(th2) - L2.*M.*T1.*cos(th2).*sin(th1) - L2.*M.*Thip.*cos(th1).*sin(th2) + L2.*M.*Thip.*cos(th2).*sin(th1) - L2.*T1.*m1.*cos(th1).*sin(th2) + L2.*T1.*m1.*cos(th2).*sin(th1) + L2.*Thip.*m1.*cos(th1).*sin(th2) - L2.*Thip.*m1.*cos(th2).*sin(th1) - H1.*L1.*L2.*M.*cos(th2) + L2.*M.*T1.*cos(th2).*sin(th1).^3 - L2.*M.*T1.*cos(th1).^3.*sin(th2) - L2.*M.*Thip.*cos(th2).*sin(th1).^3 + L2.*M.*Thip.*cos(th1).^3.*sin(th2) - L1.*L2.*M.*V1.*sin(th2) + L1.*L2.*M.*g.*m1.*sin(th2) + L1.*L2.^2.*M.*dth2.^2.*m1.*cos(th2).^2 + L1.*L2.^2.*M.*dth2.^2.*m1.*sin(th2).^2 + L1.*T2.*m1.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*T2.*m1.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*T2.*m1.*sin(th1 - th2).*cos(th1).*cos(th2) + L1.*Thip.*m1.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*Thip.*m1.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*Thip.*m1.*sin(th1 - th2).*cos(th1).*cos(th2) + F1.*L1.*L2.*M.*cos(th1).*cos(th2) + L2.*M.*T1.*cos(th1).^2.*cos(th2).*sin(th1) - L2.*M.*Thip.*cos(th1).^2.*cos(th2).*sin(th1) - L2.*M.*T1.*cos(th1).*sin(th1).^2.*sin(th2) + L2.*M.*Thip.*cos(th1).*sin(th1).^2.*sin(th2) + L1.*T2.*m1.*sin(th1 - th2).*sin(th1).*sin(th2) + L1.*Thip.*m1.*sin(th1 - th2).*sin(th1).*sin(th2) + F1.*L1.*L2.*M.*sin(th1).*sin(th2) - F1.*L1.*L2.*m1.*cos(th1).*cos(th2) - F1.*L1.*L2.*m1.*sin(th1).*sin(th2) - F1.*L1.*L2.*M.*cos(th1).^3.*cos(th2) + H1.*L1.*L2.*M.*cos(th1).^2.*cos(th2) + H1.*L1.*L2.*M.*cos(th2).*sin(th1).^2 - F1.*L1.*L2.*M.*sin(th1).^3.*sin(th2) + L1.*L2.*M.*V1.*cos(th1).^2.*sin(th2) + L1.*L2.*M.*V1.*sin(th1).^2.*sin(th2) + F2.*L1.*L2.*m1.*cos(th1 - th2).*cos(th1).*cos(th2) - F1.*L1.*L2.*M.*cos(th1).*cos(th2).*sin(th1).^2 + F2.*L1.*L2.*m1.*cos(th1 - th2).*sin(th1).*sin(th2) - F2.*L1.*L2.*m1.*sin(th1 - th2).*cos(th1).*sin(th2) + F2.*L1.*L2.*m1.*sin(th1 - th2).*cos(th2).*sin(th1) - F1.*L1.*L2.*M.*cos(th1).^2.*sin(th1).*sin(th2))./(L1.*L2.*M.*m1.*(cos(th2).^2 + sin(th2).^2));\n\n% contactForces(1,:) == H1 == (N) Foot One, horizontal contact force\n% contactForces(2,:) == V1 == (N) Foot One, vertical contact force\n% contactForces(3,:) == H2 == (N) Foot Two, horizontal contact force\n% contactForces(4,:) == V2 == (N) Foot Two, vertical contact force\ncontactForces = zeros(4,size(States,2));\ncontactForces(1,:) = zeros(1,size(States,2));\ncontactForces(2,:) = zeros(1,size(States,2));\ncontactForces(3,:) = (L2.*M.*T1.*m2.*sin(th1).^3 - L2.*M.*Thip.*m2.*sin(th1).^3 + L1.*M.*T2.*m1.*sin(th2) - L2.*M.*T1.*m2.*sin(th1) + L1.*M.*Thip.*m1.*sin(th2) + L2.*M.*Thip.*m2.*sin(th1) + L2.*T1.*m1.*m2.*sin(th1) - L2.*Thip.*m1.*m2.*sin(th1) - H1.*L1.*L2.*M.*m2 + L1.*T2.*m1.*m2.*cos(th1 - th2).^2.*sin(th2) + L1.*Thip.*m1.*m2.*cos(th1 - th2).^2.*sin(th2) - F1.*L1.*L2.*M.*m2.*cos(th1).^3 + H1.*L1.*L2.*M.*m2.*cos(th1).^2 + H1.*L1.*L2.*M.*m2.*cos(th2).^2 + L1.*T2.*m1.*m2.*sin(th1 - th2).^2.*sin(th2) + L1.*Thip.*m1.*m2.*sin(th1 - th2).^2.*sin(th2) + H1.*L1.*L2.*M.*m2.*sin(th1).^2 + H1.*L1.*L2.*M.*m2.*sin(th2).^2 - L1.*T2.*m1.*m2.*cos(th1 - th2).*sin(th1) + L1.*T2.*m1.*m2.*sin(th1 - th2).*cos(th1) - L2.*T1.*m1.*m2.*cos(th1 - th2).*sin(th2) - L2.*T1.*m1.*m2.*sin(th1 - th2).*cos(th2) - L1.*Thip.*m1.*m2.*cos(th1 - th2).*sin(th1) + L1.*Thip.*m1.*m2.*sin(th1 - th2).*cos(th1) + L2.*Thip.*m1.*m2.*cos(th1 - th2).*sin(th2) + L2.*Thip.*m1.*m2.*sin(th1 - th2).*cos(th2) + F1.*L1.*L2.*M.*m2.*cos(th1) - F2.*L1.*L2.*M.*m1.*cos(th2) + L2.*M.*T1.*m2.*cos(th1).^2.*sin(th1) + L2.*M.*T1.*m2.*cos(th2).^2.*sin(th1) - L2.*M.*Thip.*m2.*cos(th1).^2.*sin(th1) - L2.*M.*Thip.*m2.*cos(th2).^2.*sin(th1) + L2.*M.*T1.*m2.*sin(th1).*sin(th2).^2 - L2.*M.*Thip.*m2.*sin(th1).*sin(th2).^2 - F1.*L1.*L2.*m1.*m2.*cos(th1) - F1.*L1.*L2.*M.*m2.*cos(th1).*cos(th2).^2 - F1.*L1.*L2.*M.*m2.*cos(th1).*sin(th1).^2 - F1.*L1.*L2.*M.*m2.*cos(th1).*sin(th2).^2 - F1.*L1.*L2.*m1.*m2.*sin(th1 - th2).*sin(th2) + F2.*L1.*L2.*m1.*m2.*sin(th1 - th2).*sin(th1) - F2.*L1.*L2.*m1.*m2.*cos(th1 - th2).^2.*cos(th2) - F2.*L1.*L2.*m1.*m2.*sin(th1 - th2).^2.*cos(th2) - L2.*M.*T1.*m2.*cos(th1 - th2).*cos(th1).^2.*sin(th2) - L2.*M.*T1.*m2.*sin(th1 - th2).*cos(th1).^2.*cos(th2) + L2.*M.*Thip.*m2.*cos(th1 - th2).*cos(th1).^2.*sin(th2) + L2.*M.*Thip.*m2.*sin(th1 - th2).*cos(th1).^2.*cos(th2) - L2.*M.*T1.*m2.*cos(th1 - th2).*sin(th1).^2.*sin(th2) - L2.*M.*T1.*m2.*sin(th1 - th2).*cos(th2).*sin(th1).^2 + L2.*M.*Thip.*m2.*cos(th1 - th2).*sin(th1).^2.*sin(th2) + L2.*M.*Thip.*m2.*sin(th1 - th2).*cos(th2).*sin(th1).^2 + F1.*L1.*L2.*m1.*m2.*cos(th1 - th2).*cos(th2) + F2.*L1.*L2.*m1.*m2.*cos(th1 - th2).*cos(th1) + F1.*L1.*L2.*M.*m2.*cos(th1 - th2).*cos(th1).^2.*cos(th2) + F1.*L1.*L2.*M.*m2.*cos(th1 - th2).*cos(th2).*sin(th1).^2 - F1.*L1.*L2.*M.*m2.*sin(th1 - th2).*cos(th1).^2.*sin(th2) - F1.*L1.*L2.*M.*m2.*sin(th1 - th2).*sin(th1).^2.*sin(th2) - H1.*L1.*L2.*M.*m2.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*V1.*m2.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*L2.*M.*V1.*m2.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*V1.*m2.*sin(th1 - th2).*cos(th1).*cos(th2) - H1.*L1.*L2.*M.*m2.*cos(th1 - th2).*sin(th1).*sin(th2) + H1.*L1.*L2.*M.*m2.*sin(th1 - th2).*cos(th1).*sin(th2) - H1.*L1.*L2.*M.*m2.*sin(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*V1.*m2.*sin(th1 - th2).*sin(th1).*sin(th2))./(L1.*L2.*M.*m1.*(cos(th2).^2 + sin(th2).^2));\ncontactForces(4,:) = -(L1.*L2.*M.*V1.*m2 + L1.*M.*T2.*m1.*cos(th2) - L2.*M.*T1.*m2.*cos(th1) + L1.*M.*Thip.*m1.*cos(th2) + L2.*M.*Thip.*m2.*cos(th1) + L2.*T1.*m1.*m2.*cos(th1) - L2.*Thip.*m1.*m2.*cos(th1) + L2.*M.*T1.*m2.*cos(th1).^3 - L2.*M.*Thip.*m2.*cos(th1).^3 + L1.*T2.*m1.*m2.*cos(th1 - th2).^2.*cos(th2) + L1.*Thip.*m1.*m2.*cos(th1 - th2).^2.*cos(th2) + L1.*T2.*m1.*m2.*sin(th1 - th2).^2.*cos(th2) + L1.*Thip.*m1.*m2.*sin(th1 - th2).^2.*cos(th2) + F1.*L1.*L2.*M.*m2.*sin(th1).^3 - L1.*L2.*M.*V1.*m2.*cos(th1).^2 - L1.*L2.*M.*V1.*m2.*cos(th2).^2 - L1.*L2.*M.*V1.*m2.*sin(th1).^2 - L1.*L2.*M.*V1.*m2.*sin(th2).^2 - L1.*L2.*M.*g.*m1.*m2 - L1.*T2.*m1.*m2.*cos(th1 - th2).*cos(th1) - L2.*T1.*m1.*m2.*cos(th1 - th2).*cos(th2) - L1.*Thip.*m1.*m2.*cos(th1 - th2).*cos(th1) + L2.*Thip.*m1.*m2.*cos(th1 - th2).*cos(th2) + L2.*M.*T1.*m2.*cos(th1).*cos(th2).^2 - L2.*M.*Thip.*m2.*cos(th1).*cos(th2).^2 + L2.*M.*T1.*m2.*cos(th1).*sin(th1).^2 + L2.*M.*T1.*m2.*cos(th1).*sin(th2).^2 - L2.*M.*Thip.*m2.*cos(th1).*sin(th1).^2 - L2.*M.*Thip.*m2.*cos(th1).*sin(th2).^2 - L1.*T2.*m1.*m2.*sin(th1 - th2).*sin(th1) + L2.*T1.*m1.*m2.*sin(th1 - th2).*sin(th2) - L1.*Thip.*m1.*m2.*sin(th1 - th2).*sin(th1) - L2.*Thip.*m1.*m2.*sin(th1 - th2).*sin(th2) - F1.*L1.*L2.*M.*m2.*sin(th1) + F2.*L1.*L2.*M.*m1.*sin(th2) + F1.*L1.*L2.*m1.*m2.*sin(th1) + L2.*M.*T1.*m2.*sin(th1 - th2).*sin(th1).^2.*sin(th2) - L2.*M.*Thip.*m2.*sin(th1 - th2).*sin(th1).^2.*sin(th2) - F1.*L1.*L2.*m1.*m2.*cos(th1 - th2).*sin(th2) - F1.*L1.*L2.*m1.*m2.*sin(th1 - th2).*cos(th2) - F2.*L1.*L2.*m1.*m2.*cos(th1 - th2).*sin(th1) + F2.*L1.*L2.*m1.*m2.*sin(th1 - th2).*cos(th1) + F1.*L1.*L2.*M.*m2.*cos(th1).^2.*sin(th1) + F1.*L1.*L2.*M.*m2.*cos(th2).^2.*sin(th1) + F1.*L1.*L2.*M.*m2.*sin(th1).*sin(th2).^2 + F2.*L1.*L2.*m1.*m2.*cos(th1 - th2).^2.*sin(th2) + F2.*L1.*L2.*m1.*m2.*sin(th1 - th2).^2.*sin(th2) - L2.*M.*T1.*m2.*cos(th1 - th2).*cos(th1).^2.*cos(th2) + L2.*M.*Thip.*m2.*cos(th1 - th2).*cos(th1).^2.*cos(th2) - L2.*M.*T1.*m2.*cos(th1 - th2).*cos(th2).*sin(th1).^2 + L2.*M.*Thip.*m2.*cos(th1 - th2).*cos(th2).*sin(th1).^2 + L2.*M.*T1.*m2.*sin(th1 - th2).*cos(th1).^2.*sin(th2) - L2.*M.*Thip.*m2.*sin(th1 - th2).*cos(th1).^2.*sin(th2) - F1.*L1.*L2.*M.*m2.*cos(th1 - th2).*cos(th1).^2.*sin(th2) - F1.*L1.*L2.*M.*m2.*sin(th1 - th2).*cos(th1).^2.*cos(th2) - F1.*L1.*L2.*M.*m2.*cos(th1 - th2).*sin(th1).^2.*sin(th2) - F1.*L1.*L2.*M.*m2.*sin(th1 - th2).*cos(th2).*sin(th1).^2 + L1.*L2.*M.*V1.*m2.*cos(th1 - th2).*cos(th1).*cos(th2) + H1.*L1.*L2.*M.*m2.*cos(th1 - th2).*cos(th1).*sin(th2) - H1.*L1.*L2.*M.*m2.*cos(th1 - th2).*cos(th2).*sin(th1) + H1.*L1.*L2.*M.*m2.*sin(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*V1.*m2.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*L2.*M.*V1.*m2.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*L2.*M.*V1.*m2.*sin(th1 - th2).*cos(th2).*sin(th1) + H1.*L1.*L2.*M.*m2.*sin(th1 - th2).*sin(th1).*sin(th2))./(L1.*L2.*M.*m1.*(cos(th2).^2 + sin(th2).^2));\n\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/FancyDoublePendulum/Polar/computerGeneratedCode/dynamics_singleStanceTwo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.396105867718987}}
{"text": "function grid_params = bp_parse_grid_params( per_pulse_metadata, num_samples_used, varargin )\n%BP_PARSE_GRID_PARAMS Compute grid for backprojection\n% BP_PARSE_GRID_PARAMS(PER_PULSE_METADATA, NUM_SAMPLES_USED, ...\n% 'PropertyName', PropertyValue, ...)\n%\n% Property name Description\n% center Center of image to form in ECF coordinates.\n% Default is scene reference point.\n% grid_type 'slant', 'ground', or 'DEM'. Default is ground.\n% image_size_meters Scene size for image formation ([range_size\n% azimuth_size]) in meters. Default is total size\n% supported by collect.\n% image_size_pixels Size of the image in pixels (only used for images\n% formed to a DEM)\n% sample_rate Samples per IPR. Default is 1.5.\n% grid The grid of image points (ECEF) onto which the\n% image should be formed. The format of the grid\n% parameters is identical to the (MxNx3) grid\n% returned from this routine if no grid is\n% supplied.\n%\n% Output is a structure with the following fields:\n% center Same as input property\n% grid_type Same as input property\n% grid Same as input property\n% sample_rate Same as input property\n% range_vect_hat Unit vector point from center of aperture to\n% image center\n% image_size_meters Extent of the image in meters\n% image_size_pixels Size of the image in pixels\n% row_coords Vector describing position of each row. For\n% planar grids, this is the distance from the\n% center of the image in meters. For DEMs, this is\n% the latitude position in degrees of each row.\n% col_coords Vector describing position of each column.\n% row_unit_vector For planar grids, the unit vector in direction of\n% increasing row\n% col_unit_vector For planar grids, the unit vector in direction of\n% increasing column\n%\n% Authors: Wade Schwartzkopf and Tom Krauss, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n% Calculate default image extent and supported resolution (in slant plane)\npulse_bandwidth = per_pulse_metadata.SCSS * (num_samples_used-1);\n[max_resolution, max_extent] = pulse_info_to_resolution_extent(...\n per_pulse_metadata.TxPos - per_pulse_metadata.SRPPos, ... % Line-of-sight vector between ARP and ORP\n per_pulse_metadata.SC0 + (pulse_bandwidth/2), per_pulse_metadata.SCSS, ...\n pulse_bandwidth);\n\n% Parse input parameters\np1 = inputParser;\np1.KeepUnmatched=true;\np1.addParamValue('grid_type', 'ground', @(x) any(strcmp(x,{'slant','ground','DEM'})));\np1.addParamValue('grid', []); % Single grid that fits in memory. Perhaps in the future, this could also allow for a file input.\np1.addParamValue('center', mean(per_pulse_metadata.SRPPos), @(x) isempty(x) | (isvector(x)&&(length(x)==3))); % Centerpoint of formed image (ECEF, meters)\np1.addParamValue('image_size_meters', max_extent, @(x) (isvector(x)&&(length(x)==2))); % Scene extent [x y] (m)\np1.addParamValue('image_size_pixels', [], @(x) (isvector(x)&&(length(x)==2))); % Scene extent [x y] (pixels)\np1.addParamValue('sample_rate',1.5, @(x) (isvector(x)&&(length(x)<=2)));\np1.FunctionName = mfilename;\np1.parse(varargin{:});\ngrid_params = p1.Results;\n\n% Some geometry info\nrange_vect = grid_params.center - ... % Range vector points from center of aperture to image center\n ((per_pulse_metadata.TxPos(ceil(length(per_pulse_metadata.TxPos)/2),:) + ... % Use middle pulse\n per_pulse_metadata.RcvPos(ceil(length(per_pulse_metadata.RcvPos)/2),:))/2); % Bistatic definition, average of tx and rcv\n% range_vect = grid_params.center - ... % Range vector points from center of aperture to image center\n% per_pulse_metadata.TxPos(ceil(length(per_pulse_metadata.TxPos)/2),:); % Use middle pulse\ngrid_params.range_vect_hat = range_vect/norm(range_vect); % Unit vector\nvel_vector = per_pulse_metadata.TxPos(end,:)-per_pulse_metadata.TxPos(1,:); % Velocity vector\nspn=cross(grid_params.range_vect_hat,vel_vector); % Slant plane normal\nspn=spn/norm(spn); % Unit vector\n% Slant plane normal to point \"up\" (away from origin). This is affected by left/right looking.\nspn = spn * sign(grid_params.center*cross(grid_params.range_vect_hat,vel_vector).'); % Left/right fix\n\n% Determine final image size. IMAGE_SIZE_PIXELS input parameter is ignored\n% in all cases except for DEM. We only allow it for the DEM case, since we\n% don't currently have a robust automated way to determine it there.\nif ~isempty(grid_params.grid) % Arbitrary grid was passed in. Nothing to compute.\n grid_params.grid_type = 'ignore';\n grid_params.center = squeeze(mean(mean(grid_params.grid,1),2)); % Centroid of points in grid\n % grid_params.image_size_meters = ???\n grid_params.image_size_pixels = [size(grid_params.grid,1), size(grid_params.grid,2)];\n grid_params = rmfield(grid_params,'sample_rate'); % Not valid\n return; % Nothing left to do for explicitly passed grid\nelseif strcmpi(grid_params.grid_type,'DEM')\n if isempty(grid_params.image_size_pixels) % Default\n % Assures that at least sample rate is achieved in all directions.\n grid_params.image_size_pixels = ceil(grid_params.image_size_meters.*...\n max(grid_params.sample_rate)./min(max_resolution));\n end\nelse % Planar image (slant or ground)\n % Adjust distances from slant to ground if necessary\n if strcmpi(grid_params.grid_type,'ground')\n gpn = wgs_84_norm( grid_params.center ); % Ground plane normal, based on (inflated) wgs_84 ellipsoid\n graze = asin(gpn.'*(-grid_params.range_vect_hat.')); % radians\n twist = asin(cross(gpn.',spn)*(-grid_params.range_vect_hat.')/...\n norm(cross(-grid_params.range_vect_hat.',gpn.'))); % radians\n if any(strcmp(p1.UsingDefaults,'image_size_meters'))\n grid_params.image_size_meters(1) = grid_params.image_size_meters(1)/cos(graze);\n grid_params.image_size_meters(2) = grid_params.image_size_meters(2)/cos(twist);\n end \n max_resolution(1) = max_resolution(1)/cos(graze);\n max_resolution(2) = max_resolution(2)/cos(twist);\n end\n grid_params.image_size_pixels = ceil(grid_params.image_size_meters.*...\n grid_params.sample_rate./max_resolution);\nend\n\n% Compute grid onto which the image will be formed\nswitch grid_params.grid_type\n % For planar images (ground and slant) compute the unit vectors in the\n % direction of increasing row/column direction\n case 'ground'\n row_vector = grid_params.range_vect_hat-(grid_params.range_vect_hat*gpn)*gpn.'; % Project range vector to ground\n grid_params.row_unit_vector = row_vector/norm(row_vector); % Unit vector\n col_vector = -cross(grid_params.row_unit_vector,gpn); % Vector in direction of increasing column (ECEF)\n grid_params.col_unit_vector = col_vector/norm(col_vector); % Unit vector\n case 'slant'\n % Slant plane really has no meaning in backprojection. Any\n % arbitrary grid can be defined. We define it here merely for\n % comparison against PFA.\n grid_params.row_unit_vector = grid_params.range_vect_hat; % Unit vector in direction of increasing row (ECEF)\n grid_params.col_unit_vector = -cross(grid_params.row_unit_vector,spn); % Unit vector in direction of increasing column (ECEF)\n case 'DEM'\n % We'll also get the DEM data for the image. We assume that the\n % entire image fits within .2 degrees of lat and long and that the\n % entire DEM can fit into memory (reasonable for SRTM, but probably\n % not LIDAR).\n center_lla = ecf_to_geodetic(grid_params.center);\n [lats,lons,elevations] = get_DEM_heights_region([center_lla(1)-0.1,center_lla(2)-0.1], ...\n [center_lla(1)+0.1,center_lla(2)+0.1]);\n [lats, lons] = meshgrid(lats, lons);\n % Return DEM interpolation function, rather than the grid itself,\n % since for image formation we will need values not lying exactly\n % on the DEM points.\n grid_params.F_1 = TriScatteredInterp(lats(:), lons(:), elevations(:));\n \n % Convert scene extent from meters to arc-degrees\n e2 = 6.6943799901377997e-3; % eccentricity squared of Earth (WGS 84 value)\n a = 6378137.0; % semimajor radius of the Earth (WGS 84 value)\n b = a .* sqrt( 1.0 - e2); % semiminor radius of the Earth\n lat = pi/180*center_lla(1);\n M = (a*b)^2/((a*cos(lat))^2+(b*sin(lat))^2)^(3/2);\n N = a^2/sqrt((a*cos(lat))^2+(b*sin(lat))^2);\n arcradius_lat = pi/180*M; % length of arc-degree in latitude direction (m)\n arcradius_lon = pi/180*cos(lat)*N; % length of arc-degree in longitude direction (m)\n scene_extent_lat = grid_params.image_size_meters(1)/arcradius_lat;\n scene_extent_lon = grid_params.image_size_meters(2)/arcradius_lon;\nend\n% Compute row/column coordinates\nswitch grid_params.grid_type\n % For a plane, coordinates are distances (in meters) from the center\n % of image for each row/column\n case {'ground','slant'}\n grid_params.row_coords = grid_params.image_size_meters(1)*...\n linspace(-1,1,grid_params.image_size_pixels(1))/2;\n grid_params.col_coords = grid_params.image_size_meters(2)*...\n linspace(-1,1,grid_params.image_size_pixels(2))/2;\n % For a DEM, coordinates of each row/column are in lat/lon degrees;\n % that is, angularly, rather than along a plane.\n case 'DEM'\n grid_params.row_coords = center_lla(1) + (scene_extent_lat*...\n linspace(-1,1,grid_params.image_size_pixels(1))/2);\n grid_params.col_coords = center_lla(2) + (scene_extent_lon*...\n linspace(-1,1,grid_params.image_size_pixels(2))/2);\nend\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Processing/IFP/BP/bp_parse_grid_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39606613190297923}}
{"text": "function [vert,conn,tria,tnum] = smooth2(varargin)\n%SMOOTH2 \"hill-climbing\" mesh-smoothing for two-dimensional,\n%2-simplex triangulations.\n% [VERT,EDGE,TRIA,TNUM] = SMOOTH2(VERT,EDGE,TRIA,TNUM) re-\n% turns a \"smoothed\" triangulation {VERT,TRIA}, incorpora-\n% ting \"optimised\" vertex coordinates and mesh topology.\n%\n% VERT is a V-by-2 array of XY coordinates in the triangu-\n% lation, EDGE is an array of constrained edges, TRIA is a\n% T-by-3 array of triangles, and TNUM is a T-by-1 array of\n% part indices. Each row of TRIA and EDGE define an eleme-\n% nt. VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(TRIA\n% (II,3),:) are the coordinates of the II-TH triangle. The\n% edges in EDGE are defined in a similar manner. NUM is an\n% array of part indexing, such that TNUM(II) is the index \n% of the part in which the II-TH triangle resides.\n%\n% [VERT,EDGE,TRIA,TNUM] = SMOOTH2(... ,OPTS) passes an ad-\n% ditional options structure OPTS, containing user-defined \n% parameters, including:\n%\n% - OPTS.VTOL = {+1.0E-02} -- relative vertex movement tole-\n% rance, smoothing is converged when (VNEW-VERT) <= VTOL *\n% VLEN, where VLEN is a local effective length-scale.\n%\n% - OPTS.ITER = {+32} -- max. number of smoothing iterations\n%\n% - OPTS.DISP = {+ 4} -- smoothing verbosity. Set to INF for \n% quiet execution.\n%\n% See also REFINE2, TRICOST, TRIDEMO\n\n% This routine is loosely based on the DISTMESH algorithm,\n% employing a \"spring-based\" analogy to redistribute mesh\n% vertices. Such an approach is described in: P.O. Persson \n% and Gilbert Strang. \"A simple mesh generator in MATLAB.\" \n% SIAM review 46(2) 2004, pp: 329--345. Details of the al-\n% gorithm used here are somewhat different, with an alter-\n% ative spring-based update employed, in addition to hill-\n% climbing element quality guarantees, and vertex density\n% controls.\n\n%-----------------------------------------------------------\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 21/07/2017\n%-----------------------------------------------------------\n \n vert = []; conn = []; tria = [] ; \n tnum = []; \n opts = []; hfun = []; harg = {} ;\n \n%---------------------------------------------- extract args \n if (nargin>=+1), vert = varargin{1}; end\n if (nargin>=+2), conn = varargin{2}; end\n if (nargin>=+3), tria = varargin{3}; end\n if (nargin>=+4), tnum = varargin{4}; end\n if (nargin>=+5), opts = varargin{5}; end\n \n [opts] = makeopt(opts) ;\n\n%---------------------------------------------- default CONN\n if (isempty(conn))\n \n [edge] = tricon2(tria);\n\n ebnd = edge(:,4) < +1; %-- use bnd edge\n conn = edge(ebnd,1:2);\n \n end\n \n%---------------------------------------------- default TNUM\n if (isempty(tnum))\n tnum = ones(size(tria, 1), 1) ; \n end\n\n%---------------------------------------------- basic checks \n if ( ~isnumeric(vert) || ...\n ~isnumeric(conn) || ...\n ~isnumeric(tria) || ...\n ~isnumeric(tnum) || ...\n ~isstruct (opts) )\n error('smooth2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n \n%---------------------------------------------- basic checks\n if (ndims(vert) ~= +2 || ...\n ndims(conn) ~= +2 || ...\n ndims(tria) ~= +2 || ...\n ndims(tnum) ~= +2 )\n error('smooth2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n \n if (size(vert,2)~= +2 || ...\n size(conn,2)~= +2 || ...\n size(tria,2)~= +3 || ...\n size(tnum,2)~= +1 || ...\n size(tria,1)~= size(tnum,1) )\n error('smooth2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n nvrt = size(vert,1) ;\n\n%---------------------------------------------- basic checks\n if (min(min(conn(:,1:2))) < +1 || ...\n max(max(conn(:,1:2))) > nvrt )\n error('smooth2:invalidInputs', ...\n 'Invalid EDGE input array.') ;\n end\n \n if (min(min(tria(:,1:3))) < +1 || ...\n max(max(tria(:,1:3))) > nvrt )\n error('smooth2:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n\n%---------------------------------------------- output title\n if (~isinf(opts.disp))\n fprintf(1,'\\n') ;\n fprintf(1,' Smooth triangulation...\\n') ;\n fprintf(1,'\\n') ;\n fprintf(1,[...\n' -------------------------------------------------------\\n', ...\n' |ITER.| |MOVE(X)| |DTRI(X)| \\n', ...\n' -------------------------------------------------------\\n', ...\n ] ) ;\n end\n\n%---------------------------------------------- polygon bnds \n node = vert; PSLG = conn; part = {};\n\n pmax = max(tnum(:));\n for ppos = +1 : pmax\n \n tsel = tnum == ppos ;\n tcur = tria(tsel,:) ;\n \n [ecur,tcur] ...\n = tricon2 (tcur) ;\n \n ebnd = ecur(:,4)==0 ;\n \n same = setset2( ...\n PSLG,ecur(ebnd,1:2));\n \n part{ppos} = find(same) ;\n \n end\n\n%---------------------------------------------- inflate bbox\n vmin = min(vert,[],1);\n vmax = max(vert,[],1);\n \n vdel = vmax - 1.*vmin;\n vmin = vmin - .5*vdel;\n vmax = vmax + .5*vdel;\n\n vbox = [\n vmin(1), vmin(2)\n vmax(1), vmin(2)\n vmax(1), vmax(2)\n vmin(1), vmax(2)\n ] ;\n vert = [vert ; vbox] ;\n \n%---------------------------------------------- DO MESH ITER\n tnow = tic ;\n\n tcpu = struct('full',0.,'dtri',0., ...\n 'tcon',0.,'iter',0.,'undo',0., ...\n 'keep',0.) ;\n \n for iter = +1 : opts.iter\n \n %------------------------------------------ inflate adj.\n ttic = tic ;\n \n [edge,tria] = tricon2(tria,conn) ;\n \n tcpu.tcon = ...\n tcpu.tcon + toc(ttic) ;\n \n %------------------------------------------ compute scr.\n oscr = triscr2(vert,tria) ;\n \n %------------------------------------------ vert. iter's\n ttic = tic ;\n \n nvrt = size(vert,1);\n nedg = size(edge,1);\n \n IMAT = sparse( ...\n edge(:,1),(1:nedg)',+1,nvrt,nedg) ;\n JMAT = sparse( ...\n edge(:,2),(1:nedg)',+1,nvrt,nedg) ;\n \n EMAT = IMAT + JMAT ;\n \n vdeg = sum(EMAT,2) ; %-- vertex |deg|\n free = (vdeg == 0) ;\n \n vold = vert ;\n for isub = +1 : max(+2,min(+8,iter))\n \n %-- compute HFUN at vert/midpoints\n hvrt = evalhfn(vert, ...\n edge,EMAT,hfun,harg) ;\n \n hmid = hvrt(edge(:,1),:) ...\n + hvrt(edge(:,2),:) ;\n hmid = hmid * +.5 ;\n \n %-- calc. relative edge extensions \n evec = vert(edge(:,2),:) ...\n - vert(edge(:,1),:) ;\n elen = ...\n sqrt(sum(evec.^2,2)) ;\n \n scal = +1.0-elen./hmid ;\n scal = min (+1.0, scal);\n scal = max (-1.0, scal);\n \n %-- projected points from each end\n ipos = vert(edge(:,1),:) ...\n -.67*[scal,scal].*evec;\n jpos = vert(edge(:,2),:) ...\n +.67*[scal,scal].*evec;\n \n %scal = ... %-- nlin. weight\n % max(abs(scal).^.5,eps^.75); \n scal = ...\n max(abs(scal).^ 1,eps^.75);\n \n %-- sum contributions edge-to-vert \n vnew = ...\n IMAT*([scal,scal] .* ipos) ...\n + JMAT*([scal,scal] .* jpos) ;\n \n vsum = max(EMAT*scal,eps^.75);\n \n vnew = vnew ./ [vsum,vsum] ;\n\n %-- fixed points. edge projection?\n vnew(conn(:),1:2) = ...\n vert(conn(:),1:2) ;\n \n vnew(vdeg==0,1:2) = ...\n vert(vdeg==0,1:2) ;\n \n %-- reset for the next local iter. \n vert = vnew ;\n \n end\n \n tcpu.iter = ...\n tcpu.iter + toc(ttic) ;\n \n %------------------------------------------ hill-climber\n ttic = tic ;\n \n %-- unwind vert. upadte if score lower\n nscr = ones(size(tria,1),1);\n btri = true(size(tria,1),1);\n \n umax = + 8 ;\n \n for undo = +1 : umax\n \n nscr(btri) = triscr2( ...\n vert,tria(btri,:)) ;\n \n %-- TRUE if tria needs \"unwinding\" \n smin = +.70 ;\n smax = +.90 ;\n sdel = .025 ;\n \n stol = smin+iter*sdel;\n stol = min (smax,stol) ;\n \n btri = nscr <= stol ...\n & nscr < oscr ;\n \n if (~any(btri)), break; end\n \n %-- relax toward old vert. coord's\n ivrt = ...\n unique(tria(btri,1:3));\n \n bvrt = ...\n false(size(vert,1),1) ;\n bvrt(ivrt) = true;\n \n if (undo ~= umax)\n bnew = +.75 ^ undo ;\n bold = +1.0 - bnew ;\n else\n bnew = +0.0 ;\n bold = +1.0 - bnew ;\n end\n \n vert(bvrt,:) = ...\n bold * vold(bvrt,:) ... \n + bnew * vert(bvrt,:) ;\n \n btri = any( ...\n bvrt(tria(:,1:3)),2) ;\n \n end\n \n oscr = nscr ;\n \n tcpu.undo = ...\n tcpu.undo + toc(ttic) ;\n \n %------------------------------------- test convergence!\n ttic = tic ;\n \n vdel = ...\n sum((vert-vold).^2,2) ;\n \n evec = vert(edge(:,2),:) ...\n - vert(edge(:,1),:) ;\n elen = ...\n sqrt(sum(evec.^2,2)) ;\n \n hvrt = evalhfn(vert, ...\n edge,EMAT,hfun,harg) ;\n \n hmid = hvrt(edge(:,1),:) ...\n + hvrt(edge(:,2),:) ;\n hmid = hmid * 0.5 ;\n scal = elen./hmid ;\n\n emid = vert(edge(:,1),:) ...\n + vert(edge(:,2),:) ;\n emid = emid * 0.5 ; \n \n %------------------------------------- |deg|-based prune\n keep = false(size(vert,1),1);\n keep(vdeg>+4) = true ;\n \n keep(conn(:)) = true ;\n keep(free(:)) = true ;\n \n %------------------------------------- 'density' control\n lmax = +5. / +4. ;\n lmin = +1. / lmax ;\n \n less = scal<=lmin ;\n \tmore = scal>=lmax ;\n \n vbnd = false(size(vert,1),1);\n vbnd(conn(:,1)) = true ;\n vbnd(conn(:,2)) = true ;\n \n ebad = vbnd(edge(:,1)) ... %-- not at boundaries\n | vbnd(edge(:,2)) ;\n \n less(ebad(:)) = false;\n more(ebad(:)) = false;\n \n %------------------------------------- force as disjoint\n lidx = find (less) ;\n \n for lpos = 1 : length(lidx)\n epos = lidx(lpos,1);\n inod = edge(epos,1);\n jnod = edge(epos,2);\n %--------------------------------- if still disjoint\n if (keep(inod) && ...\n keep(jnod) )\n \n keep(inod) = false ;\n keep(jnod) = false ;\n\n else\n \n less(epos) = false ;\n \n end\n end\n \n ebad = ...\n keep(edge(less,1)) ...\n & keep(edge(less,2)) ;\n \n more(ebad(:)) = false ;\n \n %------------------------------------- reindex vert/tria\n redo = ...\n zeros(size(vert,1),1);\n itop = ...\n length(find(keep));\n iend = ...\n length(find(less));\n \n redo(keep) = (1:itop)';\n \n redo(edge(less,1)) = ... %-- to new midpoints\n (itop+1 : itop+iend)';\n redo(edge(less,2)) = ...\n (itop+1 : itop+iend)';\n \n vnew =[vert(keep,:) ; \n emid(less,:) ;\n ] ;\n tnew = redo(tria(:,1:3)) ;\n\n ttmp = sort(tnew,2) ; %-- filter collapsed\n okay = all( ...\n diff(ttmp,1,2)~=0,2) ;\n okay = ...\n okay & ttmp(:,1) > 0 ;\n tnew = tnew(okay,:) ;\n\n %------------------------------------- quality preserver\n nscr = ...\n triscr2 (vnew,tnew) ;\n\n stol = +0.80 ;\n \n tbad = nscr < stol ...\n & nscr < oscr(okay) ;\n \n vbad = ...\n false(size(vnew,1),1);\n vbad(tnew(tbad,:)) = true;\n \n %------------------------------------- filter edge merge\n lidx = find (less) ;\n \n ebad = ...\n vbad(redo(edge(lidx,1))) | ...\n vbad(redo(edge(lidx,2))) ;\n \n less(lidx(ebad)) = false ;\n \n keep(edge(...\n lidx(ebad),1:2)) = true ;\n \n %------------------------------------- reindex vert/conn\n redo = ...\n zeros(size(vert,1),1);\n itop = ...\n length(find(keep));\n iend = ...\n length(find(less));\n \n redo(keep) = (1:itop)';\n \n redo(edge(less,1)) = ...\n (itop+1 : itop+iend)';\n redo(edge(less,2)) = ...\n (itop+1 : itop+iend)';\n \n vert =[vert(keep,:);\n emid(less,:);\n emid(more,:);\n ] ;\n conn = redo(conn(:,1:2)) ;\n \n tcpu.keep = ...\n tcpu.keep + toc(ttic) ;\n \n %------------------------------------- build current CDT\n ttic = tic ;\n \n [vert,conn,tria,tnum] = ...\n deltri2 (vert, ...\n conn,node,PSLG,part) ;\n \n tcpu.dtri = ...\n tcpu.dtri + toc(ttic) ;\n \n %------------------------------------- dump-out progess!\n vdel = vdel./(hvrt.*hvrt) ;\n move = vdel > opts.vtol^2 ;\n nmov = ...\n length(find(move));\n \n ntri = size(tria,1) ;\n \n if (mod(iter,opts.disp)==+0)\n fprintf(+1, ...\n '%11i %18i %18i\\n', ...\n [iter,nmov,ntri]) ;\n end\n \n %------------------------------------- loop convergence!\n if (nmov == +0), break; end\n \n end\n\n tria = tria( :,1:3);\n \n%----------------------------------------- prune unused vert\n keep = false(size(vert,1),1);\n keep(tria(:)) = true ;\n keep(conn(:)) = true ;\n \n redo = zeros(size(vert,1),1);\n redo(keep) = ...\n (+1:length(find(keep)))';\n\n conn = redo(conn);\n tria = redo(tria);\n \n vert = vert(keep,:);\n \n tcpu.full = ...\n tcpu.full + toc(tnow) ;\n\n if (opts.dbug)\n%----------------------------------------- print debug timer \n fprintf(1,'\\n') ;\n fprintf(1,' Mesh smoothing timer...\\n');\n fprintf(1,'\\n') ;\n fprintf(1, ...\n ' FULL: %f \\n', tcpu.full);\n fprintf(1, ...\n ' DTRI: %f \\n', tcpu.dtri);\n fprintf(1, ...\n ' TCON: %f \\n', tcpu.tcon);\n fprintf(1, ...\n ' ITER: %f \\n', tcpu.iter);\n fprintf(1, ...\n ' UNDO: %f \\n', tcpu.undo); \n fprintf(1, ...\n ' KEEP: %f \\n', tcpu.keep);\n fprintf(1,'\\n') ;\n end\n \n if (~isinf(opts.disp)), fprintf(1,'\\n'); end\n\nend\n\nfunction [hvrt] = evalhfn(vert,edge,EMAT,hfun,harg)\n%EVALHFN eval. the spacing-fun. at mesh vertices.\n\n if (~isempty (hfun))\n if (isnumeric(hfun))\n hvrt = hfun * ...\n ones(size(vert,1),1) ;\n else\n hvrt = feval( ...\n hfun,vert,harg{:}) ;\n end\n else\n \n%-- no HFUN - HVRT is mean edge-len. at vertices! \n evec = vert(edge(:,2),:) - ...\n vert(edge(:,1),:) ;\n elen = sqrt(sum(evec.^2,2)) ;\n \n hvrt = (EMAT*elen) ...\n ./ max(sum(EMAT,2),eps) ;\n \n free = true(size(vert,1),1) ;\n free(edge(:,1)) = false;\n free(edge(:,2)) = false;\n \n hvrt(free) = +inf;\n \n end\n\nend\n\nfunction [opts] = makeopt(opts)\n%MAKEOPT setup the options structure for SMOOTH2.\n \n if (~isfield(opts,'iter'))\n opts.iter = +32;\n else\n if (~isnumeric(opts.iter))\n error('smooth2:incorrectInputClass', ...\n 'Incorrect input class.');\n end\n if (numel(opts.iter)~= +1)\n error('smooth2:incorrectDimensions', ...\n 'Incorrect input dimensions.') ; \n end\n if (opts.iter <= +0)\n error('smooth2:invalidOptionValues', ...\n 'Invalid OPT.ITER selection.') ;\n end\n end\n \n if (~isfield(opts,'disp'))\n opts.disp = + 4;\n else\n if (~isnumeric(opts.disp))\n error('smooth2:incorrectInputClass', ...\n 'Incorrect input class.');\n end\n if (numel(opts.disp)~= +1)\n error('smooth2:incorrectDimensions', ...\n 'Incorrect input dimensions.') ; \n end\n if (opts.disp <= +0)\n error('smooth2:invalidOptionValues', ...\n 'Invalid OPT.DISP selection.') ;\n end\n end\n \n if (~isfield(opts,'vtol'))\n opts.vtol = +1.0E-02;\n else\n if (~isnumeric(opts.vtol))\n error('smooth2:incorrectInputClass', ...\n 'Incorrect input class.');\n end\n if (numel(opts.vtol)~= +1)\n error('smooth2:incorrectDimensions', ...\n 'Incorrect input dimensions.') ; \n end\n if (opts.vtol <= 0.)\n error('smooth2:invalidOptionValues', ...\n 'Invalid OPT.VTOL selection.') ;\n end\n end\n \n if (~isfield(opts,'dbug'))\n opts.dbug = false;\n else\n if (~islogical(opts.dbug))\n error('refine2:incorrectInputClass', ...\n 'Incorrect input class.');\n end\n if (numel(opts.dbug)~= +1)\n error('refine2:incorrectDimensions', ...\n 'Incorrect input dimensions.') ; \n end\n end\n \nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/smooth2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.3958043751175517}}
{"text": "function metric = metric_euclidean(varargin)\n%METRIC_EUCLIDEAN An euclidean metric function\n%\n% Description\n% METRIC = METRIC_EUCLIDEAN('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% creates a an euclidean metric function structure in which the\n% named parameters have the specified values. Either\n% 'components' or 'deltadist' has to be specified. Any\n% unspecified parameters are set to default values.\n% \n% METRIC = METRIC_EUCLIDEAN(METRIC,'PARAM1',VALUE1,'PARAM2,VALUE2,...)\n% modify a metric function structure with the named parameters\n% altered with the specified values.\n%\n% Parameters for Euclidean metric function [default]\n% components - cell array of vectors specifying which \n% inputs are grouped together with a same\n% scaling parameter. For example, the\n% component specification {[1 2] [3]}\n% means that distance between 3\n% dimensional vectors computed as \n% r = (r_1^2 + r_2^2 )/l_1 + r_3^2/l_2,\n% where r_i are distance along component\n% i, and l_1 and l_2 are lengthscales for\n% corresponding component sets. If\n% 'components' is not specified, but\n% 'deltadist' is specified, then default\n% is {1 ... length(deltadist)}\n% deltadist - indicator vector telling which component sets\n% are handled using the delta distance \n% (0 if x=x', and 1 otherwise). Default is\n% false for all component sets.\n% lengthScale - lengthscales for each input component set\n% Default is 1 for each set\n% lengthScale_prior - prior for lengthScales [prior_unif]\n%\n% See also\n% GP_SET, GPCF_SEXP\n%\n% Copyright (c) 2008 Jouni Hartikainen \n% Copyright (c) 2008 Jarno Vanhatalo \n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'METRIC_EUCLIDEAN';\n ip.addOptional('metric', [], @isstruct);\n ip.addParamValue('components',[], @(x) isempty(x) || iscell(x));\n ip.addParamValue('deltadist',[], @(x) isvector(x) || isempty(x));\n ip.addParamValue('lengthScale',[], @(x) isvector(x) && all(x>0));\n ip.addParamValue('lengthScale_prior',prior_unif, ...\n @(x) isstruct(x) || isempty(x));\n ip.parse(varargin{:});\n metric=ip.Results.metric;\n\n if isempty(metric)\n % Initialize a Gaussian process\n init=true;\n else\n % Modify a Gaussian process\n if ~isfield(metric,'type') && isequal(metric.type,'metric_euclidean')\n error('First argument does not seem to be a metric structure')\n end\n init=false;\n end\n\n if init\n % Type\n metric.type = 'metric_euclidean';\n end\n \n % Components\n if init || ~ismember('components',ip.UsingDefaults)\n metric.components = ip.Results.components;\n end\n % Deltadist\n if init || ~ismember('deltadist',ip.UsingDefaults)\n metric.deltadist = ip.Results.deltadist;\n end\n % Components+Deltadist check and defaults\n if isempty(metric.components) && isempty(metric.deltadist)\n error('Either ''components'' or ''deltadist'' has to be specified')\n elseif isempty(metric.components)\n metric.components=num2cell(1:length(metric.components));\n elseif isempty(metric.deltadist)\n metric.deltadist = false(1,length(metric.components));\n end\n % Lengthscale\n if init || ~ismember('lengthScale',ip.UsingDefaults)\n metric.lengthScale = ip.Results.lengthScale;\n if isempty(metric.lengthScale)\n metric.lengthScale = repmat(1,1,length(metric.components));\n end\n end\n % Prior for lengthscale\n if init || ~ismember('lengthScale_prior',ip.UsingDefaults)\n metric.p=[];\n metric.p.lengthScale = ip.Results.lengthScale_prior;\n end\n \n if init\n % Set the function handles to the subfunctions\n metric.fh.pak = @metric_euclidean_pak;\n metric.fh.unpak = @metric_euclidean_unpak;\n metric.fh.lp = @metric_euclidean_lp;\n metric.fh.lpg = @metric_euclidean_lpg;\n metric.fh.dist = @metric_euclidean_dist;\n metric.fh.distg = @metric_euclidean_distg;\n metric.fh.ginput = @metric_euclidean_ginput;\n metric.fh.recappend = @metric_euclidean_recappend;\n end\n\nend\n\nfunction [w s] = metric_euclidean_pak(metric)\n%METRIC_EUCLIDEAN_PAK Combine GP covariance function\n% parameters into one vector.\n%\n% Description\n% W = METRIC_EUCLIDEAN_PAK(GPCF) takes a covariance function\n% structure GPCF and combines the covariance function\n% parameters and their hyperparameters into a single row\n% vector W and takes a logarithm of the covariance function\n% parameters.\n%\n% w = [ log(metric.lengthScale(:))\n% (hyperparameters of metric.lengthScale)]'\n% \n% See also\n% METRIC_EUCLIDEAN_UNPAK\n \n w = []; s = {};\n if ~isempty(metric.p.lengthScale)\n w = log(metric.lengthScale);\n if numel(metric.lengthScale)>1\n s = [s; sprintf('log(metric.lengthScale x %d)',numel(metric.lengthScale))];\n else\n s = [s; 'log(metric.lengthScale)'];\n end\n % Hyperparameters of lengthScale\n [wh sh] = metric.p.lengthScale.fh.pak(metric.p.lengthScale);\n w = [w wh];\n s = [s; sh];\n end\n \nend\n\nfunction [metric, w] = metric_euclidean_unpak(metric, w)\n%METRIC_EUCLIDEAN_UNPAK Separate metric parameter vector into components\n%\n% Description\n% METRIC, W] = METRIC_EUCLIDEAN_UNPAK(METRIC, W) takes a\n% metric structure GPCF and a parameter vector W, and returns\n% a covariance function structure identical to the input,\n% except that the covariance parameters have been set to the\n% values in W. Deletes the values set to GPCF from W and\n% returns the modified W.\n%\n% The covariance function parameters are transformed via exp\n% before setting them into the structure.\n%\n% See also\n% METRIC_EUCLIDEAN_PAK\n%\n \n if ~isempty(metric.p.lengthScale)\n i2=length(metric.lengthScale);\n i1=1;\n metric.lengthScale = exp(w(i1:i2));\n w = w(i2+1:end);\n \n % Hyperparameters of lengthScale\n [p, w] = metric.p.lengthScale.fh.unpak(metric.p.lengthScale, w);\n metric.p.lengthScale = p;\n end\nend\n\nfunction lp = metric_euclidean_lp(metric)\n%METRIC_EUCLIDEAN_LP Evaluate the log prior of metric parameters\n%\n% Description\n% LP = METRIC_EUCLIDEAN_LP(METRIC) takes a metric structure\n% METRIC and returns log(p(th)), where th collects the\n% parameters.\n%\n% See also\n% METRIC_EUCLIDEAN_PAK, METRIC_EUCLIDEAN_UNPAK, METRIC_EUCLIDEAN_G, GP_E\n%\n \n% Evaluate the prior contribution to the error. The parameters that\n% are sampled are from space W = log(w) where w is all the \"real\" samples.\n% On the other hand errors are evaluated in the W-space so we need take\n% into account also the Jakobian of transformation W -> w = exp(W).\n% See Gelman et al. (2013), Bayesian Data Analysis, third edition, p. 21.\n if ~isempty(metric.p.lengthScale)\n lp = metric.p.lengthScale.fh.lp(metric.lengthScale, metric.p.lengthScale) + sum(log(metric.lengthScale));\n else\n lp=0;\n end\n \nend\n\nfunction lpg = metric_euclidean_lpg(metric) \n%METRIC_EUCLIDEAN_LPG d log(prior)/dth of the metric parameters th\n%\n% Description\n% LPG = METRIC_EUCLIDEAN_LPG(METRIC) takes a likelihood\n% structure METRIC and returns d log(p(th))/dth, where th\n% collects the parameters.\n%\n% See also\n% METRIC_EUCLIDEAN_PAK, METRIC_EUCLIDEAN_UNPAK, METRIC_EUCLIDEAN, GP_E\n%\n\n% Evaluate the prior contribution of gradient with respect to lengthScale\n if ~isempty(metric.p.lengthScale)\n i1=1; \n lll = length(metric.lengthScale);\n lpgs = metric.p.lengthScale.fh.lpg(metric.lengthScale, metric.p.lengthScale);\n lpg(i1:i1-1+lll) = lpgs(1:lll).*metric.lengthScale + 1;\n lpg = [lpg lpgs(lll+1:end)];\n end\nend\n\nfunction gdist = metric_euclidean_distg(metric, x, x2, mask) \n%METRIC_EUCLIDEAN_DISTG Evaluate the gradient of the metric function\n%\n% Description\n% DISTG = METRIC_EUCLIDEAN_DISTG(METRIC, X) takes a metric\n% structure METRIC together with a matrix X of input\n% vectors and return the gradient matrices GDIST and\n% GPRIOR_DIST for each parameter.\n%\n% DISTG = METRIC_EUCLIDEAN_DISTG(METRIC, X, X2) forms the\n% gradient matrices between two input vectors X and X2.\n% \n% DISTG = METRIC_EUCLIDEAN_DISTG(METRIC, X, X2, MASK) forms\n% the gradients for masked covariances matrices used in sparse\n% approximations.\n%\n% See also\n% METRIC_EUCLIDEAN_PAK, METRIC_EUCLIDEAN_UNPAK, METRIC_EUCLIDEAN, GP_E\n%\n\n gdist=[];\n components = metric.components;\n \n n = size(x,1);\n m = length(components);\n i1=0;i2=1;\n\n % NOTE! Here we have already taken into account that the parameters\n % are transformed through log() and thus dK/dlog(p) = p * dK/dp\n \n if ~isempty(metric.p.lengthScale)\n if nargin <= 3\n if nargin == 2\n x2 = x;\n end\n ii1=0; \n\n dist = 0;\n distc = cell(1,m);\n % Compute the distances for each component set\n for i=1:m\n if length(metric.lengthScale)==1\n s=1./metric.lengthScale.^2;\n else\n s=1./metric.lengthScale(i).^2;\n end\n distc{i} = 0;\n for j = 1:length(components{i})\n if metric.deltadist(i)\n distc{i} = distc{i} + double(bsxfun(@ne,x(:,components{i}(j)),x2(:,components{i}(j))'));\n else\n distc{i} = distc{i} + bsxfun(@minus,x(:,components{i}(j)),x2(:,components{i}(j))').^2;\n end\n end\n distc{i} = distc{i}.*s;\n % Accumulate to the total distance\n dist = dist + distc{i};\n end\n dist = sqrt(dist);\n % Loop through component sets\n if length(metric.lengthScale)==1\n D = -distc{1};\n D(dist~=0) = D(dist~=0)./dist(dist~=0);\n ii1 = ii1+1;\n gdist{ii1} = D;\n else\n for i=1:m\n D = -distc{i};\n ind = dist~=0;\n D(ind) = D(ind)./dist(ind);\n ii1 = ii1+1;\n gdist{ii1} = D;\n end\n end\n% $$$ elseif nargin == 3\n% $$$ if size(x,2) ~= size(x2,2)\n% $$$ error('metric_euclidean -> _ghyper: The number of columns in x and x2 has to be the same. ')\n% $$$ end\n elseif nargin == 4\n gdist = cell(1,length(metric.lengthScale));\n end\n\n % Evaluate the prior contribution of gradient with respect to lengthScale\n if ~isempty(metric.p.lengthScale)\n i1=1; \n lll = length(metric.lengthScale);\n gg = -metric.p.lengthScale.fh.lpg(metric.lengthScale, metric.p.lengthScale);\n gprior(i1:i1-1+lll) = gg(1:lll).*metric.lengthScale - 1;\n gprior = [gprior gg(lll+1:end)];\n end\n end\nend\n\nfunction dist = metric_euclidean_dist(metric, x1, x2) \n%METRIC_EUCLIDEAN_DIST Compute the euclidean distence between\n% one or two matrices.\n%\n% Description\n% DIST = METRIC_EUCLIDEAN_DIST(METRIC, X) takes a metric\n% structure METRIC together with a matrix X of input\n% vectors and calculates the euclidean distance matrix DIST.\n%\n% DIST = METRIC_EUCLIDEAN_DIST(METRIC, X1, X2) takes a\n% metric structure METRIC together with a matrices X1 and\n% X2 of input vectors and calculates the euclidean distance\n% matrix DIST.\n%\n% See also\n% METRIC_EUCLIDEAN_PAK, METRIC_EUCLIDEAN_UNPAK, METRIC_EUCLIDEAN, GP_E\n%\n if (nargin == 2 || isempty(x2))\n % use fast c-code for self-distance\n x2=x1;\n % force deltadist to be logical for simplified c-code\n metric.deltadist=logical(metric.deltadist);\n dist = dist_euclidean(metric,x1);\n if ~any(isnan(dist))\n % if c-code was available, result is not NaN\n return\n end \n end\n \n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n \n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n \n components = metric.components;\n m = length(components);\n dist = 0; \n \n s=1./metric.lengthScale.^2;\n if m>numel(s)\n s=repmat(s,1,m);\n end\n for i=1:m\n for j = 1:length(components{i})\n if metric.deltadist(i)\n dist = dist + s(i).*double(bsxfun(@ne,x1(:,components{i}(j)),x2(:,components{i}(j))'));\n else\n dist = dist + s(i).*bsxfun(@minus,x1(:,components{i}(j)),x2(:,components{i}(j))').^2;\n end\n end\n end\n dist=sqrt(dist); % euclidean distance\n \nend\n\nfunction [ginput, gprior_input] = metric_euclidean_ginput(metric, x1, x2)\n%METRIC_EUCLIDEAN_GINPUT Compute the gradient of the\n% euclidean distance function with\n% respect to input. [n, m]=size(x);\n ii1 = 0;\n components = metric.components;\n \n if nargin == 2 || isempty(x2)\n x2=x1;\n end\n \n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n \n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n \n s = 1./metric.lengthScale.^2;\n dist = 0;\n for i=1:length(components)\n for j = 1:length(components{i})\n if metric.deltadist(i)\n dist = dist + s(i).*double(bsxfun(@ne,x1(:,components{i}(j)),x2(:,components{i}(j))'));\n else\n dist = dist + s(i).*bsxfun(@minus,x1(:,components{i}(j)),x2(:,components{i}(j))').^2;\n end\n end\n end\n dist = sqrt(dist);\n \n for i=1:m1\n for j = 1:n1\n DK = zeros(n1,n2); \n for k = 1:length(components)\n if ismember(i,components{k})\n if metric.deltadist(i)\n DK(j,:) = DK(j,:)+s(k).*double(bsxfun(@ne,x1(j,i),x2(:,i)'));\n else\n DK(j,:) = DK(j,:)+s(k).*bsxfun(@minus,x1(j,i),x2(:,i)');\n end\n end\n end\n if nargin == 2\n DK = DK + DK';\n end\n DK(dist~=0) = DK(dist~=0)./dist(dist~=0);\n \n ii1 = ii1 + 1;\n ginput{ii1} = DK;\n gprior_input(ii1) = 0; \n end\n end\n %size(ginput)\n %ginput\n \nend\n\n\nfunction recmetric = metric_euclidean_recappend(recmetric, ri, metric)\n%RECAPPEND Record append\n%\n% Description\n% RECMETRIC = METRIC_EUCLIDEAN_RECAPPEND(RECMETRIC, RI,\n% METRIC) takes old metric function record RECMETRIC, record\n% index RI and metric function structure. Appends the\n% parameters of METRIC to the RECMETRIC in the ri'th place.\n%\n% See also\n% GP_MC and GP_MC -> RECAPPEND\n\n% Initialize record\n if nargin == 2\n recmetric.type = 'metric_euclidean';\n metric.components = recmetric.components;\n \n % Initialize parameters\n recmetric.lengthScale = [];\n\n % Set the function handles\n recmetric.fh.pak = @metric_euclidean_pak;\n recmetric.fh.unpak = @metric_euclidean_unpak;\n recmetric.fh.lp = @metric_euclidean_lp;\n recmetric.fh.lpg = @metric_euclidean_lpg;\n recmetric.fh.dist = @metric_euclidean_dist;\n recmetric.fh.distg = @metric_euclidean_distg;\n recmetric.fh.ginput = @metric_euclidean_ginput; \n recmetric.fh.recappend = @metric_euclidean_recappend;\n return\n end\n mp = metric.p;\n\n % record parameters\n if ~isempty(metric.lengthScale)\n recmetric.lengthScale(ri,:)=metric.lengthScale;\n recmetric.p.lengthScale = metric.p.lengthScale.fh.recappend(recmetric.p.lengthScale, ri, metric.p.lengthScale);\n elseif ri==1\n recmetric.lengthScale=[];\n end\n\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/metric_euclidean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3956781069783796}}
{"text": "function au_qmr_ilu_m_i(A,mc,max_it_qmr,tol_qmr,tol_ilu,info_qmr)\n%\n% Generates the data used in 'au_qmr_ilu_m'. Data are stored in global \n% variables.\n% \n% Moreover, it defines the parameters mc, max_it_qmr, tol_qmr, \n% tol_ilu, and info_qmr, which are needed later in 'au_qmr_ilu_l_i' and \n% 'au_qmr_ilu_s_i'.\n%\n% Calling sequence:\n%\n% au_qmr_ilu_m_i(A,mc,max_it_qmr,tol_qmr,tol_ilu,info_qmr)\n%\n% Input:\n%\n% A real matrix;\n% mc (= 'M' or 'C') Optimize for memory ('M') or computation ('C')\n% when shifted systems are solved by 'au_qmr_ilu_l/s' later. \n% Optional (default value: 'M');\n% max_it_qmr maximal number of QMR steps allowed in 'au_qmr_ilu_l/s'.\n% Corresponds to parameter 'MAXIT' in MATLAB function 'qmr'.\n% Optional (default value: min([n-1,100]));\n% tol_qmr stopping tolerance (w.r.t. normalized residual) for QMR \n% iteration in 'au_qmr_ilu_l/s'. Corresponds to parameter 'TOL' \n% in MATLAB function 'qmr'. Optional (default value: 1e-14);\n% tol_ilu dropping tolerance for ILU preconditioner. Corresponds to\n% parameter 'DROPTOL' in MATLAB function 'luinc'. Optional \n% (default value: 1e-2);\n% info_qmr (= 0, 1, ...) If 1, warnings are printed when parameter FLAG\n% of MATLAB function 'qmr' is not equal to zero in QMR \n% iteration in 'au_qmr_ilu_l/s'. If 0, no warnings are\n% printed. Optional (default value: 1). \n%\n% Remark:\n%\n% If mc = 'M', the incomplete LU factors for A+p(i)*I are computed\n% any time 'au_qmr_ilu_s' is called, but they are not stored as global\n% variables to save memory. That means they are in general computed\n% several times, which results in additional computational cost. If\n% 'mc = C', the incomplete LU factors are computed once by calling\n% 'au_qmr_ilu_s_i' and stored as global variables, which results is\n% an increased memory demand. \n%\n% \n% LYAPACK 1.0 (Thilo Penzl, August 1999)\n\nna = nargin;\n\nif na<1 | na>6\n error('Wrong number of input arguments.');\nend\n\nif nargin < 2, mc = []; end\nif nargin < 3, max_it_qmr = []; end\nif nargin < 4, tol_qmr = []; end\nif nargin < 5, tol_ilu = []; end\nif nargin < 6, info_qmr = []; end\n\nif ~length(mc), mc = 'M'; end\nif ~length(max_it_qmr), max_it_qmr = min([size(A,1)-1,100]); end\nif ~length(tol_qmr), tol_qmr = 1e-14; end\nif ~length(tol_ilu), tol_ilu = 1e-2; end\nif ~length(info_qmr), info_qmr = 1; end\n\nglobal LP_A LP_MC LP_MAX_IT_QMR LP_TOL_QMR LP_TOL_ILU LP_INFO_QMR\n\nLP_A = A;\nLP_MC = mc;\nLP_MAX_IT_QMR = max_it_qmr;\nLP_TOL_QMR = tol_qmr;\nLP_TOL_ILU = tol_ilu;\nLP_INFO_QMR = info_qmr;\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21-lyapack/lyapack/usfs/au_qmr_ilu_m_i.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3954397411624637}}
{"text": "%-------------------------------------------------------------------------------------------------------------------%\n%\n% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear \n% \tfluid-structure interaction models. This version of the code is based off of\n%\tPeskin's Immersed Boundary Method Paper in Acta Numerica, 2002.\n%\n% Author: Nicholas A. Battista\n% Email: nick.battista@unc.edu\n% Date Created: May 27th, 2015\n% Institution: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs)\n% \t3. Target Points\n%\t4. Muscle-Model (combined Force-Length-Velocity model, \"HIll+(Length-Tension)\")\n%\n% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%\tlengths, etc\n% \n% There are a number of built in Examples, mostly used for teaching purposes. \n% \n% If you would like us %to add a specific muscle model, please let Nick (nick.battista@unc.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the RUBBERBAND-EXAMPLE geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Dear_KC()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 32; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nNy = 32; % # of Eulerian Grid Pts. in y-Direction (MUST BE EVEN!!!)\nLx = 1.0; % Length of Eulerian Grid in x-Direction\nLy = 1.0; % Length of Eulerian Grid in y-Direction\nds = Lx/(2*Nx); % Spatial step!\n\n\n% Immersed Structure Geometric / Dynamic Parameters %\nN = 2*Nx; % Number of Lagrangian Pts. (2x resolution of Eulerian grid)\nds_Rest = 0; % Resting length of springs\nstruct_name = 'dear_KC'; % Name for .vertex, .spring, etc files.\n\n% Line on top and bottom of geometry\nds2 = 0.125*ds;\nxLine = Lx/20:ds2:0.95*Lx;\nyLineB = 0.025*Lx*ones(1,length(xLine));\nyLineT= 0.975*Lx*ones(1,length(xLine));\n\nxSq = [xLine xLine yLineB yLineT];\nySq = [yLineB yLineT xLine xLine];\n\n% Call function to construct geometry\n[x1,y1] = give_Me_Immsersed_Boundary_Geometry_1(Lx,Nx,ds);\nx1 = [x1 xSq];\ny1 = [y1 ySq];\n\n% Call function to construct geometry\n[x2,y2] = give_Me_Immsersed_Boundary_Geometry_2(Lx,Nx,ds,x1);\nx2 = [x2 xSq];\ny2 = [y2 ySq];\n\n% Call function to construct geometry\n[x3,y3] = give_Me_Immsersed_Boundary_Geometry_3(Lx,Nx,ds);\nx3 = [x3 xSq];\ny3 = [y3 ySq];\n\n\n% Plot Geometry to test BEFORE taking out pts.\nfigure(1)\nplot(x1,y1,'r*'); hold on;\naxis([0 Lx 0 Ly]);\n\nfigure(2)\nplot(x2,y2,'b*'); hold on;\naxis([0 Lx 0 Ly]);\n\nfigure(3)\nplot(x3,y3,'k*'); hold on;\naxis([0 Lx 0 Ly]);\n\n\n% Print files to .txt files\nplease_Print_Vertices_To_File(x1,y1,x2,y2,x3,y3)\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(x1,y1,struct_name);\n\n\n% Prints .spring file!\n%k_Spring = 1e7;\n%print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Rest,struct_name);\n\n\n% Prints .beam file!\n%k_Beam = 0.5; C = 0.0;\n%print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name);\n\n\n% Prints .target file!\nk_Target = 1e6;\nprint_Lagrangian_Target_Pts(x1,k_Target,struct_name);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called struct.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag);\n\n vertex_fid = fopen([struct_name '.vertex'], 'w');\n\n fprintf(vertex_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n X_v = xLag(s);\n Y_v = yLag(s);\n fprintf(vertex_fid, '%1.16e %1.16e\\n', X_v, Y_v);\n end\n\n fclose(vertex_fid); \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints TARGET points to a file called struct.target\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name)\n\n N = length(xLag);\n\n target_fid = fopen([struct_name '.target'], 'w');\n\n fprintf(target_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\n if s > 284\n k_Target = 2.5e9;\n end\n fprintf(target_fid, '%d %1.16e\\n', s, k_Target);\n end\n\n fclose(target_fid); \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints BEAM (Torsional Spring) points to a file called struct.beam\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name)\n\n % k_Beam: beam stiffness\n % C: beam curvature\n \n N = length(xLag); % NOTE: Total number of beams = Number of Total Lag Pts. - 2\n\n beam_fid = fopen([struct_name '.beam'], 'w');\n\n fprintf(beam_fid, '%d\\n', N );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %BEAMS BETWEEN VERTICES\n for s = 2:N-1\n if s <= N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C); \n else\n %Case s=N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, 1, k_Beam, C); \n end\n end\n fclose(beam_fid); \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called struct.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Rest,struct_name)\n\n N = length(xLag);\n\n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', N );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %SPRINGS BETWEEN VERTICES\n for s = 1:N\n if s < N \n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n else\n %Case s=N\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, 1, k_Spring, ds_Rest); \n end\n end\n fclose(spring_fid); \n \n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for PHASE 1\n% msg: \"Hi KC!!\"\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry_1(Lx,Nx,ds)\n\n% The immsersed structure message #1: Hi Nghieng!! %\nlen = Lx/6.5;\n\nxC = 0;%-Lx/4;\nyC = 0;%-Lx/2;\n[xH,yH] = give_Me_The_Letter_Please_2(ds,len,'H',xC,yC); % (0,0)\n[xi1,yi1] = give_Me_The_Letter_Please_2(ds,len,'i',xC,yC-0.05);\n%\n[xN,yN] = give_Me_The_Letter_Please_2(ds,len,'N',xC,yC);\n[xg1,yg1] = give_Me_The_Letter_Please_2(ds,len,'g',xC,yC);\n[xh,yh] = give_Me_The_Letter_Please_2(ds,len,'h',xC,yC);\n[xi2,yi2] = give_Me_The_Letter_Please_2(ds,len,'i',xC,yC-0.05);\n[xe,ye] = give_Me_The_Letter_Please_2(ds,len,'e',xC,yC);\n[xn,yn] = give_Me_The_Letter_Please_2(ds,len,'n',xC,yC);\n[xg2,yg2] = give_Me_The_Letter_Please_2(ds,len,'g',xC,yC);\n\n% No room in domain for !'s\n%[xEx1,yEx1] = give_Me_The_Letter_Please_2(ds,1.2*len,'!',xC-0.55,yC);\n%[xEx2,yEx2] = give_Me_The_Letter_Please_2(ds,1.2*len,'!',xC-0.59,yC);\n\n% HI\nxH = xH + 0.45; yH = yH + 0.7;\nxi1 = xi1 + 0.55; yi1 = yi1 + 0.65;\n\n% Nghieng\nxN = xN + 0.15; yN = yN + 0.375;\nxg1 = xg1 + 0.325; yg1 = yg1 + 0.375;\nxh = xh + 0.435; yh = yh + 0.375;\nxi2 = xi2 + 0.515; yi2 = yi2 + 0.325;\nxe = xe + 0.59; ye = ye + 0.375;\nxn = xn + 0.7; yn = yn + 0.375;\nxg2 = xg2 + 0.8; yg2 = yg2 + 0.375;\n\n%\n% COMBINE GEOMETRY\n%\nxLag = [xH xi1 xN xg1 xh xi2 xe xn xg2];\nyLag = [yH yi1 yN yg1 yh yi2 ye yn yg2];\n\n%\n% Test Plot\n%\n% figure(1)\n% plot(xH,yH,'.'); hold on;\n% plot(xi1,yi1,'.'); hold on;\n% plot(xN,yN,'.'); hold on;\n% plot(xg1,yg1,'.'); hold on;\n% plot(xh,yh,'.'); hold on;\n% plot(xi2,yi2,'.'); hold on;\n% plot(xe,ye,'.'); hold on;\n% plot(xn,yn,'.'); hold on;\n% plot(xg2,yg2,'.'); hold on;\n\n%\n% Construct Horizontal Lines for Added Pts. in Domain\n%\nxRow = (0:ds:Lx/3) + 1/3;\nyRow = ones(size(xRow));\n\n\nxRow2 = (0:ds:Lx/6+ds) + 0.41666;\nyRow2 = ones(size(xRow2));\n\nxRow_T1 = xRow; yRow_T1 = 0.925*yRow;\nxRow_T2 = xRow2; yRow_T2 = 0.85*yRow2;\n\nxRow_B1 = [xRow xRow(end)+ds]; yRow_B1 = 0.075*[yRow 1];\nxRow_B2 = xRow2; yRow_B2 = 0.15*yRow2;\n\n%\n% Combine Letters + Horizontal Lines\n%\nxLag = [xLag xRow_T1 xRow_T2 xRow_B1 xRow_B2];\nyLag = [yLag yRow_T1 yRow_T2 yRow_B1 yRow_B2];\n\n%\n% Test Plot 2\n%\n% figure(11)\n% plot(xLag,yLag,'.'); hold on;\n% axis([0 1 0 1]);\n\n%\n% CHECK TO MAKE SURE EQUAL NUMBER OF MOVING LAGS AS OTHER PHASES\n% HERE: 284\n%\n%size(xLag)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for PHASE 2\n% msg: \"Would you like to ...\"\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry_2(Lx,Nx,ds,x1)\n\n% The immsersed structure message #2: Woud you like to... %\nlen = Lx/8;\n\nxC = -Lx/6;\nyC = -2*Lx/3;\n[xW,yW] = give_Me_The_Letter_Please(ds,len,'W',xC,yC);\n[xo,yo] = give_Me_The_Letter_Please(ds,len,'o',xC-0.1,yC);\n[xu,yu] = give_Me_The_Letter_Please(ds,len,'u',xC-0.18,yC);\n[xl,yl] = give_Me_The_Letter_Please(ds,len,'l',xC-0.27,yC);\n[xd,yd] = give_Me_The_Letter_Please(ds,1.2*len,'d',xC-0.29,yC);\n\n[xy,yy] = give_Me_The_Letter_Please(ds,1.2*len,'y',xC-0.47,yC);\n[xo2,yo2] = give_Me_The_Letter_Please(ds,len,'o',xC-0.55,yC);\n[xu2,yu2] = give_Me_The_Letter_Please(ds,len,'u',xC-0.63,yC);\n\nxC = -Lx/4;\nyC = -1*Lx/4 - Lx/6;\n[xl2,yl2] = give_Me_The_Letter_Please(ds,len,'l',xC,yC);\n[xi,yi] = give_Me_The_Letter_Please(ds,len,'i',xC-0.01,yC);\n[xk,yk] = give_Me_The_Letter_Please(ds,len,'k',xC-0.07,yC);\n[xe,ye] = give_Me_The_Letter_Please(ds,len,'e',xC-0.13,yC);\n\n[xt,yt] = give_Me_The_Letter_Please(ds,len,'t',xC-0.27,yC);\n[xo3,yo3] = give_Me_The_Letter_Please(ds,len,'o',xC-0.32,yC);\n\nyC = -1*Lx/5 - Lx/6;\n[xo4,yo4] = give_Me_The_Letter_Please(ds/3,len/6,'o',xC-0.44,yC);\n[xo5,yo5] = give_Me_The_Letter_Please(ds/3,len/6,'o',xC-0.48,yC);\n[xo6,yo6] = give_Me_The_Letter_Please(ds/3,len/6,'o',xC-0.52,yC);\n\nxLag = [xW xo xu xl xd xy xo2 xu2 xl2 xi xk xe xt xo3 xo4 xo5 xo6];\nyLag = [yW yo yu yl yd yy yo2 yu2 yl2 yi yk ye yt yo3 yo4 yo5 yo6];\n\n%x1Len = length(x1)\n%xLagLen=length(xLag)\n%PtsLeft = abs( length(xLag) - length(x1) )\n%ds1 = (Lx/2.5)/( PtsLeft/2 - 1 );\n\nxBL = 0:ds:Lx/2.5; xBL = xBL + 3/10*Lx;\nyTL = 0.84*ones(1,length(xBL));\nyBL = 0.18*ones(1,length(xBL));\n\n\nxLag = [xLag xBL xBL];\nyLag = [yLag yTL yBL];\n\n% plot(xW,yW,'r*'); hold on;\n% plot(xo,yo,'r*'); hold on;\n% plot(xu,yu,'r*'); hold on;\n% plot(xl,yl,'r*'); hold on;\n% plot(xd,yd,'r*'); hold on;\n% \n% plot(xy,yy,'r*'); hold on;\n% plot(xo2,yo2,'r*'); hold on;\n% plot(xu2,yu2,'r*'); hold on;\n% \n% plot(xl2,yl2,'r*'); hold on;\n% plot(xi,yi,'r*'); hold on;\n% plot(xk,yk,'r*'); hold on;\n% plot(xe,ye,'r*'); hold on;\n% \n% plot(xt,yt,'r*'); hold on;\n% plot(xo3,yo3,'r*'); hold on;\n% \n% plot(xo4,yo4,'r*'); hold on;\n% plot(xo5,yo5,'r*'); hold on;\n% plot(xo6,yo6,'r*'); hold on;\n% axis([0 Lx 0 Lx]);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for PHASE 2\n% msg: \"Would you like to ...\"\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry_3(Lx,Nx,ds)\n\n% The immsersed structure message #3: ...go on a date with me? %\nlen = Lx/9;\n\nxC = -Lx/8;\nyC = -3*Lx/4;\nshift = 0.2;\n\n[xo4,yo4] = give_Me_The_Letter_Please(ds/3,len/6,'o',xC,yC+0.09);\n[xo5,yo5] = give_Me_The_Letter_Please(ds/3,len/6,'o',xC-0.04,yC+0.09);\n[xo6,yo6] = give_Me_The_Letter_Please(ds/3,len/6,'o',xC-0.08,yC+0.09);\n\n[xg,yg] = give_Me_The_Letter_Please(ds,len,'g',xC-shift,yC);\n[xo,yo] = give_Me_The_Letter_Please(ds,len,'o',xC-0.1-shift,yC);\n\n[xo2,yo2] = give_Me_The_Letter_Please(ds,1.2*len,'o',xC-0.25-shift,yC);\n[xn,yn] = give_Me_The_Letter_Please(ds,1.2*len,'n',xC-0.34-shift,yC);\n\n[xa,ya] = give_Me_The_Letter_Please(ds,len,'a',xC-0.48-shift,yC);\n\n\nxC = -Lx/5;\nyC = -Lx/2;\n[xd,yd] = give_Me_The_Letter_Please(ds,len,'d',xC,yC);\n[xa2,ya2] = give_Me_The_Letter_Please(ds,len,'a',xC-0.08,yC);\n[xt,yt] = give_Me_The_Letter_Please(ds,len,'t',xC-0.16,yC);\n[xe,ye] = give_Me_The_Letter_Please(ds,len,'e',xC-0.22,yC);\n\n[xw,yw] = give_Me_The_Letter_Please(ds,1.1*len,'w',xC-0.37,yC);\n[xi,yi] = give_Me_The_Letter_Please(ds,len,'i',xC-0.45,yC);\n[xt2,yt2] = give_Me_The_Letter_Please(ds,len,'t',xC-0.505,yC);\n[xh,yh] = give_Me_The_Letter_Please(ds,len,'h',xC-0.58,yC);\n\nxC = -Lx/2.5;\nyC = -Lx/4;\n[xm,ym] = give_Me_The_Letter_Please(ds,1.1*len,'m',xC,yC);\n[xe2,ye2] = give_Me_The_Letter_Please(ds,len,'e',xC-0.12,yC);\n[xQU,yQU] = give_Me_The_Letter_Please(ds,1.2*len,'?',xC-0.22,yC);\n\nxLag = [xo4 xo5 xo6 xg xo xo2 xn xa xd xa2 xt xe xw xi xt2 xh xm xe2 xQU];\nyLag = [yo4 yo5 yo6 yg yo yo2 yn ya yd ya2 yt ye yw yi yt2 yh ym ye2 yQU];\n\n\n% plot(xo4,yo4,'r*'); hold on;\n% plot(xo5,yo5,'r*'); hold on;\n% plot(xo6,yo6,'r*'); hold on;\n% \n% plot(xg,yg,'r*'); hold on;\n% plot(xo,yo,'r*'); hold on;\n% \n% plot(xo2,yo2,'r*'); hold on;\n% plot(xn,yn,'r*'); hold on;\n% \n% plot(xa,ya,'r*'); hold on;\n% \n% plot(xd,yd,'r*'); hold on;\n% plot(xa2,ya2,'r*'); hold on;\n% plot(xt,yt,'r*'); hold on;\n% plot(xe,ye,'r*'); hold on;\n% \n% plot(xw,yw,'r*'); hold on;\n% plot(xi,yi,'r*'); hold on;\n% plot(xt2,yt2,'r*'); hold on;\n% plot(xh,yh,'r*'); hold on;\n% \n% plot(xm,ym,'r*'); hold on;\n% plot(xe2,ye2,'r*'); hold on;\n% plot(xQU,yQU,'r*'); hold on;\n% \n% axis([0 Lx 0 Lx]);\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%s%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for the Heart\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry_Heart(Lx,Nx,frac,Nb)\n\n% The immsersed structure is a heart %\nds = 2*pi/(Nb-1);\ntVec = 0:ds:2*pi;\n\nfor i=1:length(tVec)\n t = tVec(i);\n xLag(i)\t=\t16*sin(t)^3;\n yLag(i)\t=\t13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t);\nend\n\nxLag = frac*xLag + 0.5;\nyLag = frac*yLag + 0.5;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for PHASE 2 \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry_4(Lx,Nx,frac,Nb)\n\n% The immsersed structure is a heart %\nds = 2*pi/(Nb-1);\ntVec = 0:ds:2*pi;\nfor i=1:length(tVec)\n t = tVec(i);\n r(i) = 1 - sin(t);\n xLag(i)\t=\tr(i)*cos(t);\n yLag(i)\t=\tr(i)*sin(t);\nend\n\nxLag = frac*xLag;\nyLag = frac*yLag;\n\nminY = min(yLag);\nyLag = yLag - 3*minY/8;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: take out Lagrangian Pts.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x1,y1,x2,y2] = please_Take_Out_Points(x1,y1,x2,y2)\n\nn1 = 50;\nn2 = 70;\n\nx1 = [x1(1:n1) x1(n2:end)];\ny1 = [y1(1:n1) y1(n2:end)];\n\nx2 = [x2(1:n1) x2(n2:end)];\ny2 = [y2(1:n1) y2(n2:end)];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints all Vertices to File\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction please_Print_Vertices_To_File(X1,Y1,X2,Y2,X3,Y3)\n\nfileID = fopen('All_Positions.txt','w');\nfor j=1:length(X1)\n fprintf(fileID,'%1.16e %1.16e %1.16e %1.16e %1.16e %1.16e %1.16e %1.16e\\n', X1(j),Y1(j),X2(j),Y2(j),X3(j),Y3(j),X3(j),Y3(j) );\nend\nfclose(fileID);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: give me the letter!!!!!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x,y] = give_Me_The_Letter_Please(ds,len,letter,xC,yC)\n\nif strcmp(letter,'a')\n r = len/4.1;\n dt = ds/r;\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n xA(i) = r*cos(theta(i)) - xC;\n yA(i) = r*sin(theta(i)) - yC - len/4;\n end\n \n yLine = [-r:ds:r r]; yLine = yLine - yC - len/4;\n xLine = r*ones(1,length(yLine)) - (xC-ds/6);\n \n x = [xA xLine];\n y = [yA yLine];\n\nelseif strcmp(letter,'C')\n \n r = len/2;\n dt = ds/r;\n theta = pi/2:dt:pi-0.25*dt;\n theta = [theta pi -theta];\n for i=1:length(theta)\n x(i) = 3*r/4*cos(theta(i)) - xC;\n y(i) = r*sin(theta(i)) - yC;\n end\n \n xTB = 0:3*ds/4:len/6;\n xTB = xTB - xC + 0.01;\n yT = r*ones(1,length(xTB))-yC;\n yB = -r*ones(1,length(xTB))-yC;\n \n x = [xTB x xTB];\n y = [yT y yB];\n \n \n\n length(x)\n \nelseif strcmp(letter,'d')\n \n r = len/4.1;\n dt = ds/r;\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n xA(i) = r*cos(theta(i)) - xC;\n yA(i) = r*sin(theta(i)) - yC - len/4;\n end\n \n yLine = [-len/2:ds:len/2.25 r]; yLine = yLine - yC;\n xLine = r*ones(1,length(yLine)) - (xC-ds/6);\n \n x = [xA xLine];\n y = [yA yLine];\n \n elseif strcmp(letter,'e')\n \n r = len/4.1;\n yV = [-r:ds:r r]; \n xH = yV - xC;\n yH = zeros(1,length(xH)) - yC;\n yH2 = yH - len/4;\n yH3 = yH - len/2;\n \n yV = yV - yC - len/4;\n xV = r*ones(1,length(yV));\n \n yV3 = 0:-ds:-len/4;\n yV3 = yV3 - yC;\n xV3 = r*ones(1,length(yV3));\n \n x = [-xV-(xC-ds/6) xH xV3-(xC-ds/6) xH xH];\n y = [yV yH yV3 yH2 yH3];\n \n \nelseif strcmp(letter,'g')\n \n r = len/4.1;\n dt = ds/r;\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n xA(i) = r*cos(theta(i)) - xC;\n yA(i) = r*sin(theta(i)) - yC - len/4;\n end\n \n yLine = [-len/2:ds:len/2.25 r]; yLine = yLine - yC - len/3;\n xLine = r*ones(1,length(yLine)) - (xC-ds/6);\n \n yV = [-r:ds:r r]; \n xH = yV - xC;\n yH = zeros(1,length(xH)) - yC - 0.85*len;\n \n x = [xA xLine xH];\n y = [yA yLine yH];\n \nelseif strcmp(letter,'h')\n\n yLine = -len/2:ds:0-ds/4;\n yLine = [yLine 0 -yLine];\n yLine1 = yLine - yC;\n xLine1 = 1/2*len/2*ones(1,length(yLine1));\n \n yLine2 = -len/2:ds:0-ds/4;\n yLine2 = [yLine2 0];\n yLine2 = yLine2 - yC;\n xLine2 = 1/2*len/2*ones(1,length(yLine2));\n \n xH = (-1/2*len/2+ds/2:ds:1/2*len/2-ds/4);\n xH = xH - xC;\n yH = zeros(1,length(xH)) - yC;\n \n x = [-xLine1-xC xH xLine2-xC];\n y = [yLine1 yH yLine2]; \n \nelseif strcmp(letter,'H')\n yLine = -len/2:ds:0-ds/4;\n yLine = [yLine 0 -yLine];\n yLine = yLine - yC;\n xLine = 1/2*len/2*ones(1,length(yLine));\n xH = (-1/2*len/2+ds/2:ds:1/2*len/2-ds/4);\n xH = xH - xC;\n yH = zeros(1,length(xH)) - yC;\n \n x = [-xLine-xC xH xLine-xC];\n y = [yLine yH yLine];\n \nelseif strcmp(letter,'i')\n \n yLine = -len/2:ds:0-ds/4;\n yLine = yLine - yC;\n xLine = zeros(1,length(yLine)) - xC; \n \n r = len/21;\n dt = ds/(2*r);\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n xDot(i) = r*cos(theta(i)) - xC;\n yDot(i) = r*sin(theta(i)) - yC + len/7;\n end\n \n x = [xLine xDot];\n y = [yLine yDot];\n \n\nelseif strcmp(letter,'k')\n \n yLine = -len/2:ds:len/2;\n yLine = yLine - yC;\n xLine = zeros(1,length(yLine)) -xC-len/3.9;\n\n XD = 0:ds:len/sqrt(2);\n YD = zeros(1,length(XD));\n \n %rotate!\n for i=1:length(XD)\n xDt(i) = XD(i)*cos(pi/4)-YD(i)*sin(pi/4);\n yDt(i) = XD(i)*sin(pi/4)+YD(i)*cos(pi/4);\n \n xDb(i) = XD(i)*cos(pi/4)-YD(i)*sin(-pi/4);\n yDb(i) = XD(i)*sin(-pi/4)+YD(i)*cos(pi/4);\n end\n xDt = xDt - xC - len/4;\n yDt = yDt - yC;\n \n xDb = xDb - xC - len/4;\n yDb = yDb - yC;\n \n x = [xLine(1:ceil(0.75*end)) xDt(1:ceil(2*end/3)) xDb(1:ceil(2*end/3))];\n y = [yLine(1:ceil(0.75*end)) yDt(1:ceil(2*end/3))-len/8 yDb(1:ceil(2*end/3))-len/5.5];\n \nelseif strcmp(letter,'K')\n \n yLine = -len/2:ds:len/2;\n yLine = yLine - yC;\n xLine = zeros(1,length(yLine)) -xC-len/3.9;\n\n XD = 0:ds:len/sqrt(2);\n YD = zeros(1,length(XD));\n \n %rotate!\n for i=1:length(XD)\n xDt(i) = XD(i)*cos(pi/4)-YD(i)*sin(pi/4);\n yDt(i) = XD(i)*sin(pi/4)+YD(i)*cos(pi/4);\n \n xDb(i) = XD(i)*cos(pi/4)-YD(i)*sin(-pi/4);\n yDb(i) = XD(i)*sin(-pi/4)+YD(i)*cos(pi/4);\n end\n xDt = xDt - xC - len/4.5;\n yDt = yDt - yC;\n \n xDb = xDb - xC - len/5.5;\n yDb = yDb - yC;\n \n x = [xLine xDt xDb];\n y = [yLine yDt yDb];\n\n \nelseif strcmp(letter,'l')\n \n yLine = -len/2:ds:len/2.25;\n yLine = yLine - yC;\n xLine = 1/2*len/2*ones(1,length(yLine));\n\n x = -xLine-xC;\n y = yLine;\n\nelseif strcmp(letter,'m')\n \n r = len/2;\n xH = -r:ds:r; xH = xH - xC;\n yH = zeros(1,length(xH)) - yC;\n yV = 0:-ds:-len/2; yV = yV - yC;\n xV = -r*ones(1,length(yV)) - xC;\n xV2 = zeros(1,length(yV)) - xC;\n xV3 = r*ones(1,length(yV)) - xC;\n \n yVS = 0:ds:len/12;\n yVS = yVS - yC;\n xVS = -r*ones(1,length(yVS)) - xC;\n \n x = [xVS xH xV xV2 xV3];\n y = [yVS yH yV yV yV];\n \nelseif strcmp(letter,'n')\n \n r = len/4.1;\n yV = [-r:ds:r r]; \n xH = yV - xC;\n yH = zeros(1,length(xH)) - yC;\n \n yV = yV - yC - len/4;\n xV = r*ones(1,length(yV));\n \n yV2 = 0:ds:len/12;\n yV2 = yV2 - yC;\n xV2 = r*ones(1,length(yV2));\n \n x = [-xV-(xC-ds/6) -xV2-(xC-ds/6) xH xV-(xC-ds/6)];\n y = [yV yV2 yH yV];\n \n \nelseif strcmp(letter,'o')\n \n r = len/4.1;\n dt = ds/r;\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n x(i) = r*cos(theta(i)) - xC;\n y(i) = r*sin(theta(i)) - yC - len/4;\n end\n \n elseif strcmp(letter,'r')\n \n r = len/4.1;\n yV = [-r:ds:r r]; \n xH = yV - xC;\n yH = zeros(1,length(xH)) - yC;\n \n yV = yV - yC - len/4;\n xV = r*ones(1,length(yV));\n \n yV2 = 0:ds:len/12;\n yV2 = yV2 - yC;\n xV2 = r*ones(1,length(yV2));\n \n yV3 = 0:-ds:-len/10;\n yV3 = yV3 - yC;\n xV3 = r*ones(1,length(yV3));\n \n x = [-xV-(xC-ds/6) -xV2-(xC-ds/6) xH xV3-(xC-ds/6)];\n y = [yV yV2 yH yV3];\n \n \nelseif strcmp(letter,'t')\n \n yLine = -len/2:ds:len/2.25;\n yLine = yLine - yC;\n xLine = zeros(1,length(yLine));\n\n xH = -len/4:ds:len/4;\n xH = xH-xC;\n yH = zeros(1,length(xH)) - yC + len/9;\n \n x = [xLine-xC xH];\n y = [yLine yH];\n \n \nelseif strcmp(letter,'u')\n \n r = len/4.1;\n yV = [-r:ds:r r]; \n xH = yV - xC;\n yH = zeros(1,length(xH)) - yC - len/2;\n \n yV = yV - yC - len/4;\n xV = r*ones(1,length(yV));\n \n x = [-xV-(xC-ds/6) xH xV-(xC-ds/6)];\n y = [yV yH yV];\n\nelseif strcmp(letter,'v')\n \n XD = 0:ds:sqrt(5)*len/4;\n YD = zeros(1,length(XD));\n \n %rotate!\n ang = atan(2);\n for i=1:length(XD)\n xDr(i) = XD(i)*cos(ang)-YD(i)*sin(ang);\n yDr(i) = XD(i)*sin(ang)+YD(i)*cos(ang);\n \n xDL(i) = XD(i)*cos(pi-ang)-YD(i)*sin(pi-ang);\n yDL(i) = XD(i)*sin(pi-ang)+YD(i)*cos(pi-ang);\n end\n xDr = xDr - xC;\n yDr = yDr - yC - len/2;\n \n xDL = xDL - xC;\n yDL = yDL - yC - len/2;\n \n x = [xDL xDr(2:end)];\n y = [yDL yDr(2:end)];\n \nelseif strcmp(letter,'w')\n \n XD = 0:ds:sqrt(5)*len/4;\n YD = zeros(1,length(XD));\n \n %rotate!\n ang = atan(2);\n for i=1:length(XD)\n xDr(i) = XD(i)*cos(ang)-YD(i)*sin(ang);\n yDr(i) = XD(i)*sin(ang)+YD(i)*cos(ang);\n \n xDL(i) = XD(i)*cos(pi-ang)-YD(i)*sin(pi-ang);\n yDL(i) = XD(i)*sin(pi-ang)+YD(i)*cos(pi-ang);\n end\n xDr = xDr - xC - len/4;\n yDr = yDr - yC - len/2;\n \n xDL = xDL - xC - len/4;\n yDL = yDL - yC - len/2;\n \n x = [xDL xDr(2:end) xDL+len/2 xDr(2:end)+len/2];\n y = [yDL yDr(2:end) yDL yDr(2:end)]; \n \nelseif strcmp(letter,'W')\n \n XD = 0:ds:sqrt(5)*len/2;\n YD = zeros(1,length(XD));\n \n %rotate!\n ang = atan(2);\n for i=1:length(XD)\n xDr(i) = XD(i)*cos(ang)-YD(i)*sin(ang);\n yDr(i) = XD(i)*sin(ang)+YD(i)*cos(ang);\n \n xDL(i) = XD(i)*cos(pi-ang)-YD(i)*sin(pi-ang);\n yDL(i) = XD(i)*sin(pi-ang)+YD(i)*cos(pi-ang);\n end\n xDr = xDr - xC - len/4;\n yDr = yDr - yC - len/2;\n \n xDL = xDL - xC - len/4;\n yDL = yDL - yC - len/2;\n \n x = [xDL xDr(2:floor(end/2)) xDL(1:floor(end/2))+len/2 xDr(2:end)+len/2];\n y = [yDL yDr(2:floor(end/2)) yDL(1:floor(end/2)) yDr(2:end)]; \n \nelseif strcmp(letter,'y')\n \n XD = 0:ds:sqrt(5)*len/4;\n YD = zeros(1,length(XD));\n \n %rotate!\n ang = atan(2);\n for i=1:length(XD)\n xDr(i) = XD(i)*cos(ang)-YD(i)*sin(ang);\n yDr(i) = XD(i)*sin(ang)+YD(i)*cos(ang);\n \n xDL(i) = XD(i)*cos(pi-ang)-YD(i)*sin(pi-ang);\n yDL(i) = XD(i)*sin(pi-ang)+YD(i)*cos(pi-ang);\n \n xB(i) = XD(i)*cos(pi+ang)-YD(i)*sin(pi+ang);\n yB(i) = XD(i)*sin(pi+ang)+YD(i)*cos(pi+ang);\n end\n xDr = xDr - xC;\n yDr = yDr - yC - len/2;\n \n xDL = xDL - xC;\n yDL = yDL - yC - len/2;\n \n xB = xB - xC;\n yB = yB - yC - len/2;\n \n x = [xDL xDr(2:end) xB(2:end)];\n y = [yDL yDr(2:end) yB(2:end)];\n \n \nelseif strcmp(letter,'!')\n \n yLine = -len/4:ds:len/2;\n yLine = yLine - yC;\n xLine = zeros(1,length(yLine)) - xC; \n \n r = len/21;\n dt = ds/(2*r);\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n xDot(i) = r*cos(theta(i)) - xC;\n yDot(i) = r*sin(theta(i)) - yC - len/2.1;\n end\n \n x = [xLine xDot];\n y = [yLine yDot]; \n \nelseif strcmp(letter,'?')\n \n %xT = 0:ds:len/8-ds; xT = xT - xC - len/4;\n %yT = zeros(1,length(xT)) - yC + len/2;\n\n r = len/4;\n dt = ds/r;\n theta = 1.25*pi/2:-dt:-pi/2;\n for i=1:length(theta)\n xL(i) = 1.5*r*cos(theta(i)) - xC - len/8;\n yL(i) = r*sin(theta(i)) - yC + len/4;\n end\n \n yV = -ds:-ds:-len/3.25;\n xV = zeros(1,length(yV)) - xC - len/8;\n \n r = len/21;\n dt = ds/(2*r);\n theta = 0:dt:2*pi;\n for i=1:length(theta)\n xDot(i) = r*cos(theta(i)) - xC -len/8;\n yDot(i) = r*sin(theta(i)) - yC - len/2.1;\n end\n \n x = [xL xV xDot];\n y = [yL yV yDot]; \n \nend\n\n\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_KC/For_Danh/Dear_KC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39543974116246366}}
{"text": "function varargout = interp_ungridded(pos_from, pos_to, varargin)\n\n% INTERP_UNGRIDDED computes an interpolation matrix for two clouds of 3-D points\n%\n% To get the interpolated data, use as\n% [valto] = interp_ungridded(pos_from, pos_to, 'data', valfrom, ...)\n% or to get the interpolation matrix itself, use as\n% [interpmat, distmat] = interp_ungridded(pos_from, pos_to, ...)\n% where\n% pos_from Nx3 matrix with the vertex positions\n% pos_to Mx3 matrix with the vertex positions onto which the data should be interpolated\n%\n% Optional arguments are specified in key-value pairs and can be\n% data = NxK matrix with functional data\n% distmat = NxM matrix with precomputed distances\n% projmethod = 'nearest', 'sphere_avg', 'sphere_weighteddistance', 'smudge'\n% triout = triangulation for the second set of vertices\n% sphereradius = scalar\n% power = scalar, power parameter as in the Inverse Distance Weighting function proposed by Shepard (default = 1).\n\n% Copyright (C) 2007-2018, Jan-Mathijs Schoffelen & Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif nargin<3\n ft_error('Not enough input arguments.');\nend\n\n% get the optional arguments\nprojmethod = ft_getopt(varargin, 'projmethod'); % required\nsphereradius = ft_getopt(varargin, 'sphereradius'); % required for some projection methods\npowerparam = ft_getopt(varargin, 'power', 1);\ndistmat = ft_getopt(varargin, 'distmat'); % will be computed if needed and not present\ntriout = ft_getopt(varargin, 'triout');\ndat = ft_getopt(varargin, 'data'); % functional data defined at pos_from\ninside = ft_getopt(varargin, 'inside');\n\nhasdat = ~isempty(dat);\nhasinside = ~isempty(inside);\nnpos_from = size(pos_from, 1);\nnpos_to = size(pos_to, 1);\ndimres = sqrt(sum((pos_to(2,:)-pos_to(1,:)).^2,2));\n\nif hasinside\n % convert to boolean vector\n tmp = false(npos_from,1);\n tmp(inside) = true;\n inside = tmp;\n clear tmp;\nelse\n inside = true(npos_from,1);\nend\n\nif isempty(distmat)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % compute a distance matrix\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n switch projmethod\n case 'nearest'\n if ~isempty(sphereradius)\n ft_warning('sphereradius is not used for projmethod ''nearest''');\n end\n \n % determine the nearest voxel for each surface point\n ind = find_nearest(pos_to, pos_from, 5);\n sel = ind>0;\n indx = 1:npos_to;\n distmat = sparse(indx(sel), ind(sel), ones(size(ind(sel))), npos_to, npos_from);\n \n case {'sphere_avg', 'sphere_weighteddistance'}\n if isempty(sphereradius)\n ft_error('sphereradius should be specified');\n end\n \n % compute the distance between voxels and each surface point\n dpos_fromsq = sum(pos_from.^2,2); % squared distance to origin\n dpos_tosq = sum(pos_to.^2,2); % squared distance to origin\n maxnpnt = double(npos_to*ceil(4/3*pi*(sphereradius/max(dimres))^3)); % initial estimate of nonzero entries\n maxnpnt = min(maxnpnt, npos_to*npos_from);\n val = nan(maxnpnt, 1);\n indx1 = nan(maxnpnt, 1);\n indx2 = nan(maxnpnt, 1);\n cnt = 1;\n for j = 1:npos_to\n \n % d = dpos_tosq(j) + dpos_fromsq - 2 * pos_from * pos_to(j,:)';\n % sel = find(d0\n indx1(cnt:(cnt+nsel-1)) = j(ones(nsel,1));\n indx2(cnt:(cnt+nsel-1)) = sel(:);\n val(cnt:(cnt+nsel-1)) = d(sel) + eps('double');\n cnt = cnt + nsel;\n end\n end\n indx1(isnan(indx1)) = [];\n indx2(isnan(indx2)) = [];\n val(isnan(val)) = [];\n distmat = sparse(indx1, indx2, val, npos_to, npos_from);\n \n case 'smudge'\n if isempty(triout)\n ft_error('the ''smudge'' method needs a triangle definition');\n end\n \n [datin, loc] = ismember(pos_to, pos_from, 'rows'); % note that small numerical errors can cause them to be different\n [datout, S1] = smudge(datin, triout, 6); % FIXME 6 is number of iterations, improve here\n \n sel = find(datin);\n S2 = sparse(sel(:), loc(datin), ones(npos_from,1), npos_to, npos_from);\n distmat = S1 * S2;\n \n otherwise\n ft_error('unsupported projection method');\n end % case projmethod\nend % if isempty distmat\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% do something with the distance matrix\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch projmethod\n case 'nearest'\n projmat = distmat;\n \n case 'sphere_avg'\n projmat = distmat;\n [ind1, ind2] = find(projmat);\n nnz = full(sum(spones(projmat),2));\n for k = 1:length(ind1)\n projmat(ind1(k),ind2(k)) = 1./nnz(ind1(k));\n end\n \n case 'sphere_weighteddistance'\n projmat = distmat;\n [ind1, ind2, d] = find(projmat);\n projmat = sparse(ind1, ind2, d.^-powerparam, npos_to, npos_from);\n [ind1, ind2, d] = find(projmat);\n normnz = full(sum(projmat, 2));\n projmat = sparse(ind1, ind2, d./normnz(ind1), npos_to, npos_from);\n \n case 'smudge'\n projmat = distmat;\n \n otherwise\n ft_error('unsupported projection method');\nend % case projmethod\n\nif hasdat\n % return the interpolated values\n varargout{1} = projmat * dat;\nelse\n % return the interpolation and the distance matrix\n varargout{1} = projmat;\n varargout{2} = distmat;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/interp_ungridded.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.39519114226207724}}
{"text": "function asa183_test03 ( )\n\n%*****************************************************************************80\n%\n%% ASA183_TEST03 tests R8_RANDOM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ASA183_TEST03\\n' );\n fprintf ( 1, ' Show how the seeds used by R8_RANDOM,\\n' );\n fprintf ( 1, ' which change on each step, can be reset to\\n' );\n fprintf ( 1, ' restore any part of the sequence.\\n' );\n\n s1_save = 12345;\n s2_save = 34567;\n s3_save = 56789;\n\n s1 = s1_save;\n s2 = s2_save;\n s3 = s3_save;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Begin sequence with following seeds:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' S1 = %d\\n', s1 );\n fprintf ( 1, ' S2 = %d\\n', s2 );\n fprintf ( 1, ' S3 = %d\\n', s3 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I R S1 S2 S3\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n [ r, s1, s2, s3 ] = r8_random ( s1, s2, s3 );\n fprintf ( 1, ' %8d %14f %8d %8d %8d\\n', i, r, s1, s2, s3 );\n\n if ( i == 5 )\n s1_save = s1;\n s2_save = s2;\n s3_save = s3;\n end\n\n end\n\n s1 = s1_save;\n s2 = s2_save;\n s3 = s3_save;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Restart the sequence, using the seeds\\n' );\n fprintf ( 1, ' produced after step 5:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I R S1 S2 S3\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n [ r, s1, s2, s3 ] = r8_random ( s1, s2, s3 );\n fprintf ( 1, ' %8d %14f %8d %8d %8d\\n', i, r, s1, s2, s3 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/asa183/asa183_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.3951742269849399}}
{"text": "function MDP_DEM_Mixed_Models_Movement\n% This demo illustrates a series of computational pathologies as elicited\n% during a synthetic neurological examination. This focuses upon an\n% examination of the biceps reflex, and a simple coordination task. Each of\n% these are simulated for an arm that may move in three dimensions through\n% internal and external rotation of the shoulder, flexion and extension of\n% the shoulder, and flexion and extension of the elbow. These dynamics play\n% out through an active Bayesian filtering scheme, where a series of\n% attracting points draw the hand to different locations in 3D space. The\n% selection of these attracting points involves a hierarhical Markov\n% Decision Process, which identifies these sequences based upon the prior\n% belief that (1) the sequence will minimise expected free energy and (2)\n% the sequence is consistent with the trajectory predicted by the highest\n% (contextual) level of the model.\n%__________________________________________________________________________\n\n\nrng default\n\n% REFLEXES\n%==========================================================================\n% Demonstration 1 - Tendon reflexes (healthy, pyramidal lesion,\n% cerebellar lesion)\n\n% Specify generative model and process\n%--------------------------------------------------------------------------\n\na = 2; % length of upper arm\nb = 1.5; % length of forearm\nc = [-1;-1;-1]; % location of shoulder\n\nDEM = DEM_MDP_Movement_Disorders_GM; % Continuous state generative model\nx = [0;-1;1;0;0;0]; % Initial joint positions\n\n\nDEM.G(1).g = @(x,v,a,P) Gg1Reflex(x,v,a,P); % Generative process allows for tendon tap\nDEM.M(1).x = x;\nDEM.G(1).x = x;\nDEM.U = [MDP_DEM_MD_transform(x(1:3),a,b,c);0;0;0]*ones(1,64);\nDEM.C = zeros(size(DEM.U));\nDEM.C(3,10:12) = -0.25; % Transient stimulation of type II sensory afferents\n\n% Solve model and plot healthy reflexes\n%--------------------------------------------------------------------------\ndem = spm_ADEM(DEM);\n\n% Animate\nspm_figure('GetWin','Figure 1'); clf\nopengl('software')\nfor i = 1:size(dem.pU.x{1},2)\n MDP_DEM_MD_plot_arm(full(dem.pU.x{1}(1:3,i)),dem.M(1).pE.b1,dem.M(1).pE.b2,[-1;-1;-1]), hold on\n light\n view(10,0)\n zlim([-4 1])\n xlim([-1.2 2.1])\n drawnow\n hold off\n title('Normal')\nend\n\nclear dem\n\n% Upper motor lesion\n%--------------------------------------------------------------------------\nDEM.M(1).V = exp(5); % Overestimate precision\n\ndem = spm_ADEM(DEM);\n\n% Animate\nspm_figure('GetWin','Figure 1'); clf\nfor i = 1:size(dem.pU.x{1},2)\n MDP_DEM_MD_plot_arm(full(dem.pU.x{1}(1:3,i)),dem.M(1).pE.b1,dem.M(1).pE.b2,[-1;-1;-1]), hold on\n light\n view(10,0)\n zlim([-4 1])\n xlim([-1.2 2.1])\n drawnow\n hold off\n title('Pyramidal')\nend\n\nclear dem\n\n% Cerebellar\n%--------------------------------------------------------------------------\nDEM.M(1).V = exp(4); % Restore sensory precision\nDEM.M(1).E.s = 3/4; % Overestimate smoothness\n\ndem = spm_ADEM(DEM);\n\nspm_figure('GetWin','Figure 1'); clf\nfor i = 1:size(dem.pU.x{1},2)\n MDP_DEM_MD_plot_arm(full(dem.pU.x{1}(1:3,i)),dem.M(1).pE.b1,dem.M(1).pE.b2,[-1;-1;-1]), hold on\n light\n view(10,0)\n zlim([-4 1])\n xlim([-1.2 2.1])\n drawnow\n hold off\n title('Cerebellar')\nend\n\nclear all\n\n% COORDINATION\n%==========================================================================\n% Demonstration 2 - Mixed models (healthy)\n\n\n% Specify discrete generatve model and mapping between continuous and\n% discrete\n%--------------------------------------------------------------------------\n\n% Locations\n%--------------------------------------------------------------------------\n\n% 3D coordinates for three targets\nL1 = [ 1; -1; -3];\nL2 = [ -1; 1; -3];\nL3 = [ 0; 0; -1];\n\n% Intermediate (fictive) attracting points)\nfor i = 1:4\n L{i} = L1 + (i-1)*(L2 - L1)/4;\nend\nfor i = 5:8\n L{i} = L2 + (i-5)*(L3 - L2)/4;\nend\nfor i = 9:12\n L{i} = L3 + (i-9)*(L1 - L3)/4;\nend\n\n\n% MDP outcomes to DEM causes\n%--------------------------------------------------------------------------\nN = 14;\nnl = length(L);\nnh = 3;\n\nfor i = 1:nh\n for j = 1:nl\n for k = 1:2\n c = [L{j}; sparse(i,1,1,nh,1)];\n u = [L{j}; sparse(i,1,1,nh,1)];\n demi.U{i,j,k} = u*ones(1,N);\n demi.C{i,j,k} = c*ones(1,N);\n end\n end\nend\n\no = [1 1 1];\nO{1} = spm_softmax(ones(nh,1));\nO{2} = spm_softmax(ones(nl,1));\nO{3} = spm_softmax(ones(2,1));\n\n% generative model (Continuous)\n%==========================================================================\nDEM = DEM_MDP_Movement_Disorders_GM;\nDEM = spm_MDP_DEM(DEM,demi,O,o);\n\n% generative model (Discrete)\n%==========================================================================\nmdp = MDP_DEM_Movement_Disorders_GM_1;\nmdp.demi = demi;\nmdp.DEM = DEM;\n\nmdp = MDP_DEM_Movement_Disorders_GM_2(mdp);\n\n% invert or solve\n%--------------------------------------------------------------------------\nrng default\nMDP = spm_MDP_check(mdp);\nMDP = spm_MDP_VB_X(MDP);\n\n% illustrate belief updating - discrete\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2'); clf\nspm_MDP_VB_LFP(MDP,[],2);\n\n% illustrate belief updating - continuous (last movement)\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 3'); clf;\nspm_DEM_qU(MDP.mdp(end).dem(end).qU)\n\n% illustrate movement\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 4'); clf\n\n[Q, R, X, Y, Z] = MDP_DEM_Movement_Disorders_Animate(MDP,L);\n\n\nspm_figure('GetWin','Figure 4'); clf\nplot3(Q(1,:),Q(2,:),Q(3,:),'LineWidth',2,'Color','k'), hold on\nfor m = 1:length(MDP.mdp)\n for j = 1:length(MDP.mdp(m).dem)\n h = (m - 1)*length(MDP.mdp(m).dem) + j;\n H = length(MDP.mdp)*length(MDP.mdp(m).dem);\n surf(0.1*X + MDP.mdp(m).dem(j).qU.v{2}(1,i),0.1*Y + MDP.mdp(m).dem(j).qU.v{2}(2,i),0.1*Z + MDP.mdp(m).dem(j).qU.v{2}(3,2),'Facecolor','r','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'FaceAlpha',h/(1.5*H))\n end\nend\n\nlight\naxis equal\nspm_figure('GetWin','Figure 5'); clf\nsubplot(5,1,1)\nplot(0.05*(0:size(R,2)-1),R' - repmat(R(:,1)',size(R,2),1))\ntitle('Normal')\n\n% Demonstration 3 - Mixed models (Pyramidal versus extrapyramidal)\n%--------------------------------------------------------------------------\n% Pyramidal\n\nmdp.MDP.DEM.M(1).V = exp(5); % Overestimate precision\n\n% invert or solve\n%--------------------------------------------------------------------------\nrng default\nMDP = spm_MDP_check(mdp);\nMDP = spm_MDP_VB_X(MDP);\n\nspm_figure('GetWin','Figure 6'); clf\n\n[Q, R, X, Y, Z] = MDP_DEM_Movement_Disorders_Animate(MDP,L);\n\n\nspm_figure('GetWin','Figure 6'); clf\nplot3(Q(1,:),Q(2,:),Q(3,:),'LineWidth',2,'Color','k'), hold on\nfor m = 1:length(MDP.mdp)\n for j = 1:length(MDP.mdp(m).dem)\n h = (m - 1)*length(MDP.mdp(m).dem) + j;\n H = length(MDP.mdp)*length(MDP.mdp(m).dem);\n surf(0.1*X + MDP.mdp(m).dem(j).qU.v{2}(1,i),0.1*Y + MDP.mdp(m).dem(j).qU.v{2}(2,i),0.1*Z + MDP.mdp(m).dem(j).qU.v{2}(3,2),'Facecolor','r','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'FaceAlpha',h/(1.5*H))\n end\nend\nlight\naxis equal\n\nspm_figure('GetWin','Figure 5');\nsubplot(5,1,2)\nplot(0.05*(0:size(R,2)-1),R' - repmat(R(:,1)',size(R,2),1))\ntitle('Pyramidal')\n\n% Extrapyramidal\n%--------------------------------------------------------------------------\nmdp.MDP.DEM.M(1).V = exp(4);\nmdp.MDP.beta = 50;\n\n% invert or solve\n%--------------------------------------------------------------------------\nrng default\nMDP = spm_MDP_check(mdp);\nMDP = spm_MDP_VB_X(MDP);\n\n% illustrate movement\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 8'); clf\n\n[Q, R, X, Y, Z] = MDP_DEM_Movement_Disorders_Animate(MDP,L);\n\n\nspm_figure('GetWin','Figure 8'); clf\nplot3(Q(1,:),Q(2,:),Q(3,:),'LineWidth',2,'Color','k'), hold on\nfor m = 1:length(MDP.mdp)\n for j = 1:length(MDP.mdp(m).dem)\n h = (m - 1)*length(MDP.mdp(m).dem) + j;\n H = length(MDP.mdp)*length(MDP.mdp(m).dem);\n surf(0.1*X + MDP.mdp(m).dem(j).qU.v{2}(1,i),0.1*Y + MDP.mdp(m).dem(j).qU.v{2}(2,i),0.1*Z + MDP.mdp(m).dem(j).qU.v{2}(3,2),'Facecolor','r','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'FaceAlpha',h/(1.5*H))\n end\nend\nlight\naxis equal\n\nspm_figure('GetWin','Figure 5');\nsubplot(5,1,3)\nplot(0.05*(0:size(R,2)-1),R' - repmat(R(:,1)',size(R,2),1))\ntitle('Extrapyramidal')\n\n% Cerebellar\n%--------------------------------------------------------------------------\nmdp.MDP.beta = 16;\nmdp.MDP.DEM.M(1).E.s = 3/4;\n\n% invert or solve\n%--------------------------------------------------------------------------\nrng default\nMDP = spm_MDP_check(mdp);\nMDP = spm_MDP_VB_X(MDP);\n\n% illustrate movement\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 9'); clf\n\n[Q, R, X, Y, Z] = MDP_DEM_Movement_Disorders_Animate(MDP,L);\n\nspm_figure('GetWin','Figure 9'); clf\nplot3(Q(1,:),Q(2,:),Q(3,:),'LineWidth',2,'Color','k'), hold on\nfor m = 1:length(MDP.mdp)\n for j = 1:length(MDP.mdp(m).dem)\n h = (m - 1)*length(MDP.mdp(m).dem) + j;\n H = length(MDP.mdp)*length(MDP.mdp(m).dem);\n surf(0.1*X + MDP.mdp(m).dem(j).qU.v{2}(1,i),0.1*Y + MDP.mdp(m).dem(j).qU.v{2}(2,i),0.1*Z + MDP.mdp(m).dem(j).qU.v{2}(3,2),'Facecolor','r','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'FaceAlpha',h/(1.5*H))\n end\nend\nlight\naxis equal\n\nspm_figure('GetWin','Figure 5');\nsubplot(5,1,4)\nplot(0.05*(0:size(R,2)-1),R' - repmat(R(:,1)',size(R,2),1))\ntitle('Cerebellar')\n\n% Executive\n%--------------------------------------------------------------------------\nmdp.MDP.DEM.M(1).E.s = 1/2;\nmdp.A{3} = ones(size(mdp.A{3})); % Disconnect higher level\n\n% invert or solve\n%--------------------------------------------------------------------------\nrng default\nMDP = spm_MDP_check(mdp);\nMDP = spm_MDP_VB_X(MDP);\n\n% illustrate movement\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 10'); clf\n\n[Q, R, X, Y, Z] = MDP_DEM_Movement_Disorders_Animate(MDP,L);\n\nspm_figure('GetWin','Figure 10'); clf\nplot3(Q(1,:),Q(2,:),Q(3,:),'LineWidth',2,'Color','k'), hold on\nfor m = 1:length(MDP.mdp)\n for j = 1:length(MDP.mdp(m).dem)\n h = (m - 1)*length(MDP.mdp(m).dem) + j;\n H = length(MDP.mdp)*length(MDP.mdp(m).dem);\n surf(0.1*X + MDP.mdp(m).dem(j).qU.v{2}(1,i),0.1*Y + MDP.mdp(m).dem(j).qU.v{2}(2,i),0.1*Z + MDP.mdp(m).dem(j).qU.v{2}(3,2),'Facecolor','r','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'FaceAlpha',h/(1.5*H))\n end\nend\nlight\naxis equal\n\nspm_figure('GetWin','Figure 5');\nsubplot(5,1,5)\nplot(0.05*(0:size(R,2)-1),R' - repmat(R(:,1)',size(R,2),1))\ntitle('Executive')\n\nfunction MDP = MDP_DEM_Movement_Disorders_GM_1\n\n% First level\n%--------------------------------------------------------------------------\n\n% Initial states\n%--------------------------------------------------------------------------\nD{1} = ones(3,1); % Location of visual cue\nD{2} = zeros(12,1); % Location of arm\nD{2}(1) = 1;\n\n% Likelihood\n%--------------------------------------------------------------------------\nfor f1 = 1:numel(D{1})\n for f2 = 1:numel(D{2})\n A{1}(f1,f1,f2) = 1; % Vision (target)\n A{2}(f2,f1,f2) = 1; % Vision + Proprioception (arm)\n A{3}(2,f1,f2) = (f1 == ((f2-1)/4)+1); % At target\n A{3}(1,f1,f2) = ~(f1 == ((f2-1)/4)+1); % Not at target\n end\nend\n\n% Transitions\n%--------------------------------------------------------------------------\nB{1} = eye(3);\n\nfor k = 1:length(D{2})\n for j = 1:length(D{2})\n if k == j\n B{2}(k,j,1) = 1; % Stay still\n elseif (k - j) == 1\n B{2}(k,j,2) = 1; % Move to next point\n elseif (j - k) == 1\n B{2}(k,j,3) = 1; % Move to previous point\n end\n end\nend\n\nB{2}(1,end,2) = 1;\nB{2}(end,1,3) = 1;\n\n% Preferences\n%--------------------------------------------------------------------------\nC{1} = zeros(3,1);\nC{2} = zeros(12,1);\nC{3} = [-3 3]';\n\n% Policies\n%--------------------------------------------------------------------------\nV(:,:,1) = ones(8,3); % (time, policy, factor)\nV(:,:,2) = [1 2 3;\n 1 2 3;\n 1 2 3;\n 1 2 3;\n 1 1 1;\n 1 1 1;\n 1 1 1;\n 1 1 1];\n\nE = [1 0.5 0.5]';\n\n% First level MDP\n%--------------------------------------------------------------------------\nMDP.A = A;\nMDP.B = B;\nMDP.C = C;\nMDP.D = D;\nMDP.E = E;\nMDP.V = V;\nMDP.T = 9;\nMDP.chi = -exp(64);\nMDP.beta = 16;\n% MDP.beta = 50;\nMDP = spm_MDP_check(MDP);\n\nfunction MDP = MDP_DEM_Movement_Disorders_GM_2(mdp)\n\n\n% First level\n%--------------------------------------------------------------------------\nMDP.MDP = mdp;\n\n% Second level\n%--------------------------------------------------------------------------\n\n% Initial states\n%--------------------------------------------------------------------------\nD{1} = ones(3,1); % Target location\nD{2} = zeros(9,1); % Initial locations x policies at lower level ({L1,P1},{L1,P2},{L1,P3},{L2,P1},...)\nD{2}([1 2 3]) = 1;\n\n% Likelihood\n%--------------------------------------------------------------------------\nfor f1 = 1:length(D{1})\n for f2 = 1:length(D{2})\n A{1}(f1,f1,f2) = 1; % Target location 1st level\n \n if f2 < 4\n A{2}(11,f1,f2) = 0.03; % Start location 1st level\n A{2}(12,f1,f2) = 0.12;\n A{2}(1,f1,f2) = 0.7;\n A{2}(2,f1,f2) = 0.12;\n A{2}(3,f1,f2) = 0.03;\n \n elseif f2 <7\n A{2}(3,f1,f2) = 0.03;\n A{2}(4,f1,f2) = 0.12;\n A{2}(5,f1,f2) = 0.7;\n A{2}(6,f1,f2) = 0.12;\n A{2}(7,f1,f2) = 0.03;\n else\n A{2}(7,f1,f2) = 0.03;\n A{2}(8,f1,f2) = 0.12;\n A{2}(9,f1,f2) = 0.7;\n A{2}(10,f1,f2) = 0.12;\n A{2}(11,f1,f2) = 0.03;\n end\n \n A{3}(1,f1,f2) = (rem(f2+2,3) == 0) + 0.5; % Policy 1st level (slight bias towards 'stay still' policy)\n A{3}(2,f1,f2) = (rem(f2+1,3) == 0);\n A{3}(3,f1,f2) = (rem(f2,3) == 0);\n end\nend\n\n\n% Transitions\n%--------------------------------------------------------------------------\nB{1}(:,:,1) = ones(length(D{1}));\nB{1}(:,:,2) = ones(length(D{1})); % Action that causes no change to prevent entering HMM mode\nI = eye(3);\nB{2} = [I, [I(3,:);I(1:2,:)],([I(3,:);I(1:2,:)])']/3;\nB{2} = kron(B{2},ones(3,1));\n\n% Preferences\n%--------------------------------------------------------------------------\nC{1} = zeros(3,1);\nC{2} = zeros(12,1);\nC{3} = zeros(3,1);\n\n% Second level MDP\n%--------------------------------------------------------------------------\nMDP.A = A;\nMDP.B = B;\nMDP.C = C;\nMDP.D = D;\nMDP.T = 4;\n\nMDP.link = [1 0 0;\n 0 1 0];\nMDP.linkE = [0 0 1];\n\nMDP = spm_MDP_check(MDP);\n\nfunction DEM = DEM_MDP_Movement_Disorders_GM\n% hidden states\n%--------------------------------------------------------------------------\nx = [0;-1;0.5;0;0;0]; % shoulder rotation, flexion, elbow flexion (position and velocity)\n\n% and actions\n%--------------------------------------------------------------------------\na = [0;0;0];\n\n% parameters\n%--------------------------------------------------------------------------\nP.kv = 2; % damping\nP.a = a;\nP.b1 = 2;\nP.b2 = 1.5;\n\nM(1).pE = P;\n\n% recognition model\n%==========================================================================\nM(1).E.s = 1/2; % smoothness: default 1/2 [3/4 for lesion]\nM(1).E.n = 4; % order of\nM(1).E.d = 2; % generalised motion\n\n% level 1\n%--------------------------------------------------------------------------\nM(1).f = @(x,v,P) Mf1(x,v,P); % plant dynamics\nM(1).g = @(x,v,P) Mg1(x,v,P); % prediction\n\nM(1).x = x; % hidden states\nM(1).V = exp(4); % error precision (g)[4] [3/8 ?]\nM(1).W = exp(2); % error precision (f) [2]\n\n% level 2:\n%--------------------------------------------------------------------------\nM(2).v = [0;0;0;0;0;0]; % priors (attracting point)\nM(2).V = exp(15);\n\n\n% generative model\n%==========================================================================\n\nG(1).E.s = 1/2; % smoothness: default 1/2\nG(1).E.n = 4; % order of\nG(1).E.d = 2; % generalised motion\n\n% first level\n%--------------------------------------------------------------------------\nG(1).f = @(x,v,a,P) Gf1(x,v,a,P);\nG(1).g = @(x,v,a,P) Gg1(x,v,a,P);\nG(1).x = x; % hidden states\nG(1).V = exp(16);\n% G(1).V = exp([4*ones(1,6) 16*ones(1,6)]); % error precision [16]\nG(1).W = exp(16); % error precision\nG(1).pE = P;\n\n% second level\n%--------------------------------------------------------------------------\nG(2).v = [0;0;0;0;0;0]; % exogenous forces\nG(2).a = spm_vec(a); % action forces\nG(2).V = exp(16);\n\n\nDEM.G = G;\nDEM.M = M;\n\n% Equations for DEM model and process\n%==========================================================================\nfunction f = Mf1(x,v,P)\na = P.b1; % length of upper arm\nb = P.b2; % length of forearm\nc = [-1;-1;-1]; % location of shoulder\n\nf = [x(4:6);MDP_DEM_MD_dthetadt(v(1:3),x,a,b,c) - P.kv*x(4:6)];\n\nfunction g = Mg1(x,v,P)\na = P.b1; % length of upper arm\nb = P.b2; % length of forearm\nc = [-1;-1;-1]; % location of shoulder\n\ng = [x;MDP_DEM_MD_transform(x(1:3),a,b,c);v(4:6)]; % proprioceptive, visual (hand), visual (target)\n\nfunction f = Gf1(x,~,a,P)\nf = [x(4:6);a - P.kv*x(4:6)];\n\nfunction g = Gg1(x,v,~,P)\na = P.b1; % length of upper arm\nb = P.b2; % length of forearm\nc = [-1;-1;-1]; % location of shoulder\n\ng = [x;MDP_DEM_MD_transform(x(1:3),a,b,c);v(4:6)]; % proprioceptive, visual (hand), visual (target)\n\nfunction g = Gg1Reflex(x,v,~,P)\na = P.b1; % length of upper arm\nb = P.b2; % length of forearm\nc = [-1;-1;-1]; % location of shoulder\n\ng = [x + [zeros(3,1);v(1:3)];MDP_DEM_MD_transform(x(1:3),a,b,c);v(4:6)]; % proprioceptive, visual (hand), visual (target)\n\n% Additional routines (plotting/coordinate transforms)\n%==========================================================================\nfunction y = MDP_DEM_MD_transform(x,a,b,c)\n% converts angles to hand position in euclidean space\n% x = angle of shoulder rotation, flexion, elbow flexion\n\ny1 = c + [a*cos(x(2))*cos(x(1));\n a*cos(x(2))*sin(x(1));\n a*sin(x(2))];\n\ny = y1 + [b*cos(x(3)+x(2))*cos(x(1));\n b*cos(x(3)+x(2))*sin(x(1));\n b*sin(x(3)+x(2))];\n\nfunction MDP_DEM_MD_plot_arm(x,a,b,c)\n\ny1 = c + [a*cos(x(2))*cos(x(1));\n a*cos(x(2))*sin(x(1));\n a*sin(x(2))];\n\ny = y1 + [b*cos(x(3)+x(2))*cos(x(1));\n b*cos(x(3)+x(2))*sin(x(1));\n b*sin(x(3)+x(2))];\n\n[S1, S2, S3] = sphere;\n\nsurf(S1*0.2+c(1),S2*0.2+c(2),S3*0.2+c(3),'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7), hold on\nsurf(S1*0.1+y1(1),S2*0.1+y1(2),S3*0.1+y1(3),'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7)\nsurf(S1*0.07+y(1),S2*0.07+y(2),S3*0.07+y(3),'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7)\n\nplot3([c(1) y1(1)],[c(2) y1(2)],[c(3) y1(3)],'LineWidth',6,'Color',[0.1 0.1 0.8])\nplot3([y1(1) y(1)],[y1(2) y(2)],[y1(3) y(3)],'LineWidth',5,'Color',[0.1 0.1 0.8])\nplot3([y1(1) y(1)],[y1(2) y(2)],[y1(3)-0.1 y(3)-0.1],'LineWidth',4,'Color',[0.1 0.1 0.8])\n\nMDP_DEM_Movements_Hand([pi,pi/2 + atan((y(3)-y1(3))/(sqrt((y(1) - y1(1))^2+(y(2) - y1(2))^2))),x(1)],0.25,y)\naxis equal\n\nfunction y = MDP_DEM_MD_dthetadt(v,x,a,b,c)\n\ny1 = c + [a*cos(x(2))*cos(x(1));\n a*cos(x(2))*sin(x(1));\n a*sin(x(2))];\n\ny2 = y1 + [b*cos(x(3)+x(2))*cos(x(1));\n b*cos(x(3)+x(2))*sin(x(1));\n b*sin(x(3)+x(2))];\n\n\ny(1) = [v - y2]'*[-((a*cos(x(2)) + b*cos(x(3)+x(2))*sin(x(1))));\n ((a*cos(x(2)) + b*cos(x(3)+x(2))*cos(x(1))));\n 0];\n\ny(2) = [v - y2]'*[-((a*sin(x(2)) + b*sin(x(3) + x(2)))*cos(x(1)));\n -((a*sin(x(2)) + b*sin(x(3) + x(2))*sin(x(1))));\n (a*cos(x(2)) +(b*cos(x(2) + x(3))))];\n\ny(3) = [v - y2]'*[-(a*sin(x(3) + x(2))*cos(x(1)));\n -(a*sin(x(3)+ x(2))*sin(x(1)));\n (b*cos(x(2) + x(3)))];\n\n\ny = 0.05*y'; % 0.05\n\nfunction MDP_DEM_Movements_Hand(a,s,l)\n% angle - a\n% scale - s\n% location - l\n\n% Carpals (as a single sphere)\n%--------------------------------------------------------------------------\n[X,Y,Z] = sphere;\nRx = makehgtform('xrotate',a(1));\nRy = makehgtform('yrotate',a(2));\nRz = makehgtform('zrotate',a(3));\nT = makehgtform('translate',l);\nS = makehgtform('scale',s);\nq = hgtransform;\n\nLW = 5;\n\n% 2nd finger\n%--------------------------------------------------------------------------\n\n% MCP\n%--------------------------------------------------------------------------\nplot3([0 0],[0 0],[0 1.1],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X, 0.1*Y ,0.1*Z + 1.1,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% PIP\n%--------------------------------------------------------------------------\nplot3([0 0],[0 0.4],[1.1 1.4],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X, 0.1*Y + 0.4 ,0.1*Z + 1.4,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% MIP\n%--------------------------------------------------------------------------\nplot3([0 0],[0.4 0.7],[1.4 1.5],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X, 0.1*Y + 0.7 ,0.1*Z + 1.5,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% DIP\n%--------------------------------------------------------------------------\nplot3([0 0],[0.7 1],[1.5 1.6],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X, 0.1*Y + 1 ,0.1*Z + 1.6,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n\n\n% 3rd finger\n%--------------------------------------------------------------------------\n\n% MCP\n%--------------------------------------------------------------------------\nplot3([-0.1 -0.2],[0 0],[0 1.05],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.2, 0.1*Y ,0.1*Z + 1.05,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% PIP\n%--------------------------------------------------------------------------\nplot3([-0.2 -0.2],[0 0.3],[1.05 1.4],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.2, 0.1*Y + 0.3 ,0.1*Z + 1.4,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% MIP\n%--------------------------------------------------------------------------\nplot3([-0.2 -0.2],[0.3 0.6],[1.4 1.5],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.2, 0.1*Y + 0.6 ,0.1*Z + 1.5,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% DIP\n%--------------------------------------------------------------------------\nplot3([-0.2 -0.2],[0.6 0.9],[1.5 1.6],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.2, 0.1*Y + 0.9 ,0.1*Z + 1.6,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n\n\n% 4th finger\n%--------------------------------------------------------------------------\n\n% MCP\n%--------------------------------------------------------------------------\nplot3([-0.2 -0.4],[0 0],[0 1],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.4, 0.1*Y ,0.1*Z + 1,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% PIP\n%--------------------------------------------------------------------------\nplot3([-0.4 -0.4],[0 0.2],[1 1.4],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.4, 0.1*Y + 0.2 ,0.1*Z + 1.4,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% MIP\n%--------------------------------------------------------------------------\nplot3([-0.4 -0.4],[0.2 0.5],[1.4 1.5],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.4, 0.1*Y + 0.5 ,0.1*Z + 1.5,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% DIP\n%--------------------------------------------------------------------------\nplot3([-0.4 -0.4],[0.5 0.8],[1.5 1.6],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X - 0.4, 0.1*Y + 0.8 ,0.1*Z + 1.6,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n\n% 1st finger\n%--------------------------------------------------------------------------\n\n% MCP\n%--------------------------------------------------------------------------\nplot3([0.1 0.2],[0 0],[0 1],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.2, 0.1*Y ,0.1*Z + 1,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% PIP\n%--------------------------------------------------------------------------\nplot3([0.2 0.2],[0 0.3],[1 1.4],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.2, 0.1*Y + 0.3 ,0.1*Z + 1.4,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% MIP\n%--------------------------------------------------------------------------\nplot3([0.2 0.2],[0.3 0.6],[1.4 1.5],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.2, 0.1*Y + 0.6 ,0.1*Z + 1.5,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% DIP\n%--------------------------------------------------------------------------\nplot3([0.2 0.2],[0.6 0.9],[1.5 1.6],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.2, 0.1*Y + 0.9 ,0.1*Z + 1.6,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n\n% Thumb\n%--------------------------------------------------------------------------\n\n% MCP\n%--------------------------------------------------------------------------\nplot3([0.2 0.5],[0 0.05],[0 0.4],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.5, 0.1*Y +0.05,0.1*Z + 0.4,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% PIP\n%--------------------------------------------------------------------------\nplot3([0.5 0.5],[0.05 0.45],[0.4 0.6],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.5, 0.1*Y +0.45,0.1*Z + 0.6,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n% DIP\n%--------------------------------------------------------------------------\nplot3([0.5 0.45],[0.45 0.6],[0.6 0.62],'b','LineWidth',LW,'Parent',q)\nsurf(0.1*X + 0.45, 0.1*Y +0.6,0.1*Z + 0.62,'Facecolor','b','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7,'Parent',q)\n\nset(q,'Matrix',T*Rz*Rx*Ry*S);\n\nfunction [Q, R, X, Y, Z] = MDP_DEM_Movement_Disorders_Animate(MDP,L)\nopengl('software')\nQ = [];\nR = [];\n\nfor m = 1:length(MDP.mdp)\n for j = 1:length(MDP.mdp(m).dem)\n for i = 2:size(MDP.mdp(m).dem(j).pU.x{1},2)\n MDP_DEM_MD_plot_arm(full(MDP.mdp(m).dem(j).pU.x{1}(1:3,i)),MDP.mdp(m).dem(j).M(1).pE.b1,MDP.mdp(m).dem(j).M(1).pE.b2,[-1;-1;-1]), hold on\n [X,Y,Z] = sphere;\n surf(0.1*X + MDP.mdp(m).dem(j).qU.v{2}(1,i),0.1*Y + MDP.mdp(m).dem(j).qU.v{2}(2,i),0.1*Z + MDP.mdp(m).dem(j).qU.v{2}(3,i),'Facecolor','r','EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7)\n for k = 1:3\n surf(0.2*X + L{(k-1)*4+1}(1),0.2*Y + L{(k-1)*4+1}(2),0.2*Z + L{(k-1)*4+1}(3),'Facecolor',[1 1 1]-MDP.mdp(m).dem(j).Y(9+k,i),'EdgeColor','none','FaceLighting','gouraud','AmbientStrength',0.7)\n end\n axis equal\n light\n drawnow\n hold off\n \n Q(:,end+1) = MDP_DEM_MD_transform(full(MDP.mdp(m).dem(j).pU.x{1}(1:3,i)),MDP.mdp(m).dem(j).M(1).pE.b1,MDP.mdp(m).dem(j).M(1).pE.b2,[-1;-1;-1]);\n end\n R = [R full(MDP.mdp(m).dem(j).pU.x{1}(1:3,:))];\n end\nend", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/MDP_DEM_Mixed_Models_Movement.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.39511626366706515}}
{"text": "%%*****************************************************************\n%% linsysolvefun: Solve H*x = b\n%%\n%% x = linsysolvefun(L,b)\n%% where L contains the triangular factors of H. \n%%*****************************************************************\n%% SDPT3: version 4.0\n%% Copyright (c) 1997 by\n%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************\n \n function x = linsysolvefun(L,b)\n \n x = zeros(size(b)); \n for k=1:size(b,2)\n if strcmp(L.matfct_options,'chol')\n x(L.perm,k) = mextriang(L.R, mextriang(L.R,b(L.perm,k),2) ,1); \n %% x(L.perm,k) = L.R \\ (b(L.perm,k)' / L.R)';\n elseif strcmp(L.matfct_options,'spchol')\n x(L.perm,k) = mextriangsp(L.Rt,mextriangsp(L.R,b(L.perm,k),2),1);\n elseif strcmp(L.matfct_options,'ldl')\n\tx(L.p,k) = ((L.D\\ (L.L \\ b(L.p,k)))' / L.L)';\n elseif strcmp(L.matfct_options,'spldl')\n btmp = b(:,k).*L.s;\n xtmp(L.p,1) = L.Lt\\ (L.D\\ (L.L \\ btmp(L.p)));\n\tx(:,k) = xtmp.*L.s; \n elseif strcmp(L.matfct_options,'lu')\n x(:,k) = L.U \\ (L.L \\ b(L.p,k));\n elseif strcmp(L.matfct_options,'splu') \n\tbtmp = b(:,k)./L.s; \n x(L.q,k) = L.U \\ (L.L \\ (btmp(L.p)));\n end\n end\n%%*************************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/linsysolvefun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.39472208636756034}}
{"text": "function [fusedBox] = fusePETCT(ROIbox_PET,ROIbox_CT,maskBox_PET,CTinv,CTweight,wavelet)\n% -------------------------------------------------------------------------\n% function [fusedBox] = fusePETCT(ROIbox_PET,ROIbox_CT,maskBox_PET,CTinv,CTweight,wavelet)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function fuses the region of interest (ROI) of two registered PET and \n% CT volumes using a technique based on the wavelet transform. See Ref. [2] \n% for more details.\n% -------------------------------------------------------------------------\n% REFERENCE:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n% early prediction of different tumour outcomes in head and neck cancer.\n% The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n% doi:\n% -------------------------------------------------------------------------\n% INPUTS:\n% - ROIbox_PET: 3D array of the smallest box containing the ROI of the PET \n% volume.\n% - ROIbox_CT: 3D array of the smallest box containing the ROI of the CT\n% volume.\n% - maskBox_PET: 3D array of the mask of the smallest box specifying the\n% ROI of the PET volume. Voxels within the ROI are assigned\n% value of 1, voxels outside a value of 0.\n% - CTinv: String specifying if the intensities of the CT volume are\n% inverted prior to fusion with PET. Either 'Inv' for inversion,\n% or 'NoInv' for no inversion.\n% - CTweight: Numerical value specifying the weight of the CT scan in the\n% fusion with PET.\n% - wavelet: String specifying the name of the MATLAB wavelet basis used\n% wavelet basis used in the fusion process.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - fusedBox: 3D array of the smallest box containing the ROI of the fused\n% PET/CT volume.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: July 2015\n% -------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n% \n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\n\n% PET PRE_PROCESSING\nROIbox_PET = sqrt(ROIbox_PET);\n\n\n% RESAMPLING CT VOLUME TO PET IN-PLANE RESOLUTION\nszPET = size(ROIbox_PET);\ntemp=zeros(szPET);\nfor k = 1:szPET(3)\n temp(:,:,k) = imresize(ROIbox_CT(:,:,k),[szPET(1),szPET(2)],'Method','cubic','Antialiasing',true);\nend\nROIbox_CT = temp;\n\n\n% NORMALIZATION (and inversion) OF VOLUMES\nROIOnly_CT = ROIbox_CT;\nROIOnly_PET = ROIbox_PET;\nROIOnly_CT(maskBox_PET==0) = NaN;\nROIOnly_PET(maskBox_PET==0) = NaN;\nminCT = min(ROIOnly_CT(:));\nROIbox_CT = ROIbox_CT - minCT;\nROIOnly_CT = ROIOnly_CT - minCT;\nROIbox_CT = ROIbox_CT./max(ROIOnly_CT(:)).*255;\nif strcmp(CTinv,'Inv')\n ROIbox_CT = 255 - ROIbox_CT;\nend\nminPET = min(ROIOnly_PET(:));\nROIbox_PET = ROIbox_PET - minPET;\nROIOnly_PET = ROIOnly_PET - minPET;\nROIbox_PET = ROIbox_PET./max(ROIOnly_PET(:)).*255;\n\n\n% WAVELET DECOMPOSITION AND FUSION OF COEFFICIENTS\nwdecCT = wavedec3(ROIbox_CT,1,wavelet);\nwdecPET = wavedec3(ROIbox_PET,1,wavelet);\nwdecFUSED = wdecPET;\nszDEC = size(wdecFUSED.dec{1}); % All sub-bands are of the same size\n\n% Fusion of the LLL sub-bands (dec{1})\nb = 1;\nwdecFUSED.dec{b} = (1-CTweight).*wdecPET.dec{b} + CTweight.*wdecCT.dec{b};\n\n% Fusion of the HLL sub-bands (dec{2})\nb = 2;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor k = 1:szDEC(3)\n [~,Gy] = imgradientxy(wdecPET.dec{b}(:,:,k)); tempPET(:,:,k) = sqrt(Gy.^2);\n [~,Gy] = imgradientxy(wdecCT.dec{b}(:,:,k)); tempCT(:,:,k) = sqrt(Gy.^2);\nend\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n% Fusion of the LHL sub-bands (dec{3})\nb = 3;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor k = 1:szDEC(3)\n [Gx,~] = imgradientxy(wdecPET.dec{b}(:,:,k)); tempPET(:,:,k) = sqrt(Gx.^2);\n [Gx,~] = imgradientxy(wdecCT.dec{b}(:,:,k)); tempCT(:,:,k) = sqrt(Gx.^2);\nend\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n% Fusion of the HHL sub-bands (dec{4})\nb = 4;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor k = 1:szDEC(3)\n [Gx,Gy] = imgradientxy(wdecPET.dec{b}(:,:,k)); tempPET(:,:,k) = sqrt(Gx.^2 + Gy.^2);\n [Gx,Gy] = imgradientxy(wdecCT.dec{b}(:,:,k)); tempCT(:,:,k) = sqrt(Gx.^2 + Gy.^2);\nend\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n% Fusion of the LLH sub-bands (dec{5})\nb = 5;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor i = 1:szDEC(1)\n [~,Gy_PET] = imgradientxy(squeeze(wdecPET.dec{b}(i,:,:))'); \n [~,Gy_CT] = imgradientxy(squeeze(wdecCT.dec{b}(i,:,:))');\n for k = 1:szDEC(3)\n tempPET(i,:,k) = sqrt((Gy_PET(k,:)).^2);\n tempCT(i,:,k) = sqrt((Gy_CT(k,:)).^2);\n end\nend\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n% Fusion of the HLH sub-bands (dec{6})\nb = 6;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor k = 1:szDEC(3)\n [~,Gy] = imgradientxy(wdecPET.dec{b}(:,:,k)); tempPET(:,:,k) = Gy.^2;\n [~,Gy] = imgradientxy(wdecCT.dec{b}(:,:,k)); tempCT(:,:,k) = Gy.^2;\nend\nfor i = 1:szDEC(1)\n [~,Gy_PET] = imgradientxy(squeeze(wdecPET.dec{b}(i,:,:))'); \n [~,Gy_CT] = imgradientxy(squeeze(wdecCT.dec{b}(i,:,:))');\n for k = 1:szDEC(3)\n tempPET(i,:,k) = tempPET(i,:,k) + (Gy_PET(k,:)).^2;\n tempCT(i,:,k) = tempCT(i,:,k) + (Gy_CT(k,:)).^2;\n end\nend\ntempPET = sqrt(tempPET); tempCT = sqrt(tempCT);\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n% Fusion of the LHH sub-bands (dec{7})\nb = 7;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor k = 1:szDEC(3)\n [Gx,~] = imgradientxy(wdecPET.dec{b}(:,:,k)); tempPET(:,:,k) = Gx.^2;\n [Gx,~] = imgradientxy(wdecCT.dec{b}(:,:,k)); tempCT(:,:,k) = Gx.^2;\nend\nfor i = 1:szDEC(1)\n [~,Gy_PET] = imgradientxy(squeeze(wdecPET.dec{b}(i,:,:))'); \n [~,Gy_CT] = imgradientxy(squeeze(wdecCT.dec{b}(i,:,:))');\n for k = 1:szDEC(3)\n tempPET(i,:,k) = tempPET(i,:,k) + (Gy_PET(k,:)).^2;\n tempCT(i,:,k) = tempCT(i,:,k) + (Gy_CT(k,:)).^2;\n end\nend\ntempPET = sqrt(tempPET); tempCT = sqrt(tempCT);\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n% Fusion of the HHH sub-bands (dec{8})\nb = 8;\ntempPET = zeros(szDEC);\ntempCT = zeros(szDEC);\nfor k = 1:szDEC(3)\n [Gx,Gy] = imgradientxy(wdecPET.dec{b}(:,:,k)); tempPET(:,:,k) = Gx.^2 + Gy.^2;\n [Gx,Gy] = imgradientxy(wdecCT.dec{b}(:,:,k)); tempCT(:,:,k) = Gx.^2 + Gy.^2;\nend\nfor i = 1:szDEC(1)\n [~,Gy_PET] = imgradientxy(squeeze(wdecPET.dec{b}(i,:,:))'); \n [~,Gy_CT] = imgradientxy(squeeze(wdecCT.dec{b}(i,:,:))');\n for k = 1:szDEC(3)\n tempPET(i,:,k) = tempPET(i,:,k) + (Gy_PET(k,:)).^2;\n tempCT(i,:,k) = tempCT(i,:,k) + (Gy_CT(k,:)).^2;\n end\nend\ntempPET = sqrt(tempPET); tempCT = sqrt(tempCT);\nwdecFUSED.dec{b}(tempCT > tempPET) = wdecCT.dec{b}(tempCT > tempPET);\n\n\n% WAVELET RECONSTRUCTION\nfusedBox = waverec3(wdecFUSED);\nfusedOnly = fusedBox;\nfusedOnly(maskBox_PET==0) = NaN;\nminFus = min(fusedOnly(:));\nfusedBox = fusedBox - minFus;\nfusedOnly = fusedOnly - minFus;\nfusedBox = fusedBox./max(fusedOnly(:)).*255;\n\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FUSION_PET-CT/fusePETCT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.39470387780105043}}
{"text": "function [fMc, mcCalculator] = calc_Mc(mCatalog, calcMethod, binInterval, mcCorrectionFactor)\n % CALC_MC Calculates the magnitude of completeness for a given catalog\n %\n % fMc = CALC_MC(mCatalog, nMethod, binInterval, mcCorrectionFactor)\n % [fMc, mc_calculator] = CALC_MC(...) returns a function handle to the calculation\n % method, so it can be reused in heavy loops. MC_CALCULATOR has the form:\n % fMc = MY_CALCULATOR(catalog, bins, correction);\n %\n % --------------------------------------------------------------------\n %\n %\n % Input parameters:\n % mCatalog Earthquake catalog for determing the magnitude of completeness\n % calcMethod Method to determine the magnitude of completeness\n % see: McMethods for a list of valid values\n % binInterval Binning of catalog's magnitudes (default 0.1)\n % mcCorrectionFactor Correction term to be added to fMc (default 0)\n %\n % Output parameters:\n % fMc Magnitude of completeness\n % mc_calculator\n %\n %\n % Copyright (C) 2004 by Danijel Schorlemmer, Jochen Woessner\n \n % This program is free software; you can redistribute it and/or modify\n % it under the terms of the GNU General Public License as published by\n % the Free Software Foundation; either version 2 of the License, or\n % (at your option) any later version.\n %\n % This program is distributed in the hope that it will be useful,\n % but WITHOUT ANY WARRANTY; without even the implied warranty of\n % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n % GNU General Public License for more details.\n %\n % You should have received a copy of the GNU General Public License\n % along with this program; if not, write to the\n % Free Software Foundation, Inc.,\n % 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n \n % Magnitude binning\n if ~exist('binInterval', 'var') || isempty(binInterval)\n binInterval = 0.1;\n end\n if ~isa(calcMethod,'McMethods')\n error('Expected an actual method (McMethods) but received something else.\\n See McMethods');\n end\n % Correction\n if ~exist('mcCorrectionFactor', 'var') || isempty(mcCorrectionFactor)\n mcCorrectionFactor = 0;\n end\n useNumeric = isnumeric(mCatalog) || (ischarlike(mCatalog) && mCatalog == \"AsMagnitudes\");\n if useNumeric\n switch calcMethod\n case McMethods.MaxCurvature\n methodFun = @calc_McMaxCurvature;\n \n case McMethods.FixedMc\n methodFun = @min;\n \n case McMethods.Mc90\n methodFun = @(C)method_mc90(C,binInterval);\n \n case McMethods.Mc95\n methodFun = @(C)method_mc95(C,binInterval);\n \n case McMethods.McBestCombo\n methodFun = @(C)method_bestcombo(C,binInterval);\n \n case McMethods.McEMR\n error('this only works with full catalogs')\n %methodFun = @(C)calc_McEMR(C,binInterval); %requires catalog Magnitude AND Date\n \n case McMethods.McDueB_ShiBolt\n methodFun = @(C)calc_Mcdueb(C, binInterval);\n \n case McMethods.McDueB_Bootstrap\n nSample = 500;\n nWindowSize = 5;\n nMinEvents = 50;\n methodFun = @(C) calc_McduebBst(C, binInterval, nWindowSize, nMinEvents,nSample);\n \n case McMethods.McDueB_Cao\n methodFun = @(C, ~)calc_McduebCao(C);\n \n otherwise\n error('unknown Mc method');\n end\n else % catalog object\n switch calcMethod\n case McMethods.MaxCurvature\n methodFun = @(C)calc_McMaxCurvature(C.Magnitude);\n \n case McMethods.FixedMc\n methodFun = @(C) min(C.Magnitude);\n \n case McMethods.Mc90\n methodFun = @(C)method_mc90(C.Magnitude,binInterval);\n \n case McMethods.Mc95\n methodFun = @(C)method_mc95(C.Magnitude,binInterval);\n \n case McMethods.McBestCombo\n methodFun = @(C)method_bestcombo(C.Magnitude,binInterval);\n \n case McMethods.McEMR\n methodFun = @(C)calc_McEMR(C,binInterval); %requires catalog Magnitude AND Date\n \n case McMethods.McDueB_ShiBolt\n methodFun = @(C)calc_Mcdueb(C.Magnitude, binInterval);\n \n case McMethods.McDueB_Bootstrap\n nSample = 500;\n nWindowSize = 5;\n nMinEvents = 50;\n methodFun = @(C) calc_McduebBst(C.Magnitude, binInterval, nWindowSize, nMinEvents,nSample);\n \n case McMethods.McDueB_Cao\n methodFun = @(C, ~)calc_McduebCao(C.Magnitude);\n \n otherwise\n error('unknown Mc method');\n end\n end\n \n % lock the method into this calculation\n mcCalculator = @(C) do_calculation(methodFun, C, mcCorrectionFactor);\n\n if ~isempty(mCatalog)\n % do the calculation\n fMc = mcCalculator(mCatalog);\n else\n fMc = [];\n end\n \nend\n\nfunction fMc = do_calculation(methodFun, mCatalog, mcCorrectionFactor)\n if isempty(mCatalog) || ischarlike(mCatalog)\n fMc = nan;\n return\n end\n \n fMc = methodFun(mCatalog);\n \n % Check fMc\n if isempty(fMc)\n fMc = nan;\n end\n \n % Apply correction\n fMc = fMc + mcCorrectionFactor;\nend\n\n% functions to return that all have same signature\nfunction fMc = method_mc90(mags, binInterval)\n [~, ~, fMc] = calc_McBest(mags, binInterval);\nend\n\nfunction fMc = method_mc95(mags, binInterval)\n [~, fMc] = calc_McBest(mags, binInterval);\nend\n\nfunction fMc = method_bestcombo(mags, binInterval)\n [~, Mc95, Mc90] = calc_McBest(mags, binInterval);\n if ~isnan(Mc95)\n fMc = Mc95;\n elseif ~isnan(Mc90)\n fMc = Mc90;\n else\n fMc = calc_McMaxCurvature(mags);\n end\nend\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/danijel/calc/calc_Mc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3946045468185987}}
{"text": "function [dpsi,deps]=nut_iau1980(t,f)\n\nAS2R=pi/180/3600;\nnut=[ 0, 0, 0, 0, 1, -6798.4, -171996, -174.2, 92025, 8.9;\n 0, 0, 2, -2, 2, 182.6, -13187, -1.6, 5736, -3.1;\n 0, 0, 2, 0, 2, 13.7, -2274, -0.2, 977, -0.5;\n 0, 0, 0, 0, 2, -3399.2, 2062, 0.2, -895, 0.5;\n 0, -1, 0, 0, 0, -365.3, -1426, 3.4, 54, -0.1;\n 1, 0, 0, 0, 0, 27.6, 712, 0.1, -7, 0.0;\n 0, 1, 2, -2, 2, 121.7, -517, 1.2, 224, -0.6;\n 0, 0, 2, 0, 1, 13.6, -386, -0.4, 200, 0.0;\n 1, 0, 2, 0, 2, 9.1, -301, 0.0, 129, -0.1;\n 0, -1, 2, -2, 2, 365.2, 217, -0.5, -95, 0.3;\n -1, 0, 0, 2, 0, 31.8, 158, 0.0, -1, 0.0;\n 0, 0, 2, -2, 1, 177.8, 129, 0.1, -70, 0.0;\n -1, 0, 2, 0, 2, 27.1, 123, 0.0, -53, 0.0;\n 1, 0, 0, 0, 1, 27.7, 63, 0.1, -33, 0.0;\n 0, 0, 0, 2, 0, 14.8, 63, 0.0, -2, 0.0;\n -1, 0, 2, 2, 2, 9.6, -59, 0.0, 26, 0.0;\n -1, 0, 0, 0, 1, -27.4, -58, -0.1, 32, 0.0;\n 1, 0, 2, 0, 1, 9.1, -51, 0.0, 27, 0.0;\n -2, 0, 0, 2, 0, -205.9, -48, 0.0, 1, 0.0;\n -2, 0, 2, 0, 1, 1305.5, 46, 0.0, -24, 0.0;\n 0, 0, 2, 2, 2, 7.1, -38, 0.0, 16, 0.0;\n 2, 0, 2, 0, 2, 6.9, -31, 0.0, 13, 0.0;\n 2, 0, 0, 0, 0, 13.8, 29, 0.0, -1, 0.0;\n 1, 0, 2, -2, 2, 23.9, 29, 0.0, -12, 0.0;\n 0, 0, 2, 0, 0, 13.6, 26, 0.0, -1, 0.0;\n 0, 0, 2, -2, 0, 173.3, -22, 0.0, 0, 0.0;\n -1, 0, 2, 0, 1, 27.0, 21, 0.0, -10, 0.0;\n 0, 2, 0, 0, 0, 182.6, 17, -0.1, 0, 0.0;\n 0, 2, 2, -2, 2, 91.3, -16, 0.1, 7, 0.0;\n -1, 0, 0, 2, 1, 32.0, 16, 0.0, -8, 0.0;\n 0, 1, 0, 0, 1, 386.0, -15, 0.0, 9, 0.0;\n 1, 0, 0, -2, 1, -31.7, -13, 0.0, 7, 0.0;\n 0, -1, 0, 0, 1, -346.6, -12, 0.0, 6, 0.0;\n 2, 0, -2, 0, 0, -1095.2, 11, 0.0, 0, 0.0;\n -1, 0, 2, 2, 1, 9.5, -10, 0.0, 5, 0.0;\n 1, 0, 2, 2, 2, 5.6, -8, 0.0, 3, 0.0;\n 0, -1, 2, 0, 2, 14.2, -7, 0.0, 3, 0.0;\n 0, 0, 2, 2, 1, 7.1, -7, 0.0, 3, 0.0;\n 1, 1, 0, -2, 0, -34.8, -7, 0.0, 0, 0.0;\n 0, 1, 2, 0, 2, 13.2, 7, 0.0, -3, 0.0;\n -2, 0, 0, 2, 1, -199.8, -6, 0.0, 3, 0.0;\n 0, 0, 0, 2, 1, 14.8, -6, 0.0, 3, 0.0;\n 2, 0, 2, -2, 2, 12.8, 6, 0.0, -3, 0.0;\n 1, 0, 0, 2, 0, 9.6, 6, 0.0, 0, 0.0;\n 1, 0, 2, -2, 1, 23.9, 6, 0.0, -3, 0.0;\n 0, 0, 0, -2, 1, -14.7, -5, 0.0, 3, 0.0;\n 0, -1, 2, -2, 1, 346.6, -5, 0.0, 3, 0.0;\n 2, 0, 2, 0, 1, 6.9, -5, 0.0, 3, 0.0;\n 1, -1, 0, 0, 0, 29.8, 5, 0.0, 0, 0.0;\n 1, 0, 0, -1, 0, 411.8, -4, 0.0, 0, 0.0;\n 0, 0, 0, 1, 0, 29.5, -4, 0.0, 0, 0.0;\n 0, 1, 0, -2, 0, -15.4, -4, 0.0, 0, 0.0;\n 1, 0, -2, 0, 0, -26.9, 4, 0.0, 0, 0.0;\n 2, 0, 0, -2, 1, 212.3, 4, 0.0, -2, 0.0;\n 0, 1, 2, -2, 1, 119.6, 4, 0.0, -2, 0.0;\n 1, 1, 0, 0, 0, 25.6, -3, 0.0, 0, 0.0;\n 1, -1, 0, -1, 0, -3232.9, -3, 0.0, 0, 0.0;\n -1, -1, 2, 2, 2, 9.8, -3, 0.0, 1, 0.0;\n 0, -1, 2, 2, 2, 7.2, -3, 0.0, 1, 0.0;\n 1, -1, 2, 0, 2, 9.4, -3, 0.0, 1, 0.0;\n 3, 0, 2, 0, 2, 5.5, -3, 0.0, 1, 0.0;\n -2, 0, 2, 0, 2, 1615.7, -3, 0.0, 1, 0.0;\n 1, 0, 2, 0, 0, 9.1, 3, 0.0, 0, 0.0;\n -1, 0, 2, 4, 2, 5.8, -2, 0.0, 1, 0.0;\n 1, 0, 0, 0, 2, 27.8, -2, 0.0, 1, 0.0;\n -1, 0, 2, -2, 1, -32.6, -2, 0.0, 1, 0.0;\n 0, -2, 2, -2, 1, 6786.3, -2, 0.0, 1, 0.0;\n -2, 0, 0, 0, 1, -13.7, -2, 0.0, 1, 0.0;\n 2, 0, 0, 0, 1, 13.8, 2, 0.0, -1, 0.0;\n 3, 0, 0, 0, 0, 9.2, 2, 0.0, 0, 0.0;\n 1, 1, 2, 0, 2, 8.9, 2, 0.0, -1, 0.0;\n 0, 0, 2, 1, 2, 9.3, 2, 0.0, -1, 0.0;\n 1, 0, 0, 2, 1, 9.6, -1, 0.0, 0, 0.0;\n 1, 0, 2, 2, 1, 5.6, -1, 0.0, 1, 0.0;\n 1, 1, 0, -2, 1, -34.7, -1, 0.0, 0, 0.0;\n 0, 1, 0, 2, 0, 14.2, -1, 0.0, 0, 0.0;\n 0, 1, 2, -2, 0, 117.5, -1, 0.0, 0, 0.0;\n 0, 1, -2, 2, 0, -329.8, -1, 0.0, 0, 0.0;\n 1, 0, -2, 2, 0, 23.8, -1, 0.0, 0, 0.0;\n 1, 0, -2, -2, 0, -9.5, -1, 0.0, 0, 0.0;\n 1, 0, 2, -2, 0, 32.8, -1, 0.0, 0, 0.0;\n 1, 0, 0, -4, 0, -10.1, -1, 0.0, 0, 0.0;\n 2, 0, 0, -4, 0, -15.9, -1, 0.0, 0, 0.0;\n 0, 0, 2, 4, 2, 4.8, -1, 0.0, 0, 0.0;\n 0, 0, 2, -1, 2, 25.4, -1, 0.0, 0, 0.0;\n -2, 0, 2, 4, 2, 7.3, -1, 0.0, 1, 0.0;\n 2, 0, 2, 2, 2, 4.7, -1, 0.0, 0, 0.0;\n 0, -1, 2, 0, 1, 14.2, -1, 0.0, 0, 0.0;\n 0, 0, -2, 0, 1, -13.6, -1, 0.0, 0, 0.0;\n 0, 0, 4, -2, 2, 12.7, 1, 0.0, 0, 0.0;\n 0, 1, 0, 0, 2, 409.2, 1, 0.0, 0, 0.0;\n 1, 1, 2, -2, 2, 22.5, 1, 0.0, -1, 0.0;\n 3, 0, 2, -2, 2, 8.7, 1, 0.0, 0, 0.0;\n -2, 0, 2, 2, 2, 14.6, 1, 0.0, -1, 0.0;\n -1, 0, 0, 0, 2, -27.3, 1, 0.0, -1, 0.0;\n 0, 0, -2, 2, 1, -169.0, 1, 0.0, 0, 0.0;\n 0, 1, 2, 0, 1, 13.1, 1, 0.0, 0, 0.0;\n -1, 0, 4, 0, 2, 9.1, 1, 0.0, 0, 0.0;\n 2, 1, 0, -2, 0, 131.7, 1, 0.0, 0, 0.0;\n 2, 0, 0, 2, 0, 7.1, 1, 0.0, 0, 0.0;\n 2, 0, 2, -2, 1, 12.8, 1, 0.0, -1, 0.0;\n 2, 0, -2, 0, 1, -943.2, 1, 0.0, 0, 0.0;\n 1, -1, 0, -2, 0, -29.3, 1, 0.0, 0, 0.0;\n -1, 0, 0, 1, 1, -388.3, 1, 0.0, 0, 0.0;\n -1, -1, 0, 2, 1, 35.0, 1, 0.0, 0, 0.0;\n 0, 1, 0, 1, 0, 27.3, 1, 0.0, 0, 0.0];\n\ndpsi=0;\ndeps=0;\nfor i=1:106\n ang=0;\n for j=1:5\n ang=ang+nut(i,j)*f(j);\n end\n dpsi=dpsi+(nut(i,7)+nut(i,8)*t)*sin(ang);\n deps=deps+(nut(i,9)+nut(i,10)*t)*cos(ang);\nend\ndpsi=dpsi*1e-4*AS2R;\ndeps=deps*1e-4*AS2R;\n\nreturn\n\n", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/nut_iau1980.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3945617393455975}}
{"text": "function [Q,R,S,U,P] = spm_MDP(MDP)\n% solves the active inference problem for Markov decision processes\n% FROMAT [Q,R,S,U,P] = spm_MDP(MDP)\n%\n% MDP.T - process depth (the horizon)\n% MDP.S(N,1) - initial state\n% MDP.B{M}(N,N) - transition probabilities among hidden states (priors)\n% MDP.C(N,1) - terminal cost probabilities (prior N over hidden states)\n% MDP.D(M,1) - control probabilities (prior over M control states)\n%\n% optional:\n%\n% MDP.W - log-precision of beliefs about transitions (default: 1)\n% MDP.G{M}(N,N) - transition probabilities used to generate outcomes\n% (default: the prior transition probabilities)\n% MDP.A(N,N) - Likelihood of outcomes given hidden states\n% (default: an identity mapping from states to outcomes)\n% MDP.B{T,M}(N,N) - transition probabilities for each time point\n% MDP.G{T,M}(N,N) - transition probabilities for each time point\n% (default: MDP.B{T,M} = MDP.B{M})\n%\n% MDP.plot - swtich to suppress graphics\n%\n% produces:\n%\n% Q(N,K,T) - an array of conditional (posterior) expectations over N hidden\n% states and time 1,...,T at time 1,...,K\n% R(M,K,T) - an array of conditional expectations over M control\n% states and time 1,...,T at time 1,...,K\n% S(N,T) - a sparse matrix of ones, encoding the state at time 1,...,T\n% U(M,T) - a sparse matrix of ones, encoding the action at time 1,...,T\n% P(M,T) - probabaility of emitting action 1,...,M at time 1,...,T\n%\n% This routine provides solutions of active inference (minimisation of\n% variational free energy)using a generative model based upon a Markov\n% decision process. This model and inference scheme is formulated\n% in discrete space and time. This means that the generative model (and\n% process) are finite state machines or hidden Markov models whose\n% dynamics are given by transition probabilities among states. For\n% simplicity, we assume an isomorphism between hidden states and outcomes,\n% where the likelihood corresponds to a particular outcome conditioned upon\n% hidden states. Similarly, for simplicity, this routine assumes that action\n% and hidden controls are isomorphic. If the dynamics of transition\n% probabilities of the true process are not provided, this routine will use\n% the equivalent probabilities from the generative model.\n%\n% The transition probabilities are a cell array of probability transition\n% matrices corresponding to each (discrete) the level of the control state.\n%\n% Mote that the conditional expectations are functions of time but also\n% contain expectations about fictive states over time at each time point.\n% To create time dependent transition probabilities, one can specify a\n% function in place of the transition probabilities under different levels\n% of control.\n%\n% partially observed Markov decision processes can be modelled by\n% specifying a likelihood (as part of a generative model) and absorbing any\n% probabilistic mapping between (isomorphic) hidden states and outcomes\n% into the transition probabilities G.\n%\n% See also spm_MDP_game\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_MDP.m 6061 2014-06-21 09:02:42Z karl $\n\n% set up and preliminaries\n%==========================================================================\n\n% plotting and precision defaults\n%--------------------------------------------------------------------------\ntry PLOT = MDP.plot; catch, PLOT = 1; end\ntry lambda = MDP.lambda; catch, lambda = 1; end\ntry W = MDP.W; catch, W = 1; end\n\n% get figure\n%--------------------------------------------------------------------------\nif PLOT, spm_figure('GetWin','MDP'); clf, end\n\n% generative model and initial states\n%--------------------------------------------------------------------------\nP0 = exp(-32); % smallest probability\nT = MDP.T; % process depth (the horizon)\nNs = size(MDP.B{1},1); % number of hidden states\nNb = size(MDP.B,1); % number of time-dependent probabilities\nNu = size(MDP.B,2); % number of hidden controls\n\n\n% likelihood model (for a partially observed MDP implicit in G)\n%--------------------------------------------------------------------------\ntry\n A = MDP.A + P0;\ncatch\n A = speye(Ns,Ns) + P0;\nend\nA = A*diag(1./sum(A));\n\n% transition probabilities (priors)\n%--------------------------------------------------------------------------\nfor i = 1:T\n for j = 1:Nu\n if i == 1 || Nb == T\n B{i,j} = MDP.B{i,j} + P0;\n H{i,j} = B{i,j}';\n B{i,j} = B{i,j}*diag(1./sum(B{i,j}));\n H{i,j} = H{i,j}*diag(1./sum(H{i,j}));\n lnB{i,j} = log(B{i,j})*W;\n lnH{i,j} = log(H{i,j})*W;\n else\n B{i,j} = B{1,j};\n lnB{i,j} = lnB{1,j};\n lnH{i,j} = lnH{1,j};\n end\n end\nend\n\n% terminal cost probabilities (priors)\n%--------------------------------------------------------------------------\ntry\n C = spm_vec(MDP.C) + P0;\ncatch\n C = ones(Ns,1);\nend\n\n% control probabilities (priors)\n%--------------------------------------------------------------------------\ntry\n D = spm_vec(MDP.D) + P0;\ncatch\n D = ones(Nu,1);\nend\n\n% state probabilities (priors)\n%--------------------------------------------------------------------------\ntry\n E = spm_vec(MDP.E) + P0;\ncatch\n E = ones(Ns,1);\nend\n\nC = C/sum(C);\nD = D/sum(D);\nE = E/sum(E);\nlnA = log(A);\nlnD = log(D)*W;\nlnE = log(E)*W;\n\n% generative process (assume the true process is the same as the model)\n%--------------------------------------------------------------------------\ntry\n G = MDP.G;\ncatch\n G = MDP.B;\nend\nNg = size(G,1);\nfor i = 1:T\n for j = 1:Nu\n if i == 1 || Ng == T\n G{i,j} = G{i,j}*diag(1./sum(G{i,j}));\n else\n G{i,j} = G{1,j};\n end\n end\nend\n\n\n% effector action (e) and sufficient statistics of proposal density\n%--------------------------------------------------------------------------\na = zeros(Ns,T); % state probability\nb = ones(Nu,T); % control probability\na(:,T) = C; % final state\nb = b*diag(1./sum(b));\n\n% posterior expectations (states Q, control R)\n%--------------------------------------------------------------------------\nQ(:,1,:) = a;\nR(:,1,:) = b;\n\n% initial state and posterior (states Q, control R) and action (E)\n%--------------------------------------------------------------------------\ns = find(spm_vec(MDP.S));\nS = sparse(s,1,1,Ns,T);\nU = sparse(Nu,T);\n\n% solve\n%==========================================================================\nfor k = 1:(T - 1)\n \n % forward and backward passes at this time point\n %----------------------------------------------------------------------\n for i = 1:8\n for t = (T - 1):-1:k\n \n % get data likelihood if available at this time\n %--------------------------------------------------------------\n if t > k\n at = lnE;\n else\n at = lnA'*S(:,t) + lnE;\n end\n \n % and accumulate empirical priors\n %--------------------------------------------------------------\n for j = 1:Nu\n if t > 1\n at = at + b(j,t - 1) *lnH{t,j}'*a(:,t - 1);\n end\n at = at + b(j,t ) *lnB{t,j}'*a(:,t + 1);\n bt(j,1) = lnD(j) + a(:,t )'*lnB{t,j}'*a(:,t + 1);\n end\n \n % update sufficient statistics of hidden states and control\n %--------------------------------------------------------------\n a(:,t) = spm_softmax(at);\n b(:,t) = spm_softmax(bt);\n \n % graphics to inspect update scheme\n %==============================================================\n if PLOT > 2\n \n % posterior beliefs about hidden states\n %----------------------------------------------------------\n spm_plot_states(a,b)\n \n % pause if requested\n %----------------------------------------------------------\n if PLOT > 3, pause, end\n \n end\n \n \n end\n \n % graphics to inspect update scheme\n %==================================================================\n if PLOT > 1\n \n % posterior beliefs about hidden states\n %--------------------------------------------------------------\n spm_plot_states(a,b)\n \n end\n end\n \n \n % sampling of next state (outcome)\n %======================================================================\n for i = 1:Nu\n F(i,1) = B{k,i}(:,s)'*lnA*a(:,k + 1);\n end\n \n % next action (the action and minimises expected free energy)\n %----------------------------------------------------------------------\n Pu = spm_softmax(F,lambda);\n i = find(rand < cumsum(Pu),1);\n \n % next state (assuming G mediates uncertainty modelled the likelihood)\n %----------------------------------------------------------------------\n Ps = spm_softmax(G{k,i}(:,s),lambda);\n s = find(rand < cumsum(Ps),1);\n \n \n % save action, state and posterior expectations (states Q, control R)\n %----------------------------------------------------------------------\n P(:,k) = Pu;\n Q(:,k,:) = a;\n R(:,k,:) = b;\n S(s,k + 1) = 1;\n U(i,k) = 1;\n \n \n % plot\n %======================================================================\n if PLOT > 0\n \n % posterior beliefs about hidden states\n %------------------------------------------------------------------\n spm_plot_states(a,b)\n \n % states sampled (outcome)\n %------------------------------------------------------------------\n subplot(2,2,3)\n if size(S,1) > 512\n spy(S,16)\n else\n imagesc(1 - S)\n end\n axis square\n title('Sampled state','FontSize',16)\n xlabel('time','FontSize',12)\n ylabel('action','FontSize',12)\n \n % action sampled (selected)\n %------------------------------------------------------------------\n subplot(2,2,4)\n if size(U,1) > 512\n spy(U,16)\n else\n imagesc(1 - U)\n end\n axis square\n title('Selected action','FontSize',16)\n xlabel('time','FontSize',12)\n ylabel('action','FontSize',12)\n drawnow\n \n end\n \nend\n\n\nfunction spm_plot_states(a,b)\n\n% posterior beliefs about hidden states\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nif size(a,1) > 512\n spy(a > 1/32,16)\nelse\n imagesc(1 - a)\nend\naxis square\ntitle('Expected hidden states','FontSize',16)\nxlabel('time','FontSize',12)\nylabel('hidden state','FontSize',12)\n\n% posterior beliefs about control states\n%--------------------------------------------------------------------------\nsubplot(2,2,2)\nif size(b,1) > 512\n spy(b > 1/8,16)\nelse\n imagesc(1 - b)\nend\naxis square\ntitle('Expected control states','FontSize',16)\nxlabel('time','FontSize',12)\nylabel('control state','FontSize',12)\ndrawnow\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/spm_MDP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.39438844747693524}}
{"text": "% Using A Binary Sensor Mask Example\n%\n% This example demonstrates how to use a binary sensor mask for the\n% detection of the pressure field generated by an initial pressure\n% distribution within a two-dimensional homogeneous propagation medium. It\n% builds on the Homogeneous Propagation Medium Example. \n%\n% author: Bradley Treeby\n% date: 29th June 2009\n% last update: 22nd September 2012\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\nclear all;\n\n% =========================================================================\n% SIMULATION\n% =========================================================================\n\n% create the computational grid\nNx = 128; % number of grid points in the x (row) direction\nNy = 128; % number of grid points in the y (column) direction\ndx = 0.1e-3; % grid point spacing in the x direction [m]\ndy = 0.1e-3; % grid point spacing in the y direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500; \t% [m/s]\nmedium.alpha_coeff = 0.75; % [dB/(MHz^y cm)]\nmedium.alpha_power = 1.5;\n\n% create initial pressure distribution using makeDisc\ndisc_magnitude = 5; % [Pa]\ndisc_x_pos = 50; % [grid points]\ndisc_y_pos = 50; % [grid points]\ndisc_radius = 8; % [grid points]\ndisc_1 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\ndisc_magnitude = 3; % [Pa]\ndisc_x_pos = 80; % [grid points]\ndisc_y_pos = 60; % [grid points]\ndisc_radius = 5; % [grid points]\ndisc_2 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);\n\nsource.p0 = disc_1 + disc_2;\n\n% define a binary sensor mask\nsensor_x_pos = Nx/2; % [grid points]\nsensor_y_pos = Ny/2; % [grid points]\nsensor_radius = Nx/2 - 22; % [grid points]\nsensor_arc_angle = 3*pi/2; % [radians]\nsensor.mask = makeCircle(Nx, Ny, sensor_x_pos, sensor_y_pos, sensor_radius, sensor_arc_angle);\n\n% run the simulation\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor);\n\n% reorder the simulation data\nsensor_data_reordered = reorderSensorData(kgrid, sensor, sensor_data);\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the initial pressure and sensor distribution\nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, source.p0 + disc_magnitude*sensor.mask, [-1 1]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\n\n% plot the simulated sensor data\nfigure;\nimagesc(sensor_data, [-1, 1]);\ncolormap(getColorMap);\nylabel('Sensor Position');\nxlabel('Time Step');\ncolorbar;\n\n% plot the re-ordered sensor data\nfigure;\nimagesc(sensor_data_reordered, [-1, 1]);\ncolormap(getColorMap);\nylabel('Sensor Position');\nxlabel('Time Step');\ncolorbar;", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_ivp_binary_sensor_mask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3941831605627113}}
{"text": "% sensors.m\n% Compute the output of rate gyros, accelerometers, and pressure sensors\n%\n% Revised:\n% 3/5/2010 - RB \n% 5/14/2010 - RB\n\nfunction y = sensors(uu, P)\n\n % relabel the inputs\n% pn = uu(1);\n% pe = uu(2);\n pd = uu(3);\n% u = uu(4);\n% v = uu(5);\n% w = uu(6);\n phi = uu(7);\n theta = uu(8);\n% psi = uu(9);\n p = uu(10);\n q = uu(11);\n r = uu(12);\n F_x = uu(13);\n F_y = uu(14);\n F_z = uu(15);\n% M_l = uu(16);\n% M_m = uu(17);\n% M_n = uu(18);\n Va = uu(19);\n% alpha = uu(20);\n% beta = uu(21);\n% wn = uu(22);\n% we = uu(23);\n% wd = uu(24);\n \n % simulate rate gyros (units are rad/sec)\n y_gyro_x = p + P.sigma_gyro * randn;\n y_gyro_y = q + P.sigma_gyro * randn;\n y_gyro_z = r + P.sigma_gyro * randn;\n\n % simulate accelerometers (units of g)\n y_accel_x = F_x / P.mass / P.gravity + sin(theta) + P.sigma_accel * randn;\n y_accel_y = F_y / P.mass / P.gravity - cos(theta) * sin(phi) + P.sigma_accel * randn;\n y_accel_z = F_z / P.mass / P.gravity - cos(theta) * cos(phi) + P.sigma_accel * randn;\n\n % simulate pressure sensors\n y_static_pres = P.rho * P.gravity * (-pd) + P.beta_abs_pres + P.sigma_abs_pres * randn;\n y_diff_pres = P.rho * Va^2 / 2 + P.beta_diff_pres + P.sigma_diff_pres * randn;\n\n % construct total output\n y = [...\n y_gyro_x;...\n y_gyro_y;...\n y_gyro_z;...\n y_accel_x;...\n y_accel_y;...\n y_accel_z;...\n y_static_pres;...\n y_diff_pres;...\n ];\n\nend\n\n\n\n", "meta": {"author": "chengji253", "repo": "Multiple-fixed-wing-UAVs-flight-simulation-platform", "sha": "7c1fa69d9033355461c0753c2a7408a9bcf1e3e7", "save_path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform", "path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform/Multiple-fixed-wing-UAVs-flight-simulation-platform-7c1fa69d9033355461c0753c2a7408a9bcf1e3e7/platform_code/uavA1/sensors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3940283072213606}}
{"text": "function lik = lik_t(varargin)\n%LIK_T Create a Student-t likelihood structure \n%\n% Description\n% LIK = LIK_T('PARAM1',VALUE1,'PARAM2,VALUE2,...)\n% creates Student-t likelihood structure in which the named\n% parameters have the specified values. Any unspecified\n% parameters are set to default values.\n%\n% LIK = LIK_T(LIK,'PARAM1',VALUE1,'PARAM2,VALUE2,...)\n% modify a likelihood structure with the named parameters\n% altered with the specified values.\n% \n% Parameters for Student-t likelihood [default]\n% sigma2 - scale squared [1]\n% nu - degrees of freedom [4]\n% sigma2_prior - prior for sigma2 [prior_logunif]\n% nu_prior - prior for nu [prior_fixed]\n%\n% Note! If the prior is 'prior_fixed' then the parameter in\n% question is considered fixed and it is not handled in\n% optimization, grid integration, MCMC etc.\n%\n% The likelihood is defined as follows:\n% __ n\n% p(y|f, z) = || i=1 C(nu,s2) * (1 + 1/nu * (y_i - f_i)^2/s2 )^(-(nu+1)/2)\n%\n% where nu is the degrees of freedom, s2 the scale and f_i the\n% latent variable defining the mean. C(nu,s2) is constant\n% depending on nu and s2.\n%\n% See also\n% GP_SET, LIK_*, PRIOR_*\n%\n \n% Copyright (c) 2009-2010 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2011 Pasi Jyl�nki\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_T';\n ip.addOptional('lik', [], @isstruct);\n ip.addParamValue('sigma2',0.1, @(x) isscalar(x) && x>0);\n ip.addParamValue('sigma2_prior',prior_logunif(), @(x) isstruct(x) || isempty(x));\n ip.addParamValue('nu',4, @(x) isscalar(x) && x>0);\n ip.addParamValue('nu_prior',prior_fixed, @(x) isstruct(x) || isempty(x));\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n \n if isempty(lik)\n init=true;\n lik.type = 'Student-t';\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'Student-t')\n error('First argument does not seem to be a valid likelihood function structure')\n end\n init=false;\n end\n\n % Initialize parameters\n if init || ~ismember('sigma2',ip.UsingDefaults)\n lik.sigma2 = ip.Results.sigma2;\n end\n if init || ~ismember('nu',ip.UsingDefaults)\n lik.nu = ip.Results.nu;\n end\n % Initialize prior structure\n if init\n lik.p=[];\n end\n if init || ~ismember('sigma2_prior',ip.UsingDefaults)\n lik.p.sigma2=ip.Results.sigma2_prior;\n end\n if init || ~ismember('nu_prior',ip.UsingDefaults)\n lik.p.nu=ip.Results.nu_prior;\n end\n \n if init \n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_t_pak;\n lik.fh.unpak = @lik_t_unpak;\n lik.fh.lp = @lik_t_lp;\n lik.fh.lpg = @lik_t_lpg;\n lik.fh.ll = @lik_t_ll;\n lik.fh.llg = @lik_t_llg; \n lik.fh.llg2 = @lik_t_llg2;\n lik.fh.llg3 = @lik_t_llg3;\n lik.fh.tiltedMoments = @lik_t_tiltedMoments;\n lik.fh.tiltedMoments2 = @lik_t_tiltedMoments2;\n lik.fh.siteDeriv = @lik_t_siteDeriv;\n lik.fh.siteDeriv2 = @lik_t_siteDeriv2; \n lik.fh.optimizef = @lik_t_optimizef;\n lik.fh.upfact = @lik_t_upfact;\n lik.fh.invlink = @lik_t_invlink;\n lik.fh.predy = @lik_t_predy;\n lik.fh.predprcty = @lik_t_predprcty;\n lik.fh.recappend = @lik_t_recappend;\n end\n\nend\n\nfunction [w, s] = lik_t_pak(lik)\n%LIK_T_PAK Combine likelihood parameters into one vector.\n%\n% Description \n% W = LIK_T_PAK(LIK) takes a likelihood structure LIK and\n% combines the parameters into a single row vector W. This \n% is a mandatory subfunction used for example in energy and \n% gradient computations.\n% \n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.sigma2)\n% log(log(lik.nu))\n% (hyperparameters of lik.nu)]'\n%\n% See also\n% LIK_T_UNPAK, GP_PAK\n \n w = []; s = {};\n if ~isempty(lik.p.sigma2)\n w = [w log(lik.sigma2)];\n s = [s; 'log(lik.sigma2)'];\n [wh sh] = lik.p.sigma2.fh.pak(lik.p.sigma2);\n w = [w wh];\n s = [s; sh];\n end\n if ~isempty(lik.p.nu)\n w = [w log(log(lik.nu))];\n s = [s; 'loglog(lik.nu)'];\n [wh sh] = lik.p.nu.fh.pak(lik.p.nu);\n w = [w wh];\n s = [s; sh];\n end \nend\n\nfunction [lik, w] = lik_t_unpak(lik, w)\n%LIK_T_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_T_UNPAK(W, LIK) takes a likelihood structure LIK and\n% extracts the parameters from the vector W to the LIK\n% structure. This is a mandatory subfunction used for example \n% in energy and gradient computations.\n% \n% Assignment is inverse of \n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.sigma2)\n% log(log(lik.nu))\n% (hyperparameters of lik.nu)]'\n%\n% See also\n% LIK_T_PAK, GP_UNPAK\n\n if ~isempty(lik.p.sigma2)\n lik.sigma2 = exp(w(1));\n w = w(2:end);\n [p, w] = lik.p.sigma2.fh.unpak(lik.p.sigma2, w);\n lik.p.sigma2 = p;\n end\n if ~isempty(lik.p.nu) \n lik.nu = exp(exp(w(1)));\n w = w(2:end);\n [p, w] = lik.p.nu.fh.unpak(lik.p.nu, w);\n lik.p.nu = p;\n end\nend\n\nfunction lp = lik_t_lp(lik)\n%LIK_T_LP log(prior) of the likelihood parameters\n%\n% Description\n% LP = LIK_T_LP(LIK) takes a likelihood structure LIK and\n% returns log(p(th)), where th collects the parameters.\n% This subfunction is needed when there are likelihood parameters.\n%\n% See also\n% LIK_T_LLG, LIK_T_LLG3, LIK_T_LLG2, GPLA_E\n \n v = lik.nu;\n sigma2 = lik.sigma2;\n lp = 0;\n \n if ~isempty(lik.p.sigma2) \n lp = lp + lik.p.sigma2.fh.lp(sigma2, lik.p.sigma2) +log(sigma2);\n end\n if ~isempty(lik.p.nu)\n lp = lp + lik.p.nu.fh.lp(lik.nu, lik.p.nu) +log(v) +log(log(v));\n end\nend\n\nfunction lpg = lik_t_lpg(lik)\n%LIK_T_LPG d log(prior)/dth of the likelihood parameters th\n%\n% Description\n% LPG = LIK_T_LPG(LIK) takes a likelihood structure LIK\n% and returns d log(p(th))/dth, where th collects the\n% parameters. This subfunction is needed when there are \n% likelihood parameters.\n%\n% See also\n% LIK_T_LLG, LIK_T_LLG3, LIK_T_LLG2, GPLA_G\n \n% Evaluate the gradients of log(prior)\n\n v = lik.nu;\n sigma2 = lik.sigma2;\n lpg = [];\n i1 = 0;\n \n if ~isempty(lik.p.sigma2) \n i1 = i1+1;\n lpg(i1) = lik.p.sigma2.fh.lpg(lik.sigma2, lik.p.sigma2).*sigma2 + 1;\n end\n if ~isempty(lik.p.nu) \n i1 = i1+1;\n lpg(i1) = lik.p.nu.fh.lpg(lik.nu, lik.p.nu).*v.*log(v) +log(v) + 1;\n end \nend\n\nfunction ll = lik_t_ll(lik, y, f, z)\n%LIK_T_LL Log likelihood\n%\n% Description\n% LL = LIK_T_LL(LIK, Y, F) takes a likelihood structure LIK,\n% observations Y, and latent values F. Returns the log\n% likelihood, log p(y|f,z). This subfunction is needed when \n% using Laplace approximation or MCMC for inference with \n% non-Gaussian likelihoods. This subfunction is also used in\n% information criteria (DIC, WAIC) computations.\n%\n% See also\n% LIK_T_LLG, LIK_T_LLG3, LIK_T_LLG2, GPLA_E\n\n r = y-f;\n v = lik.nu;\n sigma2 = lik.sigma2;\n\n term = gammaln((v + 1) / 2) - gammaln(v/2) -log(v.*pi.*sigma2)/2;\n ll = term + log(1 + (r.^2)./v./sigma2) .* (-(v+1)/2);\n ll = sum(ll);\nend\n\n\nfunction llg = lik_t_llg(lik, y, f, param, z)\n%LIK_T_LLG Gradient of the log likelihood\n%\n% Description\n% LOKLIKG = LIK_T_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y, and latent values F. Returns\n% the gradient of log likelihood with respect to PARAM. At the\n% moment PARAM can be 'param' or 'latent'. This subfunction is \n% needed when using Laplace approximation or MCMC for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_T_LL, LIK_T_LLG2, LIK_T_LLG3, GPLA_E\n \n r = y-f;\n v = lik.nu;\n sigma2 = lik.sigma2;\n \n switch param\n case 'param'\n n = length(y);\n\n i1=0;\n if ~isempty(lik.p.sigma2)\n i1=i1+1;\n % Derivative with respect to sigma2\n llg(i1) = -n./sigma2/2 + (v+1)./2.*sum(r.^2./(v.*sigma2.^2+r.^2*sigma2));\n % correction for the log transformation\n llg(i1) = llg(i1).*sigma2;\n end\n if ~isempty(lik.p.nu)\n i1=i1+1;\n % Derivative with respect to nu\n llg(i1) = 0.5.* sum(psi((v+1)./2) - psi(v./2) - 1./v - log(1+r.^2./(v.*sigma2)) + (v+1).*r.^2./(v.^2.*sigma2 + v.*r.^2));\n \n % correction for the log transformation\n llg(i1) = llg(i1).*v.*log(v);\n end\n case 'latent'\n llg = (v+1).*r ./ (v.*sigma2 + r.^2); \n end\n \nend\n\n\nfunction llg2 = lik_t_llg2(lik, y, f, param, z)\n%LIK_T_LLG2 Second gradients of log likelihood\n%\n% Description \n% LLG2 = LIK_T_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y, and latent values F. Returns\n% the Hessian of log likelihood with respect to PARAM. At the\n% moment PARAM can be only 'latent'. LLG2 is a vector with\n% diagonal elements of the Hessian matrix (off diagonals are\n% zero). This subfunction is needed when using Laplace \n% approximation or EP for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_T_LL, LIK_T_LLG, LIK_T_LLG3, GPLA_E\n\n r = y-f;\n v = lik.nu;\n sigma2 = lik.sigma2;\n\n switch param\n case 'param'\n \n case 'latent'\n % The Hessian d^2 /(dfdf)\n llg2 = (v+1).*(r.^2 - v.*sigma2) ./ (v.*sigma2 + r.^2).^2;\n case 'latent+param'\n % gradient d^2 / (dfds2)\n llg2 = -v.*(v+1).*r ./ (v.*sigma2 + r.^2).^2;\n \n % Correction for the log transformation\n llg2 = llg2.*sigma2;\n if ~isempty(lik.p.nu)\n % gradient d^2 / (dfdnu)\n llg2(:,2) = r./(v.*sigma2 + r.^2) - sigma2.*(v+1).*r./(v.*sigma2 + r.^2).^2;\n\n % Correction for the log transformation\n llg2(:,2) = llg2(:,2).*v.*log(v);\n end\n end\nend \n\nfunction llg3 = lik_t_llg3(lik, y, f, param, z)\n%LIK_T_LLG3 Third gradients of log likelihood (energy)\n%\n% Description\n% LLG3 = LIK_T_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F and\n% returns the third gradients of log likelihood with respect\n% to PARAM. At the moment PARAM can be only 'latent'. G3 is a\n% vector with third gradients. This subfunction is needed when \n% using Laplace approximation for inference with non-Gaussian \n% likelihoods.\n%\n% See also\n% LIK_T_LL, LIK_T_LLG, LIK_T_LLG2, GPLA_E, GPLA_G\n\n r = y-f;\n v = lik.nu;\n sigma2 = lik.sigma2;\n \n switch param\n case 'param'\n \n case 'latent'\n % Return the diagonal of W differentiated with respect to latent values / dfdfdf\n llg3 = (v+1).*(2.*r.^3 - 6.*v.*sigma2.*r) ./ (v.*sigma2 + r.^2).^3;\n case 'latent2+param'\n % Return the diagonal of W differentiated with respect to\n % likelihood parameters / dfdfds2\n llg3 = (v+1).*v.*( v.*sigma2 - 3.*r.^2) ./ (v.*sigma2 + r.^2).^3;\n llg3 = llg3.*sigma2;\n if ~isempty(lik.p.nu)\n % dfdfdnu\n llg3(:,2) = (r.^2-2.*v.*sigma2-sigma2)./(v.*sigma2 + r.^2).^2 - 2.*sigma2.*(r.^2-v.*sigma2).*(v+1)./(v.*sigma2 + r.^2).^3;\n llg3(:,2) = llg3(:,2).*v.*log(v);\n end\n end\nend\n\n\nfunction [logM_0, m_1, sigm2hati1] = lik_t_tiltedMoments(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_T_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIK_T_TILTEDMOMENTS(LIK, Y, I, S2, MYY, Z)\n% takes a likelihood structure LIK, incedence counts Y,\n% expected counts Z, index I and cavity variance S2 and mean\n% MYY. Returns the zeroth moment M_0, mean M_1 and variance\n% M_2 of the posterior marginal (see Rasmussen and Williams\n% (2006): Gaussian processes for Machine Learning, page 55).\n% This subfunction is needed when using EP for inference with \n% non-Gaussian likelihoods.\n%\n% See also\n% GPEP_E\n\n \n zm = @zeroth_moment;\n \n tol = 1e-8;\n yy = y(i1);\n nu = lik.nu;\n sigma2 = lik.sigma2;\n \n % Set the limits for integration and integrate with quad\n % -----------------------------------------------------\n mean_app = myy_i;\n sigm_app = sqrt(sigm2_i);\n\n\n lambdaconf(1) = mean_app - 8.*sigm_app; lambdaconf(2) = mean_app + 8.*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2) > zm(lambdaconf(1));\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2) > zm(lambdaconf(2));\n testiter = 1;\n if test1 == 0 \n lambdaconf(1) = lambdaconf(1) - 3*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n if test1 == 0\n go=true;\n while testiter<10 & go\n lambdaconf(1) = lambdaconf(1) - 2*sigm_app;\n lambdaconf(2) = lambdaconf(2) - 2*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n if test1==1&test2==1\n go=false;\n end\n testiter=testiter+1;\n end\n end\n mean_app = (lambdaconf(2)+lambdaconf(1))/2;\n elseif test2 == 0\n lambdaconf(2) = lambdaconf(2) + 3*sigm_app;\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n if test2 == 0\n go=true;\n while testiter<10 & go\n lambdaconf(1) = lambdaconf(1) + 2*sigm_app;\n lambdaconf(2) = lambdaconf(2) + 2*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n if test1==1&test2==1\n go=false;\n end\n testiter=testiter+1;\n end\n end\n mean_app = (lambdaconf(2)+lambdaconf(1))/2;\n end\n RTOL = 1.e-6;\n ATOL = 1.e-10;\n \n % Integrate with quadrature\n [m_0, m_1, m_2] = quad_moments(zm,lambdaconf(1), lambdaconf(2), RTOL, ATOL); \n \n sigm2hati1 = m_2 - m_1.^2;\n logM_0 = log(m_0);\n function integrand = zeroth_moment(f)\n r = yy-f;\n term = gammaln((nu + 1) / 2) - gammaln(nu/2) -log(nu.*pi.*sigma2)/2;\n integrand = exp(term + log(1 + r.^2./nu./sigma2) .* (-(nu+1)/2));\n integrand = integrand.*exp(- 0.5 * (f-myy_i).^2./sigm2_i - log(sigm2_i)/2 - log(2*pi)/2); %\n end\nend\n\nfunction [g_i] = lik_t_siteDeriv(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_T_SITEDERIV Evaluate the expectation of the gradient\n% of the log likelihood term with respect\n% to the likelihood parameters for EP \n%\n% Description\n% [M_0, M_1, M2] = LIK_T_TILTEDMOMENTS(LIK, Y, I, S2, MYY)\n% takes a likelihood structure LIK, observations Y, index I\n% and cavity variance S2 and mean MYY. Returns E_f [d log\n% p(y_i|f_i) /d a], where a is the likelihood parameter and\n% the expectation is over the marginal posterior. This term is\n% needed when evaluating the gradients of the marginal\n% likelihood estimate Z_EP with respect to the likelihood\n% parameters (see Seeger (2008): Expectation propagation for\n% exponential families). This subfunction is needed when using \n% EP for inference with non-Gaussian likelihoods and there are\n% likelihood parameters.\n%\n% See also\n% GPEP_G\n\n zm = @zeroth_moment;\n znu = @deriv_nu;\n zsigma2 = @deriv_sigma2;\n \n tol = 1e-8;\n yy = y(i1);\n nu = lik.nu;\n sigma2 = lik.sigma2;\n\n % Set the limits for integration and integrate with quad\n mean_app = myy_i;\n sigm_app = sqrt(sigm2_i);\n\n lambdaconf(1) = mean_app - 6.*sigm_app; lambdaconf(2) = mean_app + 6.*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n testiter = 1;\n if test1 == 0 \n lambdaconf(1) = lambdaconf(1) - 3*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n if test1 == 0\n go=true;\n while testiter<10 & go\n lambdaconf(1) = lambdaconf(1) - 2*sigm_app;\n lambdaconf(2) = lambdaconf(2) - 2*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n if test1==1&test2==1\n go=false;\n end\n testiter=testiter+1;\n end\n end\n mean_app = (lambdaconf(2)+lambdaconf(1))/2;\n elseif test2 == 0\n lambdaconf(2) = lambdaconf(2) + 3*sigm_app;\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n if test2 == 0\n go=true;\n while testiter<10 & go\n lambdaconf(1) = lambdaconf(1) + 2*sigm_app;\n lambdaconf(2) = lambdaconf(2) + 2*sigm_app;\n test1 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(1));\n test2 = zm((lambdaconf(2)+lambdaconf(1))/2)>zm(lambdaconf(2));\n if test1==1&test2==1\n go=false;\n end\n testiter=testiter+1;\n end\n end\n mean_app = (lambdaconf(2)+lambdaconf(1))/2;\n end\n\n % Integrate with quad\n [m_0, fhncnt] = quadgk(zm, lambdaconf(1), lambdaconf(2));\n \n % t=linspace(lambdaconf(1),lambdaconf(2),100);\n % plot(t,zm(t))\n % keyboard\n \n [g_i(1), fhncnt] = quadgk( @(f) zsigma2(f).*zm(f) , lambdaconf(1), lambdaconf(2));\n g_i(1) = g_i(1)/m_0*sigma2;\n \n if ~isempty(lik.p.nu)\n [g_i(2), fhncnt] = quadgk(@(f) znu(f).*zm(f) , lambdaconf(1), lambdaconf(2));\n g_i(2) = g_i(2)/m_0.*nu.*log(nu);\n end\n \n function integrand = zeroth_moment(f)\n r = yy-f;\n term = gammaln((nu + 1) / 2) - gammaln(nu/2) -log(nu.*pi.*sigma2)/2;\n integrand = exp(term + log(1 + r.^2./nu./sigma2) .* (-(nu+1)/2));\n integrand = integrand.*exp(- 0.5 * (f-myy_i).^2./sigm2_i - log(sigm2_i)/2 - log(2*pi)/2);\n end \n\n function g = deriv_nu(f)\n r = yy-f;\n temp = 1 + r.^2./nu./sigma2;\n g = psi((nu+1)/2)./2 - psi(nu/2)./2 - 1./(2.*nu) - log(temp)./2 + (nu+1)./(2.*temp).*(r./nu).^2./sigma2;\n end\n\n function g = deriv_sigma2(f)\n r = yy-f;\n g = -1/sigma2/2 + (nu+1)./2.*r.^2./(nu.*sigma2.^2 + r.^2.*sigma2);\n end\n\nend\n\nfunction [lnZhat, muhat, sigm2hat] = lik_t_tiltedMoments2(likelih, y, yi, sigm2_i, myy_i, z, eta)\n%LIKELIH_T_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIKELIH_T_TILTEDMOMENTS(LIKELIH, Y, I, S2, MYY, Z)\n% takes a likelihood data structure LIKELIH, incedence counts Y,\n% expected counts Z, index I and cavity variance S2 and mean\n% MYY. Returns the zeroth moment M_0, mean M_1 and variance M_2\n% of the posterior marginal (see Rasmussen and Williams (2006):\n% Gaussian processes for Machine Learning, page 55). This subfunction \n% is needed when using robust-EP for inference with non-Gaussian \n% likelihoods.\n%\n% See also\n% GPEP_E\n\n if nargin<7\n eta=1;\n end\n \n yy = y(yi);\n nu = likelih.nu;\n sigma2 = likelih.sigma2;\n sigma = sqrt(sigma2);\n \n nuprime = eta*nu+eta-1;\n a=nuprime/2; %a=nu/2;\n \n u=linspace(log(1e-8),5,200);\n du=u(2)-u(1);\n lnpu=(a-1)*u -a*exp(u)+u;\n \n % sigma2 t-likelihood parameter, scale squared\n % sigm2_i cavity variance\n % myy_i cavity mean\n \n sigma2prime = sigma2*nu/nuprime;\n Vu = sigm2_i + (sigma2prime)./exp(u);\n lnZu = 0.5*(-log(2*pi*Vu)) -0.5 * (yy-myy_i)^2 ./Vu;\n lnZt = eta*gammaln((nu+1)/2) - eta/2*log(nu*pi*sigma2) - eta*gammaln(nu/2) - gammaln((nuprime+1)/2) + 0.5*log(nuprime*pi*sigma2prime) + gammaln(nuprime/2);\n \n ptu=exp(lnpu+lnZu+lnZt);\n \n Z_0=sum(ptu)*du;\n lnZhat=log(Z_0) + a*log(a)-gammaln(a);\n \n Vtu=1./(1/sigm2_i +(1/sigma2prime)*exp(u));\n mtu=Vtu.*(myy_i/sigm2_i + (yy/sigma2prime)*exp(u));\n \n muhat=sum(mtu.*ptu)*du/Z_0;\n sigm2hat=sum((Vtu+mtu.^2).*ptu)*du/Z_0-muhat^2;\n \n % limiting distribution (nu -> infinity)\n% Vg=1/(1/sigm2_i +eta/sigma2);\n% mg=Vg*(myy_i/sigm2_i +yy*eta/sigma2);\n% sigm_i=sqrt(sigm2_i);\n% sg=sqrt(Vg);\n% \n% % set integration limits and scaling\n% nu_lim=1e10;\n% if nu=myy_i\n% % grid break points \n% bp=[min(myy_i-6*sigm_i,yy-dd*sigma) myy_i-6*sigm_i, ...\n% min(myy_i+6*sigm_i,yy-dd*sigma), yy-dd*sigma, yy+dd*sigma,...\n% max(myy_i+6*sigm_i,yy+dd*sigma)];\n% \n% % grid values\n% a=1e-6;\n% fvec =[ bp(1):df(2):bp(2)-a, bp(2):df(1):bp(3)-a, bp(3):max(df):bp(4)-a, ...\n% bp(4):df(2):bp(5)-a, bp(5):df(1):bp(6)];\n% else\n% % grid break points \n% bp=[min(myy_i-6*sigm_i,yy-dd*sigma), yy-dd*sigma, yy+dd*sigma,...\n% max(myy_i-6*sigm_i,yy+dd*sigma), myy_i+6*sigm_i, ...\n% max(myy_i+6*sigm_i,yy+dd*sigma)];\n% \n% % grid values\n% a=1e-6;\n% fvec =[ bp(1):df(1):bp(2)-a, bp(2):df(2):bp(3)-a, bp(3):max(df):bp(4)-a, ...\n% bp(4):df(1):bp(5)-a, bp(5):df(2):bp(6)];\n% end\n% \n% np=numel(fvec);\n% logpt = lpt(fvec,0);\n% lpt_max = max([logpt lpt([myy_i mg],0)]);\n% lambdaconf=[fvec(1), fvec(end)];\n% for i1=2:np-1\n% if logpt(i1) < lpt_max+log(1e-7) %(exp(logpt(i1))/exp(lpt_max) < 1e-7)\n% lambdaconf(1) = fvec(i1);\n% else\n% break;\n% end\n% end\n% for i1=1:np-2\n% if logpt(end-i1) < lpt_max+log(1e-7) %(exp(logpt(end-i1))/exp(lpt_max) < 1e-7)\n% lambdaconf(2) = fvec(end-i1);\n% else\n% break;\n% end\n% end\n% else\n% % set the integration limits in easier cases\n% np=20;\n% if mg>myy_i\n% lambdaconf=[myy_i-6*sigm_i,max(mg+6*sg,myy_i+6*sigm_i)];\n% fvec=linspace(myy_i,mg,np);\n% else\n% lambdaconf=[min(mg-6*sg,myy_i-6*sigm_i),myy_i+6*sigm_i];\n% fvec=linspace(mg,myy_i,np);\n% end\n% lpt_max=max(lpt(fvec,0));\n% end\n% C=log(1)-lpt_max; % scale the log-density for the quadrature tolerance\n% else\n% lambdaconf=[mg-6*sg,mg+6*sg];\n% C=log(1)-lpt(mg,0);\n% end\n% \n% if nu>nu_lim\n% % the limiting Gaussian case\n% Vz=sigm2_i+sigma2/eta;\n% lnZhat = 0.5*(-log(eta) +(1-eta)*log(2*pi*sigma2) -log(2*pi*Vz)) -(0.5/Vz)*(yy-myy_i)^2;\n% muhat = mg;\n% sigm2hat = Vg;\n% else\n% % Integrate with quadrature\n% RTOL = 1.e-6;\n% ATOL = 1.e-7;\n% tic\n% [m_0, m_1, m_2] = quad_moments(@(f) exp(lpt(f,C)),lambdaconf(1), lambdaconf(2), RTOL, ATOL);toc\n% muhat = m_1;\n% sigm2hat = m_2 - m_1.^2;\n% lnZhat = log(m_0) -C;\n% end\n \n function lpdf = lpt(f,C)\n % logarithm of the tilted distribution\n r = yy-f;\n lpdf = gammaln((nu + 1) / 2) - gammaln(nu/2) -log(nu.*pi.*sigma2)/2;\n lpdf = lpdf + log(1 + r.^2./nu./sigma2) .* (-(nu+1)/2);\n lpdf = lpdf*eta - (0.5/sigm2_i) * (f-myy_i).^2 + (C-log(2*pi*sigm2_i)/2);\n end\nend\n\nfunction [g_i] = lik_t_siteDeriv2(likelih, y, yi, sigm2_i, myy_i, z, eta, lnZhat)\n%LIKELIH_T_SITEDERIV Evaluate the expectation of the gradient\n% of the log likelihood term with respect\n% to the likelihood parameters for EP\n%\n% Description\n% [M_0, M_1, M2] = LIKELIH_T_TILTEDMOMENTS(LIKELIH, Y, I, S2, MYY)\n% takes a likelihood data structure LIKELIH, observations Y, index I\n% and cavity variance S2 and mean MYY. Returns E_f [d log\n% p(y_i|f_i) /d a], where a is the likelihood parameter and the\n% expectation is over the marginal posterior. This term is\n% needed when evaluating the gradients of the marginal\n% likelihood estimate Z_EP with respect to the likelihood\n% parameters (see Seeger (2008): Expectation propagation for\n% exponential families). This subfunction is needed when using \n% robust-EP for inference with non-Gaussian likelihoods and there \n% are likelihood parameters.\n%\n% See also\n% GPEP_G\n \n if nargin<7\n eta=1;\n end\n \n yy = y(yi);\n nu = likelih.nu;\n sigma2 = likelih.sigma2;\n sigma = sqrt(sigma2);\n \n % limiting distribution (nu -> infinity)\n Vg=1/(1/sigm2_i +eta/sigma2);\n mg=Vg*(myy_i/sigm2_i +yy*eta/sigma2);\n sigm_i=sqrt(sigm2_i);\n sg=sqrt(Vg);\n \n % set integration limits and scaling\n nu_lim=1e10;\n if nu=myy_i\n % grid break points \n bp=[min(myy_i-6*sigm_i,yy-dd*sigma) myy_i-6*sigm_i, ...\n min(myy_i+6*sigm_i,yy-dd*sigma), yy-dd*sigma, yy+dd*sigma,...\n max(myy_i+6*sigm_i,yy+dd*sigma)];\n \n % grid values\n a=1e-6;\n fvec =[ bp(1):df(2):bp(2)-a, bp(2):df(1):bp(3)-a, bp(3):max(df):bp(4)-a, ...\n bp(4):df(2):bp(5)-a, bp(5):df(1):bp(6)];\n else\n % grid break points \n bp=[min(myy_i-6*sigm_i,yy-dd*sigma), yy-dd*sigma, yy+dd*sigma,...\n max(myy_i-6*sigm_i,yy+dd*sigma), myy_i+6*sigm_i, ...\n max(myy_i+6*sigm_i,yy+dd*sigma)];\n \n % grid values\n a=1e-6;\n fvec =[ bp(1):df(1):bp(2)-a, bp(2):df(2):bp(3)-a, bp(3):max(df):bp(4)-a, ...\n bp(4):df(1):bp(5)-a, bp(5):df(2):bp(6)];\n end\n \n np=numel(fvec);\n logpt = lpt(fvec,0);\n lpt_max = max([logpt lpt([myy_i mg],0)]);\n lambdaconf=[fvec(1), fvec(end)];\n for i1=2:np-1\n if logpt(i1) < lpt_max+log(1e-7) %(exp(logpt(i1))/exp(lpt_max) < 1e-7)\n lambdaconf(1) = fvec(i1);\n else\n break;\n end\n end\n for i1=1:np-2\n if logpt(end-i1) < lpt_max+log(1e-7) %(exp(logpt(end-i1))/exp(lpt_max) < 1e-7)\n lambdaconf(2) = fvec(end-i1);\n else\n break;\n end\n end\n else\n % set the integration limits in easier cases\n np=20;\n if mg>myy_i\n lambdaconf=[myy_i-6*sigm_i,max(mg+6*sg,myy_i+6*sigm_i)];\n fvec=linspace(myy_i,mg,np);\n else\n lambdaconf=[min(mg-6*sg,myy_i-6*sigm_i),myy_i+6*sigm_i];\n fvec=linspace(mg,myy_i,np);\n end\n lpt_max=max(lpt(fvec,0));\n end\n C=log(1)-lpt_max; % scale the log-density for the quadrature tolerance\n else\n lambdaconf=[mg-6*sg,mg+6*sg];\n C=log(1)-lpt(mg,0);\n end\n \n if nu>nu_lim\n % the limiting normal observation model\n Vz=sigm2_i+sigma2/eta;\n g_i(1) = 0.5*( (1-eta)/sigma2 -1/Vz/eta + (yy-myy_i)^2 /Vz^2 /eta ) *sigma2/eta;\n \n if (isfield(likelih,'p') && ~isempty(likelih.p.nu))\n g_i(2) = 0;\n end\n else\n \n % Integrate with quadrature\n RTOL = 1.e-6;\n ATOL = 1e-7;\n \n % Integrate with quad\n %zm=@(f) exp(lpt(f,C));\n %[m_0, fhncnt] = quadgk(zm, lambdaconf(1), lambdaconf(2),'AbsTol',ATOL,'RelTol',RTOL)\n \n % Use the normalization determined in the lik_t_tiltedMoments2\n m_0=exp(lnZhat+C);\n \n zm=@(f) deriv_sigma2(f).*exp(lpt(f,C))*sigma2;\n [g_i(1), fhncnt] = quadgk( zm, lambdaconf(1), lambdaconf(2),'AbsTol',ATOL,'RelTol',RTOL);\n g_i(1) = g_i(1)/m_0;\n \n if (isfield(likelih,'p') && ~isempty(likelih.p.nu))\n zm=@(f) deriv_nu(f).*exp(lpt(f,C));\n [g_i(2), fhncnt] = quadgk( zm, lambdaconf(1), lambdaconf(2),'AbsTol',ATOL,'RelTol',RTOL);\n g_i(2) = g_i(2)/m_0.*nu.*log(nu);\n end\n \n end\n \n function lpdf = lpt(f,C)\n % logarithm of the tilted distribution\n r = yy-f;\n lpdf = gammaln((nu + 1) / 2) - gammaln(nu/2) -log(nu.*pi.*sigma2)/2;\n lpdf = lpdf + log(1 + r.^2./nu./sigma2) .* (-(nu+1)/2);\n lpdf = lpdf*eta - (0.5/sigm2_i) * (f-myy_i).^2 + (C-log(2*pi*sigm2_i)/2);\n end\n\n function g = deriv_nu(f)\n % derivative of the log-likelihood wrt nu\n r = yy-f;\n temp = r.^2 ./(nu*sigma2);\n g = psi((nu+1)/2) - psi(nu/2) - 1/nu;\n g = g + (1+1/nu).*temp./(1+temp);\n \n % for small values use a more accurate method for log(1+x)\n ii = temp<1e3;\n g(ii) = g(ii) - log1p(temp(ii));\n g(~ii) = g(~ii) - log(1+temp(~ii));\n g = g*0.5;\n \n end\n\n function g = deriv_sigma2(f)\n % derivative of the log-likelihood wrt sigma2\n r = yy-f;\n temp = r.^2 /sigma2;\n g = -1/sigma2/2 + ((1+1/nu)/2) * temp ./ (1 + temp/nu) /sigma2;\n end\n\nend\n\n\nfunction [f, a] = lik_t_optimizef(gp, y, K, Lav, K_fu)\n%LIK_T_OPTIMIZEF function to optimize the latent variables\n% with EM algorithm\n%\n% Description:\n% [F, A] = LIK_T_OPTIMIZEF(GP, Y, K, Lav, K_fu) Takes Gaussian\n% process structure GP, observations Y and the covariance\n% matrix K. Solves the posterior mode of F using EM algorithm\n% and evaluates A = (K + W)\\Y as a sideproduct. Lav and K_fu\n% are needed for sparse approximations. For details, see\n% Vanhatalo, Jyl�nki and Vehtari (2009): Gaussian process\n% regression with Student-t likelihood. This subfunction is \n% needed when using lik_specific optimization method for mode \n% finding in Laplace algorithm.\n%\n \n iter = 1;\n sigma2 = gp.lik.sigma2;\n% if sigma2==0\n% f=NaN;a=NaN;\n% return\n% end\n nu = gp.lik.nu;\n n = length(y);\n \n switch gp.type\n case 'FULL' \n iV = ones(n,1)./sigma2;\n siV = sqrt(iV);\n B = eye(n) + siV*siV'.*K;\n [L,notpositivedefinite] = chol(B);\n if notpositivedefinite\n f=NaN;a=NaN;\n return\n end\n B=B';\n b = iV.*y;\n a = b - siV.*(L'\\(L\\(siV.*(K*b))));\n f = K*a;\n while iter < 200\n fold = f; \n iV = (nu+1) ./ (nu.*sigma2 + (y-f).^2);\n siV = sqrt(iV);\n B = eye(n) + siV*siV'.*K;\n L = chol(B)';\n b = iV.*y;\n ws=warning('off','MATLAB:nearlySingularMatrix');\n a = b - siV.*(L'\\(L\\(siV.*(K*b))));\n warning(ws);\n f = K*a;\n \n if max(abs(f-fold)) < 1e-8\n break\n end\n iter = iter + 1;\n end\n case 'FIC'\n K_uu = K;\n \n Luu = chol(K_uu)';\n B=Luu\\(K_fu'); % u x f\n\n K = diag(Lav) + B'*B;\n \n iV = ones(n,1)./sigma2;\n siV = sqrt(iV);\n B = eye(n) + siV*siV'.*K;\n L = chol(B)';\n b = iV.*y;\n a = b - siV.*(L'\\(L\\(siV.*(K*b))));\n f = K*a;\n while iter < 200\n fold = f; \n iV = (nu+1) ./ (nu.*sigma2 + (y-f).^2);\n siV = sqrt(iV);\n B = eye(n) + siV*siV'.*K;\n L = chol(B)';\n b = iV.*y;\n a = b - siV.*(L'\\(L\\(siV.*(K*b))));\n f = K*a;\n \n if max(abs(f-fold)) < 1e-8\n break\n end\n iter = iter + 1;\n end\n end\n \nend\n\nfunction upfact = lik_t_upfact(gp, y, mu, ll, z)\n nu = gp.lik.nu;\n sigma = sqrt(gp.lik.sigma2);\n sll = sqrt(ll);\n\n fh_e = @(f) t_pdf(f, nu, y, sigma).*norm_pdf(f, mu, sll);\n EE = quadgk(fh_e, -40, 40);\n \n \n fm = @(f) f.*t_pdf(f, nu, y, sigma).*norm_pdf(f, mu, sll)./EE;\n mm = quadgk(fm, -40, 40);\n \n fV = @(f) (f - mm).^2.*t_pdf(f, nu, y, sigma).*norm_pdf(f, mu, sll)./EE;\n Varp = quadgk(fV, -40, 40);\n \n upfact = -(Varp - ll)./ll^2;\nend\n\nfunction [lpy, Ey, Vary] = lik_t_predy(lik, Ef, Varf, y, z)\n%LIK_T_PREDY Returns the predictive mean, variance and density of y\n%\n% Description \n% LPY = LIK_T_PREDY(LIK, EF, VARF YT)\n% Returns logarithm of the predictive density PY of YT, that is \n% p(yt | zt) = \\int p(yt | f, zt) p(f|y) df.\n% This requires also the observations YT. This subfunction is \n% needed when computing posterior preditive distributions for \n% future observations.\n%\n% [LPY, EY, VARY] = LIK_T_PREDY(LIK, EF, VARF) takes a likelihood\n% structure LIK, posterior mean EF and posterior Variance\n% VARF of the latent variable and returns the posterior\n% predictive mean EY and variance VARY of the observations\n% related to the latent variables. This subfunction is needed when \n% computing posterior preditive distributions for future observations.\n% \n\n%\n% See also\n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n nu = lik.nu;\n sigma2 = lik.sigma2;\n sigma = sqrt(sigma2);\n \n Ey = zeros(size(Ef));\n EVary = zeros(size(Ef));\n VarEy = zeros(size(Ef)); \n lpy = zeros(size(Ef));\n if nargout > 1\n% for i1=1:length(Ef)\n% %%% With quadrature\n% ci = sqrt(Varf(i1));\n% \n% F = @(x) x.*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n% Ey(i1) = quadgk(F,Ef(i1)-6*ci,Ef(i1)+6*ci);\n% \n% F2 = @(x) (nu./(nu-2).*sigma2).*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n% EVary(i1) = quadgk(F2,Ef(i1)-6*ci,Ef(i1)+6*ci);\n% \n% F3 = @(x) x.^2.*norm_pdf(x,Ef(i1),sqrt(Varf(i1)));\n% VarEy(i1) = quadgk(F3,Ef(i1)-6*ci,Ef(i1)+6*ci) - Ey(i1).^2;\n% end\n% Vary = EVary + VarEy;\n \n Ey = Ef;\n if nu>2\n Vary=nu./(nu-2).*sigma2 +Varf;\n else\n warning('Variance of Student''s t-distribution is not defined for nu<=2')\n Vary=NaN+Varf;\n end\n end\n \n\n lpy = zeros(length(y),1);\n for i2 = 1:length(y)\n mean_app = Ef(i2);\n sigm_app = sqrt(Varf(i2));\n \n pd = @(f) t_pdf(y(i2), nu, f, sigma).*norm_pdf(f,Ef(i2),sqrt(Varf(i2)));\n lpy(i2) = log(quadgk(pd, mean_app - 12*sigm_app, mean_app + 12*sigm_app));\n end\n\n \nend\n\nfunction prctys = lik_t_predprcty(lik, Ef, Varf, zt, prcty)\n%LIK_T_PREDPRCTY Returns the percentiles of predictive density of y\n%\n% Description \n% PRCTY = LIK_T_PREDPRCTY(LIK, EF, VARF YT, ZT)\n% Returns percentiles of the predictive density PY of YT. This\n% subfunction is needed when using function gp_predprcty.\n%\n% See also \n% GP_PREDPCTY\n\n opt=optimset('TolX',1e-5,'Display','off');\n nt=size(Ef,1);\n prctys = zeros(nt,numel(prcty));\n prcty=prcty/100;\n nu = lik.nu;\n nu_p=max(2.5,nu);\n sigma2 = lik.sigma2;\n Vary=nu_p./(nu_p-2).*sigma2 +Varf;\n for i1=1:nt\n ci = sqrt(Varf(i1));\n for i2=1:numel(prcty)\n minf=sqrt(Vary(i1))*tinv(prcty(i2),nu)+(Ef(i1)-2.5*sqrt(Vary(i1)));\n maxf=sqrt(Vary(i1))*tinv(prcty(i2),nu)+(Ef(i1)+2.5*sqrt(Vary(i1)));\n a=(fminbnd(@(a) (quadgk(@(f) tcdf((a-f)/sqrt(Vary(i1)),nu).*norm_pdf(f,Ef(i1),ci),Ef(i1)-6*ci,Ef(i1)+6*ci,'AbsTol',1e-4)-prcty(i2)).^2,minf,maxf,opt));\n% a=(fminbnd(@(a) (quadgk(@(f) quadgk(@(y) t_pdf(y,nu,Ef(i1),sqrt(Vary(i1))),Ef(i1)-12*sqrt(Vary(i1)),a).*norm_pdf(f,Ef(i1),ci),Ef(i1)-6*ci,Ef(i1)+6*ci,'AbsTol',1e-4)-prcty(i2)).^2,minf,maxf,opt));\n prctys(i1,i2)=a;\n close all;\n end\n end\nend\n\nfunction mu = lik_t_invlink(lik, f, z)\n%LIK_T_INVLINK Returns values of inverse link function\n% \n% Description \n% P = LIK_T_INVLINK(LIK, F) takes a likelihood structure LIK and\n% latent values F and returns the values MU of inverse link function.\n% This subfunction is needed when using gp_predprctmu. \n%\n% See also\n% LIK_T_LL, LIK_T_PREDY\n \n mu = f;\nend\n\nfunction reclik = lik_t_recappend(reclik, ri, lik)\n%RECAPPEND Record append\n% Description\n% RECCF = GPCF_SEXP_RECAPPEND(RECCF, RI, GPCF) takes old\n% covariance function record RECCF, record index RI, RECAPPEND\n% returns a structure RECCF. This subfunction is needed when \n% using MCMC sampling (gp_mc).\n\n if nargin == 2\n % Initialize the record\n reclik.type = 'Student-t';\n\n % Initialize parameters\n reclik.nu = [];\n reclik.sigma2 = [];\n\n % Set the function handles\n reclik.fh.pak = @lik_t_pak;\n reclik.fh.unpak = @lik_t_unpak;\n reclik.fh.lp = @lik_t_lp;\n reclik.fh.lpg = @lik_t_lpg;\n reclik.fh.ll = @lik_t_ll;\n reclik.fh.llg = @lik_t_llg; \n reclik.fh.llg2 = @lik_t_llg2;\n reclik.fh.llg3 = @lik_t_llg3;\n reclik.fh.tiltedMoments = @lik_t_tiltedMoments;\n reclik.fh.tiltedMoments2 = @lik_t_tiltedMoments2;\n reclik.fh.siteDeriv = @lik_t_siteDeriv;\n reclik.fh.siteDeriv2 = @lik_t_siteDeriv2;\n reclik.fh.optimizef = @lik_t_optimizef;\n reclik.fh.upfact = @lik_t_upfact;\n reclik.fh.invlink = @lik_t_invlink;\n reclik.fh.predy = @lik_t_predy;\n reclik.fh.predprcty = @lik_t_predprcty;\n reclik.fh.recappend = @lik_t_recappend;\n reclik.p.nu=[];\n if ~isempty(ri.p.nu)\n reclik.p.nu = ri.p.nu;\n end\n reclik.p.sigma2=[];\n if ~isempty(ri.p.sigma2)\n reclik.p.sigma2 = ri.p.sigma2;\n end\n else\n % Append to the record\n likp = lik.p;\n \n % record sigma2\n reclik.sigma2(ri,:) = lik.sigma2;\n if isfield(likp,'sigma2') && ~isempty(likp.sigma2)\n reclik.p.sigma2 = likp.sigma2.fh.recappend(reclik.p.sigma2, ri, likp.sigma2);\n end\n % record nu\n reclik.nu(ri,:) = lik.nu;\n if isfield(likp,'nu') && ~isempty(likp.nu)\n reclik.p.nu = likp.nu.fh.recappend(reclik.p.nu, ri, likp.nu);\n end\n end\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/lik_t.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39392531883179815}}
{"text": "function [res]=tt_smv(sttm, vec)\n%TT-matrix with sparse factors by TT-vector multiplication\n% [res]=TT_SMV(STTM,VEC) Multiplies the TT-matrix stored in the TT1.0\n% format but with \"sparse\" cores by a vector VEC\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\n\nd=size(vec,1);\nres=cell(d,1);\n\nn=sttm{d+2}(1);\n% m=size(vec{1},1);\nrm1=sttm{d+1}(1);\nrv1=size(vec{1},2);\n%mat{1} is (n x m x rm1 , vec{1} is mxrv1)\n% n x rm1 x rv1\nres{1}=sttm{1}*vec{1};\nres{1}=reshape(permute(reshape(res{1},[n,rm1,rv1]),[1,3,2]),[n,rv1*rm1]);\n\nif (d>1)\n n=sttm{d+2}(d);\n % m=size(mat{d},2);\n rm1=sttm{d+1}(d-1);\n rv1=size(vec{d},2);\n %mat{1} is (n x rm1 x rv1 , vec{1} is mxrv1)\n res{d}=sttm{d}*vec{d};\n res{d}=reshape(permute(reshape(res{d},[n,rm1,rv1]),[1,3,2]),[n,rv1*rm1]);\nend;\n\nfor i=2:d-1\n n=sttm{d+2}(i);\n m=size(vec{i},1);\n rm1=sttm{d+1}(i-1);\n rm2=sttm{d+1}(i);\n rv1=size(vec{i},2);\n rv2=size(vec{i},3);\n %mat{i} is n x m x rm1 x rm2, vec{i} is m x rv1 x rv2\n %n x (rv1*rv2)*rm1*rm2\n %n x rm2 x rm1 x m, n x rm2 x rm1 x (rv1*rv2)\n %n x rm2 x rmx1 x rv1 x rv2\n %want: n x rv1*rm1 x rv2*rm2\n res{i}=sttm{i}*reshape(vec{i},[m,rv1*rv2]);\n res{i}=reshape(res{i},[n,rm2,rm1,rv1,rv2]);\n res{i}=permute(res{i},[1,4,3,5,2]);\n res{i}=reshape(res{i},[n,rv1*rm1,rv2*rm2]);\n %res{i}=permute(reshape(permute(mat{i},[1,3,4,2])*reshape(vec{i},[m,rv1*rv2]),[n,rv1,rv2,rm1,rm2]),[1,2,4,3,5]);\nend \n\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/exp/tt_smv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.3939177282406857}}
{"text": "function h = conv(f, g)\n%CONV Convolution of DELTAFUN objects.\n% H = CONV(F, G) produces the convolution of DELTAFUN objects F and G:\n% - \n% /\n% H(x) = | F(t) G(x-t) dt, x in [a + c, b + d]\n% /\n% The output H is a cell array of DELTAFUNs or CLASSICFUNS. If the result of\n% the convolution of F and G is zero, an empty cell is returned. The cell\n% array returned is used by higher level convolutions.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Return empty for an empty input:\nif ( isempty(f) || isempty(g) )\n h = deltafun();\n return\nend\n\nif ( ~isa(f, 'deltafun') )\n deltaMagF = [];\n deltaLocF = [];\n funF = f;\nelse\n f = simplifyDeltas(f);\n if ( isa(f, 'deltafun') )\n deltaMagF = f.deltaMag;\n deltaLocF = f.deltaLoc; \n funF = f.funPart;\n else\n deltaMagF = [];\n deltaLocF = [];\n funF = f;\n end\nend\n\nif ( ~isa(g, 'deltafun') )\n deltaMagG = [];\n deltaLocG = [];\n funG = g;\nelse\n g = simplifyDeltas(g);\n if ( isa(g, 'deltafun') )\n deltaMagG = g.deltaMag;\n deltaLocG = g.deltaLoc; \n funG = g.funPart;\n else\n deltaMagG = [];\n deltaLocG = [];\n funG = g;\n end\nend\n\n% Extract the domains of f and g:\ndomF = funF.domain;\ndomG = funG.domain;\na = domF(1);\nb = domF(end);\nc = domG(1);\nd = domG(end);\n\n% Get the threshold for deltafunctions:\npref = chebfunpref();\ndeltaTol = pref.deltaPrefs.deltaTol;\n\n% Compute the convolution of funParts and append it to the output cell:\nh = conv(funF, funG);\n\n% Remove zero funs for simplicity:\nzeroIndices = cellfun( @(hk) iszero(hk), h);\nh(zeroIndices) = [];\n\n%% Get all the deltafunction contributions\n% (f + df) * (g + dg) = f*g + dg * (f + df) + df * (g + dg) - df * dg\n% = f*g + dg * (f + df/2) + df * (g + dg/2)\n\n% Contributions due to deltafunctions in F:\n% df * (g + dg/2):\nh = convDeltas(deltaMagF, deltaLocF, g, c, d, deltaTol, h);\n\n% Contributions due to delta functions in G:\n% dg * (f + df/2);\nh = convDeltas(deltaMagG, deltaLocG, f, a, b, deltaTol, h);\n\n% Check for emptiness:\nif ( isempty(h) )\n h = {fun.constructor(0, struct('domain', [a, b]))};\n return\nend\n\n%% Make sure that h is a cell array with non-overlapping funs.\n\n% First extract the breakpints from funs forming h:\ndoms = cellfun(@(hk) hk.domain, h, 'uniformoutput', 0);\nbreakPoints = sort(unique(horzcat(doms{:})));\n\n% Coalesce breakpoints that are extremely close together.\nif ( any(isinf(breakPoints)) )\n tol = 2*eps; % hscale of functions on unbounded domains is 1.\nelse\n tol = 2*eps*norm(breakPoints, Inf);\nend\n\n% TODO: Take the average of points which are close together instead of just\n% picking one more or less arbitrarily?\ncloseBreaks = abs(diff(breakPoints)) < tol;\nbreakPoints(closeBreaks) = [];\n\n% Restrict each FUN to lie within the new breakpoints.\nnFuns = length(h);\nH = {};\ndeltaTol = pref.deltaPrefs.proximityTol;\nfor k = 1:nFuns\n hk = h{k};\n dom = hk.domain;\n\n % The domain endpoints of each computed FUN must lie _exactly_ within the\n % set of breakpoints or RESTRICT will fail.\n idx1 = find(abs(breakPoints - dom(1)) < tol);\n idx2 = find(abs(breakPoints - dom(2)) < tol);\n hk = changeMap(hk, breakPoints([idx1, idx2]));\n\n % If we just changed the map of a DELTAFUN, the locations of deltas at the\n % domain endpoints also need to be updated.\n if ( isa(hk, 'deltafun') )\n deltaLoc = hk.deltaLoc;\n domk = hk.domain;\n if( ~isempty(deltaLoc) )\n if ( abs(deltaLoc(1) - domk(1) ) < deltaTol )\n deltaLoc(1) = domk(1);\n end\n if ( abs(deltaLoc(end) - domk(2)) < deltaTol )\n deltaLoc(end) = domk(2);\n end\n hk.deltaLoc = deltaLoc;\n end\n end\n\n % Do the restriction.\n hk = restrict(hk, breakPoints(idx1:idx2));\n if ( ~isa(hk, 'cell') )\n hk = {hk};\n end\n H = [H, hk]; %#ok\nend\n\n% If H has the same number of funs, nothing further needs to be done:\nif ( length(H) == length(breakPoints) - 1 )\n return\nend\n\n% H has more funs as a result of restrict. Re-initialize h with 0 BNDFUNS:\nnFuns = length(breakPoints) - 1;\nh = {};\nfor k = 1:nFuns\n data.domain = breakPoints(k:k+1);\n h = [h, {bndfun(0, data)}]; %#ok\nend\n\n% Loop through H and add each fun to the relevant domain piece in h:\nfor k = 1:length(H)\n hk = H{k};\n dom = hk.domain;\n if ( abs(dom(2) - dom(1)) > tol )\n idx = find(breakPoints == dom(1));\n h{idx} = h{idx} + hk; %#ok\n end\nend\n\nend\n\nfunction h = convDeltas(deltaMagF, deltaLocF, g, c, d, deltaTol, h)\n% H = CONVDELTAS() convolves the function G with deltafunctions described by\n% deltaMagF and deltaLocF. G originally lives on [c, d] and the output is\n% returned in H. This function is called twice so deltafunctions in g are \n% scaled by half to get the correct delta-delta contributions.\n\n%%\n% Contributions due to deltafunctions in F:\n% df * (g + dg/2):\n[m, n] = size(deltaMagF);\n% Loop through the delta function matrix:\nfor i = 1:m\n for j = 1:n\n if ( abs(deltaMagF(i, j)) > deltaTol )\n % Take appropriate derivative, scale and shift the function:\n hij = deltaMagF(i, j) * changeMap(diff(g,i-1), deltaLocF(j) + [c d]);\n % The half below is to make sure that delta-delta interaction\n % is not counted twice:\n if ( isa(hij, 'deltafun') )\n hij.deltaMag = hij.deltaMag/2; \n end\n \n % If the result is non-zero, append it:\n if ( ~iszero(hij) )\n h = [h, {hij}]; %#ok\n end\n end\n end\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@deltafun/conv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3938963228916901}}
{"text": "function [pred, accuracy] = cosmo_crossvalidate(ds, classifier, partitions, opt)\n% performs cross-validation using a classifier\n%\n% [pred, accuracy] = cosmo_crossvalidate(dataset, classifier, partitions, opt)\n%\n% Inputs\n% ds struct with fields .samples (PxQ for P samples and\n% Q features) and .sa.targets (Px1 labels of samples)\n% classifier function handle to classifier, e.g.\n% @classify_naive_baysian\n% partitions For example the output from nfold_partition\n% opt optional struct with options for classifier\n% .normalization optional, one of 'zscore','demean','scale_unit'\n% to normalize the data prior to classification using\n% zscoring, demeaning or scaling to [-1,1] along the\n% first dimension of ds. Normalization\n% parameters are estimated using the training data\n% and applied to the testing data.\n% .pca_explained_count optional, transform the data with PCA prior to\n% classification, and retain this number of\n% components\n% .pca_explained_ratio optional, transform the data with PCA prior to\n% classification, and retain the components that\n% explain this percentage of the variance\n% (value between 0-1)\n% .check_partitions optional (default: true). If set to false then\n% partitions are not checked for being set properly.\n% .average_train_X average the samples in the train set using\n% cosmo_average_samples. For X, use any parameter\n% supported by cosmo_average_samples, i.e. either\n% 'count' or 'ratio', and optionally, 'resamplings'\n% or 'repeats'.\n%\n% Output\n% pred Qx1 array with predicted class labels.\n% elements with no predictions have the value NaN.\n% accuracy scalar classification accuracy\n% test_chunks Qx1 array with chunks of input dataset, if each\n% prediction was based using a single classification\n% step. Predictions with no or more than one\n% classification step are set to NaN\n%\n% Examples:\n% % generate dataset with 3 targets and 4 chunks, first target is 3\n% ds=cosmo_synthetic_dataset('ntargets',3,'nchunks',4,'target1',3);\n% % use take-1-chunk for testing crossvalidation\n% partitions=cosmo_nfold_partitioner(ds);\n% classifier=@cosmo_classify_naive_bayes;\n% % run crossvalidation\n% [pred,accuracy]=cosmo_crossvalidate(ds, classifier, ...\n% partitions);\n% % show targets, chunks, and predictions labels for each of the\n% % four folds\n% cosmo_disp({ds.sa.targets,ds.sa.chunks,pred},'threshold',inf)\n% %|| { [ 3 [ 1 [ 3 NaN NaN NaN\n% %|| 4 1 4 NaN NaN NaN\n% %|| 5 1 5 NaN NaN NaN\n% %|| 3 2 NaN 3 NaN NaN\n% %|| 4 2 NaN 5 NaN NaN\n% %|| 5 2 NaN 5 NaN NaN\n% %|| 3 3 NaN NaN 3 NaN\n% %|| 4 3 NaN NaN 4 NaN\n% %|| 5 3 NaN NaN 5 NaN\n% %|| 3 4 NaN NaN NaN 3\n% %|| 4 4 NaN NaN NaN 4\n% %|| 5 ] 4 ] NaN NaN NaN 5 ] }\n% cosmo_disp(accuracy)\n% %|| 0.917\n% %\n% % use take-2-chunks out for testing crossvalidation, LDA classifier\n% partitions=cosmo_nchoosek_partitioner(ds,2);\n% classifier=@cosmo_classify_lda;\n% % run crossvalidation\n% [pred,accuracy]=cosmo_crossvalidate(ds, classifier, ...\n% partitions);\n% % show targets, chunks, and predictions labels for each of the\n% % four folds\n% cosmo_disp({ds.sa.targets,ds.sa.chunks,pred},'threshold',inf)\n% %|| { [ 3 [ 1 [ 5 5 3 NaN NaN NaN\n% %|| 4 1 4 4 4 NaN NaN NaN\n% %|| 5 1 5 5 4 NaN NaN NaN\n% %|| 3 2 3 NaN NaN 3 3 NaN\n% %|| 4 2 4 NaN NaN 4 4 NaN\n% %|| 5 2 5 NaN NaN 4 5 NaN\n% %|| 3 3 NaN 5 NaN 3 NaN 3\n% %|| 4 3 NaN 4 NaN 4 NaN 4\n% %|| 5 3 NaN 5 NaN 5 NaN 5\n% %|| 3 4 NaN NaN 3 NaN 3 3\n% %|| 4 4 NaN NaN 4 NaN 4 5\n% %|| 5 ] 4 ] NaN NaN 5 NaN 3 3 ] }\n% cosmo_disp(accuracy)\n% %|| 0.778\n% %\n% % as the example above, but (1) use z-scoring on each training set\n% % and apply the estimated mean and std to the test set, and (2)\n% % use odd-even partitioner\n% opt=struct();\n% opt.normalization='zscore';\n% partitions=cosmo_oddeven_partitioner(ds);\n% % run crossvalidation\n% [pred,accuracy]=cosmo_crossvalidate(ds, classifier, ...\n% partitions, opt);\n% % show targets, predicted labels, and accuracy\n% cosmo_disp({ds.sa.targets,ds.sa.chunks,pred},'threshold',inf)\n% %|| { [ 3 [ 1 [ NaN 5\n% %|| 4 1 NaN 4\n% %|| 5 1 NaN 5\n% %|| 3 2 3 NaN\n% %|| 4 2 4 NaN\n% %|| 5 2 5 NaN\n% %|| 3 3 NaN 5\n% %|| 4 3 NaN 4\n% %|| 5 3 NaN 5\n% %|| 3 4 3 NaN\n% %|| 4 4 4 NaN\n% %|| 5 ] 4 ] 3 NaN ] }\n% cosmo_disp(accuracy)\n% %|| 0.75\n%\n% Notes:\n% - to apply this to a dataset struct as a measure (for searchlights),\n% consider using cosmo_crossvalidation_measure\n% - to average samples in the training set prior to training, use the\n% options provided by cosmo_average_samples prefixed by\n% 'average_train_'. For example, to take averages of 5 samples, and use\n% each sample in the input approximately 4 times, use:\n% opt.average_train_count=5;\n% opt.average_train_resamplings=4;\n%\n% See also: cosmo_crossvalidation_measure, cosmo_average_samples\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n if nargin<4,opt=struct(); end\n if ~isfield(opt, 'normalization'),\n opt.normalization=[];\n end\n if ~isfield(opt, 'check_partitions'),\n opt.check_partitions=true;\n end\n\n if ~isempty(opt.normalization);\n normalization=opt.normalization;\n opt.autoscale=false; % disable for {matlab,lib}svm classifiers\n else\n normalization=[];\n end\n\n if all(isfield(opt, {'pca_explained_count','pca_explained_ratio'}))\n error(['pca_explained_count and pca_explained_ratio are ' ...\n 'mutually exclusive'])\n elseif isfield(opt, 'pca_explained_count');\n arg_pca='pca_explained_count';\n arg_pca_value=opt.pca_explained_count;\n elseif isfield(opt, 'pca_explained_ratio');\n arg_pca='pca_explained_ratio';\n arg_pca_value=opt.pca_explained_ratio;\n else\n arg_pca=[];\n end\n\n if opt.check_partitions\n cosmo_check_partitions(partitions, ds);\n end\n\n % see if samples in training set are to be averaged\n [do_average_train, average_train_opt]=get_average_train_opt(opt);\n\n train_indices = partitions.train_indices;\n test_indices = partitions.test_indices;\n\n npartitions=numel(train_indices);\n\n nsamples=size(ds.samples,1);\n\n % space for output (one column per partition)\n % the k-th column contains predictions for the k-th fold\n % (with values of NaNs if there was no prediction)\n pred=NaN(nsamples,npartitions);\n\n targets=ds.sa.targets;\n\n % process each fold\n for fold=1:npartitions\n train_idxs=train_indices{fold};\n test_idxs=test_indices{fold};\n % for each partition get the training and test data, store in\n % train_data and test_data\n train_data = ds.samples(train_idxs,:);\n train_targets = targets(train_idxs);\n\n if do_average_train\n % make a minimal dataset, then use cosmo_average_samples to\n % compute averages\n n_train=numel(train_idxs);\n ds_train=struct();\n ds_train.samples=train_data;\n ds_train.sa.chunks=ones(n_train,1);\n ds_train.sa.targets=train_targets;\n\n ds_train_avg=cosmo_average_samples(ds_train,average_train_opt);\n train_data=ds_train_avg.samples;\n train_targets=ds_train_avg.sa.targets;\n end\n\n test_data = ds.samples(test_idxs,:);\n\n % apply pca\n if ~isempty(arg_pca)\n [train_data,pca_params]=cosmo_map_pca(train_data,...\n arg_pca,arg_pca_value);\n test_data=cosmo_map_pca(test_data,'pca_params',pca_params);\n end\n\n % apply normalization\n if ~isempty(normalization)\n [train_data,params]=cosmo_normalize(train_data,normalization);\n test_data=cosmo_normalize(test_data,params);\n end\n\n % then get predictions for the training samples using\n % the classifier, and store these in the k-th column of all_pred.\n p = classifier(train_data, train_targets, test_data, opt);\n\n pred(test_idxs,fold) = p;\n end\n\n % compute accuracies\n has_prediction_mask=~isnan(pred);\n correct_mask=bsxfun(@eq,targets,pred) & has_prediction_mask;\n\n accuracy=sum(correct_mask)/sum(has_prediction_mask);\n\nfunction [do_average_train, average_train_opt]=get_average_train_opt(opt)\n persistent cached_opt;\n persistent cached_do_average_train;\n persistent cached_average_train_opt;\n\n if ~isequal(cached_opt,opt)\n cached_average_train_opt=struct();\n cached_do_average_train=false;\n prefix='average_train_';\n keys=fieldnames(opt);\n for k=1:numel(keys)\n key=keys{k};\n sp=cosmo_strsplit(key,prefix);\n if isempty(sp{1})\n % starts with average_train, so take the rest of the key\n % and flag cached_do_average_train\n cached_average_train_opt.(sp{2})=opt.(key);\n cached_do_average_train=true;\n end\n end\n\n cached_opt=opt;\n end\n\n\n do_average_train=cached_do_average_train;\n average_train_opt=cached_average_train_opt;\n\n\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_crossvalidate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.39364311853287776}}
{"text": "%IM_BOX Fixed mapping determining a rectangular enclosing a blob (0/1 image)\n%\n% B = IM_BOX(A)\n% B = A*IM_BOX\n%\n% If A is a 0/1 image then B is the same image with all empty (0) border\n% columns and rows removed.\n%\n% B = IM_BOX(A,N)\n%\n% If A is a 0/1 image then B is the same image, but having in each direction\n% N empty (0) columns and rows around the object (1).\n%\n% B = IM_BOX(A,[NX1 NX2 NY1 NY2])\n%\n% If A is a 0/1 image then B is the same image, but having NX1, NX2 empty \n% columns (0) left, respectively right of the object (1) and NY1, NY2 empty\n% rows (0) above, respectively below the object(1).\n%\n% B = IM_BOX(A,N,ALF)\n%\n% Adds as many empty (0) columns or rows such that the aspect ratio of\n% images (height/width) equals ALF. For ALF == 1, square images are returned.\n% For ALF == 0, images are taken as they are and N rows and columns are\n% added.\n%\n% EXAMPLE\n% prdatafiles; % make sure prdatafiles is in the path\n% x = kimia_images; % load kimia images\n% x = x*im_box(0); % remove all empty rows and columns\n% x = x*im_box(0,1); % add rows/columns to make images square\n% x = x*im_resize([32 32]); % resample them \n% x = x*im_box(1,0); % add rows/columns and keep image square\n% % now all images are 34x34 and no object touches the border.\n% show(gendat(x,4)) % show a few\n%\n% SEE ALSO (PRTools Guide)\n% DATASETS, DATAFILES\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction [b,J] = im_box(varargin)\n\n\targin = shiftargin(varargin,'vector');\n argin = setdefaults(argin,[],[],[]);\n if mapping_task(argin,'definition')\n b = define_mapping(argin,'fixed');\n b = setname(b,'Image bounding box');\n else\n [a,n,alf] = deal(argin{:});\n if isdataset(a)\n error('Command cannot be used for datasets as it may change image size')\n elseif isdatafile(a)\n isobjim(a);\n b = filtim(a,mfilename,{n,alf});\n %b = setfeatsize(b,getfeatsize(a));\n elseif isa(a,'double') || isa(a,'dip_image') % here we have a single image\n if isa(a,'dip_image'), a = double(a); end\n if isempty(n)\n jx = find(sum(a,1) ~= 0);\n jy = find(sum(a,2) ~= 0);\n J = [min(jy),max(jy),min(jx),max(jx)];\n b = a(min(jy):max(jy),min(jx):max(jx));\n else\n if (~isempty(alf) && alf == 0)\n c = a;\n else\n c = feval(mfilename,a); \n end\n [my,mx] = size(c);\n if length(n) == 1\n \tn = [n n n n];\n elseif length(n) ~= 4\n \terror('Second parameter should be scalar or vector of length 4')\n end\n b = zeros(my+n(3)+n(4),mx+n(1)+n(2));\n b(n(3)+1:n(3)+my,n(1)+1:n(1)+mx) = c;\n end\n if ~isempty(alf) && alf ~= 0\n [m,k] = size(b);\n r = round(m*alf) - k;\n if r == 0\n ;\n elseif r >= 1 % add r columns\n c = zeros(m,k+r);\n c(:,ceil(r/2):ceil(r/2)+k-1) = b;\n b = c;\n else % add rows\n r = round(k/alf) - m;\n c = zeros(m+r,k);\n c(ceil(r/2):ceil(r/2)+m-1,:) = b;\n b = c;\n end\n end\n\t\tend\t \n\tend\n\nreturn", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/im_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521102, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3936431185328777}}
{"text": "% Usage: [xopt, fmin, retcode] = nlopt_minimize_constrained\n% (algorithm, f, f_data,\n% fc, fc_data, lb, ub,\n% xinit, stop)\n%\n% Minimizes a nonlinear multivariable function f(x, f_data{:}), subject\n% to nonlinear constraints described by fc and fc_data (see below), where\n% x is a row vector, returning the optimal x found (xopt) along with\n% the minimum function value (fmin = f(xopt)) and a return code (retcode).\n% A variety of local and global optimization algorithms can be used,\n% as specified by the algorithm parameter described below. lb and ub\n% are row vectors giving the upper and lower bounds on x, xinit is\n% a row vector giving the initial guess for x, and stop is a struct\n% containing termination conditions (see below).\n%\n% This function is a front-end for the external routine\n% nlopt_minimize_constrained in the free NLopt nonlinear-optimization\n% library, which is a wrapper around a number of free/open-source\n% optimization subroutines. More details can be found on the NLopt\n% web page (ab-initio.mit.edu/nlopt) and also under\n% 'man nlopt_minimize_constrained' on Unix.\n%\n% f should be a handle (@) to a function of the form:\n%\n% [val, gradient] = f(x, ...)\n%\n% where x is a row vector, val is the function value f(x), and gradient\n% is a row vector giving the gradient of the function with respect to x.\n% The gradient is only used for gradient-based optimization algorithms;\n% some of the algorithms (below) are derivative-free and only require\n% f to return val (its value). f can take additional arguments (...)\n% which are passed via the argument f_data: f_data is a cell array\n% of the additional arguments to pass to f. (Recall that cell arrays\n% are specified by curly brackets { ... }. For example, pass f_data={}\n% for functions that require no additional arguments.)\n%\n% A few of the algorithms (below) support nonlinear constraints,\n% in particular NLOPT_LD_MMA and NLOPT_LN_COBYLA. These (if any)\n% are specified by fc and fc_data. fc is a cell array of\n% function handles, and fc_data is a cell array of cell arrays of the\n% corresponding arguments. Both must have the same length m, the\n% number of nonlinear constraints. That is, fc{i} is a handle\n% to a function of the form:\n%\n% [val, gradient] = fc(x, ...)\n%\n% (where the gradient is only used for gradient-based algorithms),\n% and the ... arguments are given by fc_data{i}{:}.\n%\n% If you have no nonlinear constraints, i.e. fc = fc_data = {}, then\n% it is equivalent to calling the the nlopt_minimize() function, \n% which omits the fc and fc_data arguments.\n%\n% stop describes the termination criteria, and is a struct with a\n% number of optional fields:\n% stop.ftol_rel = fractional tolerance on function value\n% stop.ftol_abs = absolute tolerance on function value\n% stop.xtol_rel = fractional tolerance on x\n% stop.xtol_abs = row vector of absolute tolerances on x components\n% stop.fmin_max = stop when f < fmin_max is found\n% stop.maxeval = maximum number of function evaluations\n% stop.maxtime = maximum run time in seconds\n% stop.verbose = > 0 indicates verbose output\n% Minimization stops when any one of these conditions is met; any\n% condition that is omitted from stop will be ignored. WARNING:\n% not all algorithms interpret the stopping criteria in exactly the\n% same way, and in any case ftol/xtol specify only a crude estimate\n% for the accuracy of the minimum function value/x.\n%\n% The algorithm should be one of the following constants (name and\n% interpretation are the same as for the C function). Names with\n% _G*_ are global optimization, and names with _L*_ are local\n% optimization. Names with _*N_ are derivative-free, while names\n% with _*D_ are gradient-based algorithms. Algorithms:\n%\n% NLOPT_GD_MLSL_LDS, NLOPT_GD_MLSL, NLOPT_GD_STOGO, NLOPT_GD_STOGO_RAND, \n% NLOPT_GN_CRS2_LM, NLOPT_GN_DIRECT_L, NLOPT_GN_DIRECT_L_NOSCAL, \n% NLOPT_GN_DIRECT_L_RAND, NLOPT_GN_DIRECT_L_RAND_NOSCAL, NLOPT_GN_DIRECT, \n% NLOPT_GN_DIRECT_NOSCAL, NLOPT_GN_ISRES, NLOPT_GN_MLSL_LDS, NLOPT_GN_MLSL, \n% NLOPT_GN_ORIG_DIRECT_L, NLOPT_GN_ORIG_DIRECT, NLOPT_LD_AUGLAG_EQ, \n% NLOPT_LD_AUGLAG, NLOPT_LD_LBFGS, NLOPT_LD_LBFGS_NOCEDAL, NLOPT_LD_MMA, \n% NLOPT_LD_TNEWTON, NLOPT_LD_TNEWTON_PRECOND, \n% NLOPT_LD_TNEWTON_PRECOND_RESTART, NLOPT_LD_TNEWTON_RESTART, \n% NLOPT_LD_VAR1, NLOPT_LD_VAR2, NLOPT_LN_AUGLAG_EQ, NLOPT_LN_AUGLAG, \n% NLOPT_LN_BOBYQA, NLOPT_LN_COBYLA, NLOPT_LN_NELDERMEAD, \n% NLOPT_LN_NEWUOA_BOUND, NLOPT_LN_NEWUOA, NLOPT_LN_PRAXIS, NLOPT_LN_SBPLX\n%\n% For more information on individual algorithms, see their individual\n% help pages (e.g. \"help NLOPT_LN_SBPLX\").\nfunction [xopt, fmin, retcode] = nlopt_minimize_constrained(algorithm, f, f_data, fc, fc_data, lb, ub, xinit, stop)\n\nopt = stop;\nif (isfield(stop, 'minf_max'))\n opt.stopval = stop.minf_max;\nend\nopt.algorithm = algorithm;\nopt.min_objective = @(x) f(x, f_data{:});\nopt.lower_bounds = lb;\nopt.upper_bounds = ub;\n% opt.local_optimizer = alg;\n% for i = 1:length(fc)\n% opt.fc{i} = @(x) fc{i}(x, fc_data{i}{:});\n% end\nopt.fc = fc;\n[xopt, fmin, retcode] = nlopt(opt, xinit);\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/nlopt/distribution/nlopt_minimize_constrained.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3935143835758716}}
{"text": " function xs = tpl_inc(x, Gb, yi, bi, ri, R, niter, pixmax, curv, ...\n\t\tsubout, enhance, gi, denom, relax0, chat)\n%function xs = tpl_inc(x, Gb, yi, bi, ri, R, niter, pixmax, curv, ...\n%\t\tsubout, enhance, gi, denom, relax0, chat)\n%\n% TRIOT: incremental SPS algorithm for transmission Poisson problem\n% (ordered subsets separable paraboloidal surrogates)\n% in\n%\tx\t[np,1]\t\tinitial estimate\n%\tGb\t\t\tGblock object (see tpl_os_sps_test.m)\n%\tyi,bi,ri [nb,na]\tsee tr_fbp.m (for model too)\n%\tR\t\tpenalty structure (see Robject.m)\n%\t\t\t\t(or empty for ML case)\n%\tniter\t\t# iterations\n%\tpixmax\t\tupper constraint for pixel values or [lower, upper]\n%\t\t\tcan be scalar (e.g. 'inf') or an array the size of x\n%\tcurv\t\t'oc' for erdogan's optimal curvatures\n%\t\t\t'mc' for maximum curvature\n%\t\t\t'pc' for erdogan's fast precomputed curvatures,\n%\t\t\t\twhich usually provides faster convergence,\n%\t\t\t\tbut can be nonmonotone.\n%\tsubout\t[1]\tnonzero value: return all subiterates\n%\t\t\totherwise, return only iterates\n%\tenhance [1]\tnonzero value: Hsiao's enhancement\n%\t\t\totherwise, no enhancement\n%\tgi\t[nd,1]\tsum(G')'\n%\tdenom\t[np,1]\t\t(if precomputed denominator)\n%\trelax0\t[1] or [2]\trelax0 or (relax0, relax_rate)\n% out\n%\txs [np,niter]\tupdated image vectors each iteration\n%\n% Copyright Mar 2000, Jeff Fessler, The University of Michigan\n% 2002-2-20 update for Gblock object\n% Modified for incremental version by Sangtae Ahn, from ~sangtaea/trans.\n\nepsilon = 1e-10;\n\nif nargin < 3, ir_usage, end\n\nGb = block_ob(Gb, 'ensure'); % make it a block object (if not already)\nnblock = block_ob(Gb, 'n');\nstarts = subset_start(nblock);\n\nif ~isvar('bi') || isempty(bi)\n\tbi = ones(size(yi));\nend\nif ~isvar('ri') || isempty(ri)\n\tri = zeros(size(yi));\nend\n\nif ~isvar('R'), R = []; end\nif ~isvar('niter')\t|| isempty(niter),\tniter = 2;\tend\nif ~isvar('pixmax')\t|| isempty(pixmax),\tpixmax = inf;\tend\nif length(pixmax) == 2\n\tpixmin = pixmax(1);\n\tpixmax = pixmax(2);\nelse\n\tpixmin = 0;\nend\nif ~isvar('curv')\t|| isempty(curv),\tcurv = 'oc';\tend\nif ~isvar('subout')\t|| isempty(subout),\tsubout = 0;\tend\nif ~isvar('enhance')\t|| isempty(enhance),\tenhance = 0;\tend\nif ~isvar('chat')\t|| isempty(chat),\tchat = false;\tend\nif ~isvar('relax0')\t|| isempty(relax0),\trelax0 = 1;\tend\n\nif streq(curv, 'mc')\n\tsubscale = @(iset) iset;\nelse\n\tsubscale = @(iset) 1;\nend\n\nif length(relax0) == 1\n\trelax_rate = 0;\nelseif length(relax0) == 2\n\trelax_rate = relax0(2);\n\trelax0 = relax0(1);\nelse\n\terror relax\nend\n\nif length(niter) == 2\n\tosspsiter = niter(1);\n\tniter = niter(2);\nelse\n\tosspsiter = 1;\nend\n\ntrl_check(yi, bi, ri);\n\nif ~isvar('gi') || isempty(gi)\n\tgi = reshape(sum(Gb'), size(yi));\t% g_i = sum_j g_ij\nend\n\nstarts = subset_start(nblock);\n[nb na] = size(yi);\n\n% precompute denominator if needed\nif (~isvar('denom') || isempty(denom)) && (streq(curv, 'pc') || streq(curv, 'mc'))\n\tni = my_trl_curvature(yi, bi, ri, [], curv); % precomputed curvatures\n\t%\n\t% separate denominators for each subset\n\t%\n\tif streq(curv, 'mc')\n\t\tdenom = zeros(numel(x), nblock);\n\t\tfor iset=1:nblock\n\t\t\tiblock = starts(iset);\n\t\t\tia = iblock:nblock:na;\n\t\t\tdenom(:,iset) = Gb{iblock}' * col(gi(:,ia) .* ni(:,ia));\n\t\tend\n\telse\n\t%\n\t% one denominator shared by all subsets\n\t%\n\t\tdenom = Gb' * col(gi .* ni) / nblock;\n\tend\nend\n\n% \"precomputed curvature\"\nif ~streq(curv, 'pc')\n\tni = my_trl_curvature(yi, bi, ri, [], 'pc');\n\tdenom_pc = Gb' * col(gi .* ni) / nblock;\nelse\n\tdenom_pc = denom;\nend\n\n\nif subout\n\txs = zeros(length(x), (niter-1)*nblock+1);\nelse\n\txs = zeros(length(x), niter);\nend\n\nx = max(x,pixmin);\nx = min(x,pixmax);\nxs(:,1) = x;\nif subout, idx = 2; end\nnum_store = zeros(length(x), nblock);\nden_store = zeros(length(x), nblock);\n\n%\n% initialization by os-sps-pc\n%\nfor iter = 1:osspsiter\n\tfor iset=1:nblock\n\t\tiblock = starts(iset);\n\t\tia = iblock:nblock:na;\n\n\t\tli = Gb{iblock} * x;\t% l=G*x \"line integrals\"\n\t\tli = reshape(li, nb, length(ia));\n\t\tbel = bi(:,ia) .* exp(-li);\n\t\tyb = bel + ri(:,ia);\t% predicted meas. means\n\t\tdothi = (1 - yi(:,ia) ./ yb) .* bel;\n\n\t\tif streq(curv, 'oc')\n\t\t\tni = my_trl_curvature(yi(:,ia), bi(:,ia), ri(:,ia), ...\n\t\t\t\tli, 'oc');\n\t\t\tdenom = Gb{iblock}' * col(gi(:,ia) .* ni);\n\t\tend\n\n\t\tif isempty(R)\n\t\t\tgrad = Gb{iblock}' * dothi(:);\n\t\t\tden_osps = max(denom_pc, epsilon);\n\t\t\tden_store(:, iset) = max(denom(:,subscale(iset)), ...\n\t\t\t\t\t\tepsilon);\n\t\telse\n\t\t\tgrad = Gb{iblock}' * dothi(:) - R.cgrad(R, x)/nblock;\n\t\t\tden_osps = max(denom_pc + R.denom(R, x)/nblock, ...\n\t\t\t\t\tepsilon);\n\t\t\tden_store(:, iset) = max(denom(:,subscale(iset)) + ...\n\t\t\t\t\tR.denom(R, x)/nblock, epsilon);\n\t\tend\n\n\t\tif iter == osspsiter\n\t\t\tnum_store(:, iset) = x.*den_store(:, iset) + grad;\n\t\tend\n\t\tx = x + grad ./ den_osps;\n\t\tx = max(x,pixmin);\n\t\tx = min(x,pixmax);\n\t\tif subout\n\t\t\txs(:,idx) = x;\n\t\t\tidx = idx + 1;\n\t\tend\n\tend\n\tif ~subout, xs(:,iter+1) = x;\tend\nend\nnum = sum(num_store, 2);\nden = sum(den_store, 2);\n\nif 1,\t\t% optional\n\tx = num ./ den;\n\tx = max(x,pixmin); x = min(x,pixmax);\n\tif subout\n\t\txs(:,idx-1) = x;\n\telse\n\t\txs(:,iter+1) = x;\n\tend\nend\n\n\nalphidx = 1;\nfor iter = (osspsiter+2):niter\n\tticker(mfilename, iter, niter)\n\n\trelax = relax0 / (1 + relax_rate * (iter-2));\n\n\t%\n\t% loop over subsets\n\t%\n\tfor iset=1:nblock\n\t\tiblock = starts(iset);\n\t\tia = iblock:nblock:na;\n\n\t\tli = Gb{iblock} * x;\t% l=G*x \"line integrals\"\n\t\tli = reshape(li, nb, length(ia));\n\t\tbel = bi(:,ia) .* exp(-li);\n\t\tyb = bel + ri(:,ia);\t% predicted meas. means\n\t\tdothi = (1 - yi(:,ia) ./ yb) .* bel;\n\n\t\t% optimal curvatures (for ensured monotone increase)\n\t\tif streq(curv, 'oc')\n\t\t\tni = my_trl_curvature(yi(:,ia), bi(:,ia), ri(:,ia), ...\n\t\t\t\tli, 'oc');\n\t\t\tdenom = Gb{iblock}' * col(gi(:,ia) .* ni);\n\t\tend\n\n\t\tnum = num - num_store(:, iset);\n\t\tden = den - den_store(:, iset);\n\n\t\tif isempty(R)\n\t\t\tgrad = Gb{iblock}' * dothi(:);\n\t\t\tden_store(:, iset) = max(denom(:,subscale(iset)), ...\n\t\t\t\t\t\tepsilon);\n\t\telse\n\t\t\tgrad = Gb{iblock}' * dothi(:) - R.cgrad(R, x)/nblock;\n\t\t\tden_store(:, iset) = max(denom(:,subscale(iset)) + ...\n\t\t\t\t\t\tR.denom(R, x)/nblock, epsilon);\n\t\tend\n\n\t\tnum_store(:, iset) = x.*den_store(:, iset) + grad;\n\n\t\tnum = num + num_store(:, iset);\n\t\tden = den + den_store(:, iset);\n\n\t\txold = x;\n\n\t\tx = num ./ den;\n\t\tx = max(x,pixmin); x = min(x,pixmax);\n\n\t\tif enhance\n\t\t\txos = xold + grad ./ (den_store(:,iset) - ...\n\t\t\t\tdenom(:,subscale(iset)) + denom_pc);\n\t\t\txos = max(xos,pixmin);\n\t\t\txos = min(xos,pixmax);\n\n\t\t\tc2 = - sum((xos - x).^2 .* den) / 2;\n\t\t\tc1 = num'*(xos - x) - sum(x.*(xos-x).*den);\n\t\t\tc0 = num'*(x - xold) - sum(x.^2.*den - xold.^2.*den)/2;\n\n\t\t\tif 1\n\t\t\t\tif c0+c1+c2 > 0\n\t\t\t\t\talpha = 1;\n\t\t\t\telse\n\t\t\t\t\talpha = eql_root(-c2, -c1/2, 0.95*c0);\n\t\t\t\t\talpha = min(1, alpha);\n\t\t\t\t\talpha = max(0, alpha);\n\t\t\t\tend\n\t\t\telse\n\t\t\t\talpha = 1/0.9;\n\t\t\t\tdel_obj = -999;\n\t\t\t\twhile (del_obj <=0) & (alpha > 0.0096)\n\t\t\t\t\talpha = alpha * 0.9;\n\t\t\t\t\tdel_obj = c2*alpha^2 + c1*alpha + c0;\n\t\t\t\tend\n\n\t\t\t\tif alpha <= 0.0096, alpha = 0; end\n\t\t\tend\n\n\t\t\tx = (1-alpha)*x + alpha*xos;\n\t\t\talph(alphidx) = alpha;\n\t\t\talphidx = alphidx + 1;\n\n\t\tend\n\n\t\tif subout\n\t\t\txs(:,idx) = x;\n\t\t\tidx = idx + 1;\n\t\tend\n\tend\n\n\tif chat, printf('Range %g %g', min(x), max(x)), end\n\tif ~subout, xs(:,iter) = x; end\nend\n\n%figure, plot(alph, 'o-')\n\nfunction obj = trl_obj(alpha, xinc, xos, linc, los, yi, bi, ri, R)\n\nx = alpha*xos + (1 - alpha)*xinc;\nli = alpha*los + (1 - alpha)*linc;\nyp = bi .* exp(-li) + ri;\nlike = sum(yi .* log(yp) - yp);\npenal = sum(R.penal(R, x));\nobj = like - penal;\nobj = -obj;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/transmission/tpl_inc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3935054579995117}}
{"text": "% [template t2 valid] = PPG_SQI(wave,anntime,annot,template_ahead,windowlen,Fs)\n% \n% PPG_SQI.m - PPG SQI based on beat template correlation.\n% (as an advice, the algorithm get 30 beats at each call and run in loop)\n% by Qiao Li 30 Mar 2011\n% \n% PPG sampling frequency is Fs\n%\n% input: \n% wave: PPG data; \n% anntime: PPG annotation time (samples), read from ple annot file,\n% But the ann-time is the OFFSET based on wave(1)\n% annot: Annotation of beats, read from from ple annot file\n% directly\n% template: Last PPG beat template \n% windowlen: length of window to calculate template(default: 30s)\n% Fs : sampling frequency (defatult: 125 to work with pervious code)\n% output:\n% annot: ppg sqi annotation\n% annot.typeMnemonic: E - excellent beat; \n% A - acceptable beat; \n% Q - unacceptable beat\n% annot.subtype: SQI based on Direct compare\n% annot.chan: SQI based on Linear resampling\n% annot.num: SQI based on Dynamic time warping\n% annot.auxInfo: SQI based on Clipping detection\n% template: Current PPG beat template\n% valid: 1 or greater for valid template, \n% 0 for invalid template\n%\t\n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n%\n% 12-01-2107 Modified by Giulia Da Poian: replace fixed samplig frequency\n% (125) with a variable Fs\n\nfunction [annot template valid] = PPG_SQI(wave,anntime,annot,template,windowlen,Fs)\n\n if nargin < 6\n Fs =125;\n end\n if nargin < 5\n windowlen=30*Fs;\n end\n if nargin < 4\n template=[];\n end\n if nargin < 3\n sprintf('Error: must provide wave, anntime and annot');\n annot=[];\n template=[];\n valid=0;\n return;\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 19/09/2011 ADD baseline wander filter\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n wave = PPGmedianfilter(wave, Fs,Fs);\n % get PPG template\n [t t2 v]=template_pleth(wave(1:min(windowlen,length(wave))), anntime(find(anntime1\n t=t2;\n end\n \n \n \n % Calculate the PLA of template for dynamic time warping\n d1=t;\n d1=(d1-min(d1))/(max(d1)-min(d1)).*100;\n [y1 pla1]=PLA(d1,1,1);\n\n% Main Loop\n for j=1:length(annot)-1\n\n% SQI1: Direct compare\n\n% Calculate correlation coefficients based on the template\n% length\n beatbegin=anntime(j);\n beatend=anntime(j+1);\n% 07/11/2011 ADD max beat length <= 3s detection \n\t\tif beatend-beatbegin>3*Fs\n\t\t\tbeatend=beatbegin+3*Fs;\n\t\tend\n\t\ttemplatelength=length(t);\n\t\tcomplength=min(templatelength,beatend-beatbegin-1);\n if beatbegin+complength-1 > length(wave) || beatend > length(wave) || beatbegin < 1\n continue;\n end\n currentb=j;\n cc=corrcoef(t(1:complength),wave(beatbegin:beatbegin+complength-1));\n c1(j)=cc(1,2);\n if (c1(j)<0)\n c1(j)=0;\n end\n annot(currentb).subtype=int8(c1(j)*100);\n\n\n% SQI2: Linear resampling\n\n% Calculate correlation coefficients based on the linear\n% resampling (interp1)\n \n y=interp1(1:beatend-beatbegin, wave(beatbegin:beatend-1),1:(beatend-beatbegin-1)/(templatelength-1):(beatend-beatbegin),'spline');\n y(isnan(y))=0;\n cc=corrcoef(t,y);\n c2(j)=cc(1,2);\n if (c2(j)<0)\n c2(j)=0;\n end\n annot(currentb).chan=int8(c2(j)*100);\n\n% SQI3: Dynamic Time Warping \n \n% Calculate correlation coefficients based on the dynamic time\n% warping\n \n d2=wave(beatbegin:beatend-1);\n \n % if beat too long, set SQI=0;\n if (length(d2)>length(d1)*10)\n c3(j)=0;\n else\n d2=(d2-min(d2))/(max(d2)-min(d2)).*100;\n [y2 pla2]=PLA(d2,1,1);\n \n [w ta tb] = simmx_dtw(y1,pla1,y2,pla2);\n [p,q,Dm] = dp_dwt2(w,ta,tb);\n [ym1 ym2 yout1]=draw_dtw(y1,pla1,p,y2,pla2,q);\n cc=corrcoef(y1,ym2);\n c3(j)=cc(1,2);\n if (c3(j)<0)\n c3(j)=0;\n end\n end\n annot(currentb).num=int8(c3(j)*100);\n \n% SQI4: Clipping detection \n\n d2=wave(beatbegin:beatend-1);\n y=diff(d2);\n clipthreshold=0.5;\n c4(j)=int8(length(find(abs(y)>clipthreshold))/length(y)*100);\n \n% SQI: Combined\n\n sqibuf=[annot(currentb).subtype annot(currentb).chan annot(currentb).num c4(j)];\n if min(sqibuf)>=90\n annot(currentb).typeMnemonic='E'; % Excellent\n else\n if length(find(sqibuf>=90))>=3 || (median(sqibuf(1:3))>=80 && sqibuf(1)>=50 && sqibuf(4)>=70) || min(sqibuf)>=70\n annot(currentb).typeMnemonic='A'; % Acceptable\n else\n annot(currentb).typeMnemonic='Q'; % Unacceptable\n end\n end\n annot(currentb).auxInfo=num2str(int8(c4(j)));\n \n end\n\n end\n template=t;\n valid=v;\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/PPG_Tools/PPG_SQI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3935054515464119}}
{"text": "function [gx,dgdx,dgdp] = g_HRF3(Xt,P,ut,in)\n% T2* contrast observation function for HRF Balloon model (log space)\n% function [gx,dgdx,dgdp] = g_HRF3(Xt,P,ut,in)\n% This function evaluates the hemodynamic static observation equation\n% function. HEMODYNAMIC STATES ARE IN LOG SPACE.\n\nn = size(Xt,1);\n\n% Get parameters and states indices\n\ntry; TE = in.TE; catch, TE = 0.04; end\n\nif isfield(in,'fullDCM') && in.fullDCM\n % estimated region-specific resting oxygen extraction fractions\n % NB: if P(in.ind1) = 0, E0 = 0.34.\n% [E0,dsdp] = sigm(P(in.ind1)-0.6633,struct('beta',1,'G0',1,'INV',0));\n% E0 = E0(:);\n E0 = 1./(1+exp(-(P(in.ind1)-0.6633)));\n dsdp = E0.*(1-E0);\n % estimated region-specific ratios of intra- to extravascular\n % components of the gradient echo signal (prior mean = 1, log-normally\n % distributed scaling factor)\n epsilon = exp(P(in.ind2));\n % hemodynamic states indices:\n n1 = in.n1;\n n2 = in.n2;\n n3 = in.n3;\n n4 = in.n4;\n try\n n5 = in.n5;\n nreg = n./5;\n catch\n n5 = [];\n nreg = n./4;\n end\n if isfield(in,'homogeneous') && in.homogeneous\n E0 = E0.*ones(nreg,1);\n dsdp = dsdp.*ones(nreg,1);\n epsilon = epsilon.*ones(nreg,1);\n in.ind1 = [in.ind1:2:2*nreg];\n in.ind2 = [in.ind2:2:2*nreg];\n end\nelse\n [E0,dsdp] = VBA_sigmoid(P(1)-0.6633);\n E0 = E0(:);\n try\n epsilon = exp(P(2));\n p2 = 1;\n catch\n epsilon = 1;\n p2 = 0;\n end\n % hemodynamic states indices:\n n1 = 1;\n n2 = 2;\n n3 = 3;\n n4 = 4;\n nreg = n./4;\nend\n\n%--------------------------------------------------------------------------\n% coefficients in BOLD signal model,...\nV0 = 4; % resting venous volume\nr0 = 25; % intravascular relaxation rate\nnu0 = 40.3; % frequency offset\nk1 = 4.3.*nu0.*E0.*TE;\nk2 = epsilon.*r0.*E0.*TE;\nk3 = 1 - epsilon;\n\n% states ...\nx3 = exp(Xt(n3,:)); % blood volume v(t)\nx4 = exp(Xt(n4,:)); % dHb content q(t)\n\n% ... and derivatives\ndgdx = zeros(n,nreg);\ndgdp = zeros(size(P,1),nreg);\n\n% Evaluate observation function\nx4x3 = exp(log(x4)-log(x3));\ngx = V0.*(k1.*(1-x4) + k2.*(1-x4x3) + k3.*(1-x3));\n\n% Evaluate gradient wrt states and parameters\nfor i=1:nreg\n if isfield(in,'fullDCM') && in.fullDCM\n if isempty(n5)\n dgdx(n1(i):n4(i),i) = [...\n 0; ...\n 0; ...\n -k3(i).*x3(i)+k2(i).*x4x3(i); ...\n -k1(i).*x4(i)-k2(i).*x4x3(i)].*V0;\n else\n dgdx(n1(i):n5(i),i) = [...\n 0; ...\n 0; ...\n -k3(i).*x3(i)+k2(i).*x4x3(i); ...\n -k1(i).*x4(i)-k2(i).*x4x3(i); 0].*V0;\n end\n dgdp(in.ind1(i),i) = V0.*4.3.*nu0.*TE.*(1-x4(i)).*dsdp(i) + ...\n V0.*epsilon(i).*r0.*TE.*(1-x4x3(i)).*dsdp(i);\n dgdp(in.ind2(i),i) = V0.*k2(i).*(1-x4x3(i)) - ...\n V0.*epsilon(i).*(1-x3(i));\n else\n dgdx(n1(i):n4(i),i) = [0; 0; ...\n -k3(i).*x3(i)+k2(i).*x4x3(i); ...\n -k1(i).*x4(i)-k2(i).*x4x3(i)].*V0;\n dgdp = V0.*4.3.*nu0.*TE.*(1-x4(i)).*dsdp(i) + ...\n V0.*epsilon(i).*r0.*TE.*(1-x4x3(i)).*dsdp(i);\n if p2\n dgdp(2) = V0.*k2(i).*(1-x4x3(i)) - ...\n V0.*epsilon(i).*(1-x3(i));\n dgdp = dgdp(:);\n end\n end\nend\n\nif isfield(in,'homogeneous') && in.homogeneous\n dgdp0 = dgdp;\n dgdp = zeros(2,nreg);\n dgdp(1,:) = sum(dgdp0(in.ind1,:),1);\n dgdp(2,:) = sum(dgdp0(in.ind2,:),1);\nend\n\nif isfield(in,'confounds') && ~isempty(in.confounds.X0)\n tsample = ut(in.confounds.indt);\n X0 = kron(eye(nreg),in.confounds.X0(tsample,:));\n gx = gx + X0*P(in.confounds.indp);\n dgdp(in.confounds.indp,:) = X0';\nend\n\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/g_HRF3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3934549684991022}}
{"text": "function [alpha,b,eta,zeta,kappa] = solve_hkl_square_dual_fast(eta,data,Y,lambda,varargin);\n\n\n\n% solve the milasso for a given regularization parameter\nn = size(data.X,1);\np =length(data.affinity);\npX = size(data.X,2);\naffs = data.affinity;\nweights = data.weights;\n\n% optional parameters\nmingap = 1e-3;\ndisplay = 0;\ngapeta = 1e-3;\n\n% READ OPTIONAL PARAMETERS\nargs = varargin;\nnargs = length(args);\nfor i=1:2:nargs\n switch args{i},\n case 'mingap', mingap = args{i+1};\n case 'gapeta', gapeta = args{i+1};\n case 'display', display = args{i+1};\n end\nend\n\n\nif isempty(eta)\n eta = 1/p ./ weights.^2;\nend\nx = eta .* weights.^2;\nx = max(x,0);\nx = x / sum(x);\n\nif display==1\ndisplay = Inf;\nend\nbeta_ARMIJO = .25 ;\nsigma_ARMIJO = .1 ;\nkmax_ARMIJO = 20;\nkmax = 200;\ntol_dx = 1e-8;\nk = 1;\nalpha=1;\n\n% % optimization parameters for the dual problem\n% optparam.tol = 1e-16;\n% optparam.kmax = 200;\n% optparam.tol_df = 1e-20;\n% optparam.display= 0;\nfx0 = Inf;\n\n% solve the regular kernel learning problem\nmY = mean(Y);\n\n\n\n\n\n%nu = 1e-6; % added ridge on kernels\nwhile k<=kmax;\n x = max(x,0);\n x = x / sum(x);\n\n\n % compute value of function\n eta = ( x*(1-gapeta) + gapeta/p )./ weights.^2 ;\n zeta = zeros(p,1);\n for i=1:p\n zeta(affs{i}) = zeta(affs{i}) + 1./eta(i);\n end\n zeta = 1./zeta;\n\n \n \n % solve the regular kernel learning problem\n K = center_gram_matrix(double(devectorize_single( single(data.kernels * zeta ))));\n alphaK = (K + n * lambda * eye(n) ) \\ ( Y - mean(Y) );\n fx = lambda/2 * ( Y - mean(Y))'* alphaK;\n \n \n gradient_zeta = zeros(p,1);\n for i=1:p\n gradient_zeta(i) = - lambda/2 * vectorize_quad_single(data.kernels(:,i),alphaK );\n end\n \n gradient_eta = zeros(p,1);\n for i=1:p;\n gradient_eta(i) = sum( gradient_zeta(affs{i}) .* zeta(affs{i}).^2 ) / eta(i)^2;\n end\n gradient = (1-gapeta) * gradient_eta ./ weights.^2;\n\n % check optimality condition\n optcond = max(x .* ( gradient - min(gradient)));\n if max(x .* ( gradient - min(gradient))) < mingap, break; end\n\n fx0=fx;\n\n % projected gradient\n xbar = x - gradient;\n d = - gradient;\n x0=x;\n ialpha = 1;\n while ialpha= - sigma_ARMIJO * gradient' * ( xalpha - x );\n\n % start to go up\n while ( fx - fxalpha >= - sigma_ARMIJO * gradient' * ( xalpha - x ) ) & ialpha1,\n if mod(k,display)==1\n fprintf('k=%d - f=%f - armijo=%d - dx=%e - gap=%f\\n',k,fx,ialpha,norm(x-x0),optcond);\n\n end\n end\n end\n if norm(x-x0) 1+1e-1, keyboard; end\n\n k=k+1;\nend\n\n\n% if k==kmax+1\n% keyboard;\n% end\n\n\neta = ( x*(1-gapeta) + gapeta/p )./ weights.^2 ;\nzeta = zeros(p,1);\nfor i=1:p\n zeta(affs{i}) = zeta(affs{i}) + 1./eta(i);\nend\nzeta = 1./zeta;\n\n\n K = center_gram_matrix(double(devectorize_single( single(data.kernels * zeta ))));\n alpha = (K + n * lambda * eye(n) ) \\ ( Y - mean(Y) );\n\n pred = K * alpha;\n b=mean(Y-pred );\n \nkappa = zeros(p,p);\nfor i=1:p\n kappa(i,affs{i}) = zeta(affs{i})./eta(i);\nend\n\n if isinf(display)\n fprintf('k=%d - f=%f - gap=%f\\n',k,fx,optcond);\n end\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/hkl-3.0/solve_hkl_square_dual_fast_kernels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.39345141380947707}}
{"text": "function varargout = xyz\n%XYZ Three chebfun3 obejcts of the identity on [-1, 1, -1, 1, -1, 1].\n% CHEB.XYZ is shorthand for the expressions \n% X = CHEBFUN3(@(X,Y,Z) X),\n% Y = CHEBFUN3(@(X,Y,Z) Y), and\n% Z = CHEBFUN3(@(X,Y,Z) Z).\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nx = chebfun3(@(x,y,z) x);\ny = chebfun3(@(x,y,z) y);\nz = chebfun3(@(x,y,z) z);\n\nif nargout>1\n % For the syntax [x,y,z] = cheb.xyz\n varargout{1} = x;\n varargout{2} = y;\n varargout{3} = z;\nelse\n % For the syntax cheb.xyz we still want to put these variables into the\n % workspace:\n assignin('base', 'x', x);\n assignin('base', 'y', y);\n assignin('base', 'z', z);\nend\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/+cheb/xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.393373929649441}}
{"text": "function Offspring = GLMO_SMPSOOperator(Problem, Particle, Pbest, Gbest, numberOfGroups, typeOfGroups)\n% ----------------------------------------------------------------------- \n% Copyright (C) 2020 Heiner Zille\n%\n% This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 \n% International License. (CC BY-NC-SA 4.0). To view a copy of this license, \n% visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or see the \n% pdf-file \"License-CC-BY-NC-SA-4.0.pdf\" that came with this code. \n%\n% You are free to: \n% * Share ? copy and redistribute the material in any medium or format\n% * Adapt ? remix, transform, and build upon the material \n% Under the following terms:\n% * Attribution ? You must give appropriate credit, provide a link to the \n% license, and indicate if changes were made. You may do so in any reasonable \n% manner, but not in any way that suggests the licensor endorses you or your use.\n% * NonCommercial ? You may not use the material for commercial purposes.\n% * ShareAlike ? If you remix, transform, or build upon the material, you must \n% distribute your contributions under the same license as the original.\n% * No additional restrictions ? You may not apply legal terms or technological \n% measures that legally restrict others from doing anything the license permits.\n% \n% Author of this Code: \n% Heiner Zille or \n%\n% This code is based on the following publications:\n%\n% 1) Heiner Zille \n% \"Large-scale Multi-objective Optimisation: New Approaches and a Classification of the State-of-the-Art\" \n% PhD Thesis, Otto von Guericke University Magdeburg, 2019 \n% http://dx.doi.org/10.25673/32063 \n% \n% 2) Heiner Zille, Hisao Ishibuchi, Sanaz Mostaghim and Yusuke Nojima\n% \"Mutation Operators Based on Variable Grouping for Multi-objective Large-scale Optimization\"\n% IEEE Symposium Series on Computational Intelligence (SSCI), IEEE, Athens, Greece, December 2016\n% https://ieeexplore.ieee.org/document/7850214 \n%\n% This file is intended to work with the PlatEMO framework version 2.5. \n% Date of publication of this code: 06.04.2020 \n% Last Update of this code: 06.04.2020\n% A newer version of this algorithm may be available. Please contact the author \n% or see http://www.ci.ovgu.de/Research/Codes.html. \n%\n% The files may have been modified in Feb 2021 by the authors of the Platemo framework to work with the Platemo 3.0 release. \n% -----------------------------------------------------------------------\n% This file is derived from its original version containied in the PlatEMO \n% framework. The original copyright disclaimer can be found below. \n% ----------------------------------------------------------------------- \n\n% Particle swarm optimization in SMPSO\n\n %% Parameter setting\n ParticleDec = Particle.decs;\n PbestDec = Pbest.decs;\n GbestDec = Gbest.decs;\n [N,D] = size(ParticleDec);\n ParticleVel = Particle.adds(zeros(N,D));\n\n %% Particle swarm optimization\n W = repmat(unifrnd(0.1,0.5,N,1),1,D);\n r1 = repmat(rand(N,1),1,D);\n r2 = repmat(rand(N,1),1,D);\n C1 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n C2 = repmat(unifrnd(1.5,2.5,N,1),1,D);\n OffVel = W.*ParticleVel + C1.*r1.*(PbestDec-ParticleDec) + C2.*r2.*(GbestDec-ParticleDec);\n phi = max(4,C1+C2);\n OffVel = OffVel.*2./abs(2-phi-sqrt(phi.^2-4*phi));\n delta = repmat((Problem.upper-Problem.lower)/2,N,1);\n OffVel = max(min(OffVel,delta),-delta);\n OffDec = ParticleDec + OffVel;\n \n %% Deterministic back\n Lower = repmat(Problem.lower,N,1);\n Upper = repmat(Problem.upper,N,1);\n repair = OffDec < Lower | OffDec > Upper;\n OffVel(repair) = 0.001*OffVel(repair);\n OffDec = max(min(OffDec,Upper),Lower);\n \n %% Polynomial mutation\n disM = 20;\n Site1 = repmat(rand(N,1)<0.15,1,D);\n\n [outIndexList,~] = GLMO_createGroups(numberOfGroups,OffDec,D,typeOfGroups); % 3 = random groups\n chosengroups = randi(numberOfGroups,size(outIndexList,1),1);\n Site2 = outIndexList == chosengroups;\n mu = rand(N,1);\n mu = repmat(mu,1,D); \n \n temp = Site1 & Site2 & mu<=0.5;\n OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...\n (1-(OffDec(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);\n temp = Site1 & Site2 & mu>0.5; \n OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...\n (1-(Upper(temp)-OffDec(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));\n Offspring = Problem.Evaluation(OffDec,OffVel);\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/GLMO/GLMO_SMPSOOperator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39318755904606567}}
{"text": "function [g1, g2] = lfmXrbfKernGradient(lfmKern, rbfKern, t1, t2, covGrad, meanVector)\n\n% LFMXRBFKERNGRADIENT Compute gradient between the LFM and RBF kernels.\n% FORMAT\n% DESC computes the gradient of an objective function with respect\n% to cross kernel terms between LFM and RBF kernels for\n% the multiple output kernel.\n% ARG lfmKern : the kernel structure associated with the LFM\n% kernel.\n% ARG rbfKern : the kernel structure associated with the RBF\n% kernel.\n% ARG t : inputs for which kernel is to be computed.\n% RETURN g1 : gradient of objective function with respect to kernel\n% parameters of LFM kernel.\n% RETURN g2 : gradient of objective function with respect to kernel\n% parameters of RBF kernel.\n%\n% FORMAT\n% DESC computes the gradient of an objective function with respect\n% to cross kernel terms between LFM and RBF kernels for\n% the multiple output kernel.\n% ARG lfmKern : the kernel structure associated with the LFM\n% kernel.\n% ARG rbfKern : the kernel structure associated with the RBF\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% RETURN g1 : gradient of objective function with respect to kernel\n% parameters of LFM kernel.\n% RETURN g2 : gradient of objective function with respect to kernel\n% parameters of RBF kernel.\n%\n% FORMAT\n% DESC computes the gradient of an objective function with respect\n% to cross kernel terms between LFM and RBF kernels for\n% the multiple output kernel.\n% ARG lfmKern : the kernel structure associated with the LFM\n% kernel.\n% ARG rbfKern : the kernel structure associated with the RBF\n% kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG meanVec : precomputed factor that is used for the switching dynamical\n% latent force model.\n% RETURN g1 : gradient of objective function with respect to kernel\n% parameters of LFM kernel.\n% RETURN g2 : gradient of objective function with respect to kernel\n% parameters of RBF kernel.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, lfmKernParamInit, rbfKernParamInit\n%\n% COPYRIGHT : David Luengo, 2007, 2008\n%\n% MODIFICATIONS : Neil D. Lawrence, 2007\n%\n% MODIFICATIONS : Mauricio A. Alvarez, 2008, 2010\n\n% KERN\n\nsubComponent = false; % This is just a flag that indicates if this kernel is part of a bigger kernel (SDLFM)\n\nif nargin == 4\n covGrad = t2;\n t2 = t1;\nelseif nargin == 6\n subComponent = true;\n if numel(meanVector)>1\n if size(meanVector,1) == 1,\n if size(meanVector, 2)~=size(covGrad, 2)\n error('The dimensions of meanVector don''t correspond to the dimensions of covGrad')\n end\n else\n if size((meanVector'), 2)~=size(covGrad,2)\n error('The dimensions of meanVector don''t correspond to the dimensions of covGrad')\n end\n end\n else\n if numel(t1)==1 && numel(t2)>1\n % matGrad will be row vector and so should be covGrad\n dimcovGrad = length(covGrad);\n covGrad = reshape(covGrad, [1 dimcovGrad]);\n elseif numel(t1)>1 && numel(t2)==1\n % matGrad will be column vector and sp should be covGrad\n dimcovGrad = length(covGrad);\n covGrad = reshape(covGrad, [dimcovGrad 1]);\n end\n end\nend\n\nif size(t1, 2) > 1 || size(t2, 2) > 1\n error('Input can only have one column');\nend\nif lfmKern.inverseWidth ~= rbfKern.inverseWidth\n error('Kernels cannot be cross combined if they have different inverse widths.')\nend\n\nif lfmKern.isNormalised ~= rbfKern.isNormalised\n error('Kernels cannot be cross combined if they have different normalization settings.')\nend\n\nm = lfmKern.mass;\nD = lfmKern.spring;\nC = lfmKern.damper;\nS = lfmKern.sensitivity;\n\nalpha = C/(2*m);\nomega = sqrt(D/m-alpha^2);\n\nsigma2 = 2/lfmKern.inverseWidth;\nsigma = sqrt(sigma2);\n\nif isreal(omega)\n gamma = alpha + j*omega;\n ComputeUpsilon1 = lfmComputeUpsilonMatrix(gamma,sigma2,t1, t2);\n if lfmKern.isNormalised\n K0 = S/(2*sqrt(2)*m*omega);\n else\n K0 = sigma*sqrt(pi)*S/(2*m*omega);\n end\nelse\n gamma1 = alpha + j*omega;\n gamma2 = alpha - j*omega;\n ComputeUpsilon1 = lfmComputeUpsilonMatrix(gamma2,sigma2,t1, t2);\n ComputeUpsilon2 = lfmComputeUpsilonMatrix(gamma1,sigma2,t1, t2);\n if lfmKern.isNormalised\n K0 = (S/(j*4*sqrt(2)*m*omega));\n else\n K0 = sigma*sqrt(pi)*S/(j*4*m*omega);\n end\nend\n\ng1 = zeros(1,5);\n\n% Gradient with respect to m, C and D\n\nfor ind = 1:3 % Parameter (m, D or C)\n switch ind\n case 1 % Gradient wrt m\n gradThetaM = 1;\n gradThetaAlpha = -C/(2*(m^2));\n gradThetaOmega = (C^2-2*m*D)/(2*(m^2)*sqrt(4*m*D-C^2));\n case 2 % Gradient wrt D\n gradThetaM = 0;\n gradThetaAlpha = 0;\n gradThetaOmega = 1/sqrt(4*m*D-C^2);\n case 3 % Gradient wrt C\n gradThetaM = 0;\n gradThetaAlpha = 1/(2*m);\n gradThetaOmega = -C/(2*m*sqrt(4*m*D-C^2));\n end\n \n % Gradient evaluation\n \n if isreal(omega)\n gamma = alpha + j*omega;\n gradThetaGamma = gradThetaAlpha + j*gradThetaOmega;\n matGrad = -K0*imag(lfmGradientUpsilonMatrix(gamma,sigma2,t1, t2)*gradThetaGamma ...\n - (gradThetaM/m + gradThetaOmega/omega) ...\n * ComputeUpsilon1);\n else\n gamma1 = alpha + j*omega;\n gamma2 = alpha - j*omega;\n gradThetaGamma1 = gradThetaAlpha + j*gradThetaOmega;\n gradThetaGamma2 = gradThetaAlpha - j*gradThetaOmega;\n matGrad = K0*(lfmGradientUpsilonMatrix(gamma2,sigma2, t1, t2)*gradThetaGamma2 ...\n - lfmGradientUpsilonMatrix(gamma1,sigma2, t1, t2)*gradThetaGamma1 ...\n - (gradThetaM/lfmKern.mass + gradThetaOmega/omega) ...\n * (ComputeUpsilon1 - ComputeUpsilon2));\n \n end\n if subComponent\n if size(meanVector,1) ==1,\n matGrad = matGrad*meanVector;\n else\n matGrad = (meanVector*matGrad).';\n end\n end\n g1(ind) = sum(sum(matGrad.*covGrad));\nend\n\n% Gradient with respect to sigma\n\nif isreal(omega)\n gamma = alpha + j*omega;\n if lfmKern.isNormalised\n matGrad = -K0*imag(lfmGradientSigmaUpsilonMatrix(gamma,sigma2,t1, t2));\n else\n matGrad = -(sqrt(pi)*S/(2*m*omega)) ...\n * imag(ComputeUpsilon1 ...\n + sigma*lfmGradientSigmaUpsilonMatrix(gamma,sigma2,t1, t2));\n end\nelse\n gamma1 = alpha + j*omega;\n gamma2 = alpha - j*omega;\n if lfmKern.isNormalised\n matGrad = K0*(lfmGradientSigmaUpsilonMatrix(gamma2,sigma2,t1,t2) ...\n - lfmGradientSigmaUpsilonMatrix(gamma1,sigma2,t1,t2));\n else\n matGrad = (sqrt(pi)*S/(j*4*m*omega)) ...\n *(ComputeUpsilon1 - ComputeUpsilon2 ...\n + sigma*(lfmGradientSigmaUpsilonMatrix(gamma2,sigma2,t1,t2) ...\n - lfmGradientSigmaUpsilonMatrix(gamma1,sigma2,t1,t2)));\n end\nend;\n\nif subComponent\n if size(meanVector,1) ==1,\n matGrad = matGrad*meanVector;\n else\n matGrad = (meanVector*matGrad).';\n end\nend\n\ng1(4) = sum(sum(matGrad.*covGrad))*(-(sigma^3)/4); % temporarly introduced by MA\ng2(1) = g1(4);\n\n% Gradient with respect to S\n\nif isreal(omega)\n if lfmKern.isNormalised\n matGrad = -(1/(2*sqrt(2)*m*omega))* imag(ComputeUpsilon1);\n else\n matGrad = -(sqrt(pi)*sigma/(2*m*omega))* imag(ComputeUpsilon1);\n end\nelse\n if lfmKern.isNormalised\n matGrad = (1/(j*4*sqrt(2)*m*omega))*(ComputeUpsilon1 - ComputeUpsilon2);\n else\n matGrad = (sqrt(pi)*sigma/(j*4*m*omega))*(ComputeUpsilon1 - ComputeUpsilon2);\n end\nend;\n\nif subComponent\n if size(meanVector,1) ==1,\n matGrad = matGrad*meanVector;\n else\n matGrad = (meanVector*matGrad).';\n end\nend\n\ng1(5) = sum(sum(matGrad.*covGrad));\ng1 = real(g1);\n% Gradient with respect to the \"variance\" of the RBF\ng2(1) = 0; % Otherwise is counted twice, temporarly changed by MA\ng2(2) = 0;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmXrbfKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39318755295684266}}
{"text": "function [dv, dvArr, flyBy1DVVect, flyBy2DVVect, flyBy1Rp, flyBy2Rp, ...\n xferOrbitP1, xferOrbitP2, xferOrbitP3, flyBy1OrbitIn, flyBy1OrbitOut, ...\n flyBy2OrbitIn, flyBy2OrbitOut] = ...\n findOptimalTwoFlyByTraj(x, departBodyInfo, flyby1BodyInfo, flyby2BodyInfo, arrivalBodyInfo, gmuXfr)\n%findOptimalTwoFlyByTraj Summary of this function goes here\n% Detailed explanation goes here\n if(length(x)~=4)\n error('Length of x in findOptimalTwoFlyByTraj must be 4');\n end\n \n departDate = x(1);\n phase1TOF = x(2);\n phase2TOF = x(3);\n phase3TOF = x(4);\n \n xDates = [departDate, \n departDate + phase1TOF,\n departDate + phase1TOF + phase2TOF,\n departDate + phase1TOF + phase2TOF + phase3TOF];\n \n preFunc1 = @(arrivalUT, departUT) findOptimalDepartureArrivalObjFunc(arrivalUT, departUT, departBodyInfo, flyby1BodyInfo, gmuXfr, 'departDVRadioBtn');\n objFuncDepart = @(x) preFunc1(x(2), x(1));\n \n objFuncFlyby1DV = @(x) flybyDVObjFunc([xDates(1) xDates(2) xDates(3)], departBodyInfo, flyby1BodyInfo, flyby2BodyInfo, gmuXfr);\n objFuncFlyby2DV = @(x) flybyDVObjFunc([xDates(2) xDates(3) xDates(4)], flyby1BodyInfo, flyby2BodyInfo, arrivalBodyInfo, gmuXfr);\n \n preFunc2 = @(arrivalUT, departUT) findOptimalDepartureArrivalObjFunc(arrivalUT, departUT, flyby2BodyInfo, arrivalBodyInfo, gmuXfr, 'arrivalDVRadioBtn');\n objFuncArrival = @(x) preFunc2(x(4), x(3));\n \n dv1 = objFuncDepart(xDates);\n [dv2, flyBy1DVVect, flyBy1Rp, xferOrbitP1, xferOrbitP2, flyBy1OrbitIn, flyBy1OrbitOut] = objFuncFlyby1DV(xDates);\n [dv3, flyBy2DVVect, flyBy2Rp, xferOrbitP2, xferOrbitP3, flyBy2OrbitIn, flyBy2OrbitOut] = objFuncFlyby2DV(xDates);\n dv4 = objFuncArrival(xDates);\n dvArr = [dv1, dv2, dv3, dv4];\n \n dv = dv1 + dv2 + dv3 + dv4;\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/flyby/findOptimalTwoFlyByTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3931044036597374}}
{"text": "function [V,D]=gabmuleigs(K,c,p3,varargin)\n%GABMULEIGS Eigenpairs of Gabor multiplier\n% Usage: h=gabmuleigs(K,c,g,a);\n% h=gabmuleigs(K,c,a);\n% h=gabmuleigs(K,c,ga,gs,a);\n%\n% Input parameters:\n% K : Number of eigenvectors to compute.\n% c : symbol of Gabor multiplier\n% g : analysis/synthesis window\n% ga : analysis window\n% gs : synthesis window\n% a : Length of time shift.\n% Output parameters:\n% V : Matrix containing eigenvectors.\n% D : Eigenvalues.\n%\n% `gabmuleigs` has been deprecated. Please use construct a frame multiplier\n% and use |framemuleigs| instead.\n%\n% A call to `gabmuleigs(K,c,ga,gs,a)` can be replaced by ::\n%\n% [Fa,Fs]=framepair('dgt',ga,gs,a,M);\n% [V,D]=framemuleigs(Fa,Fs,s,K);\n%\n% Original help:\n% --------------\n%\n% `gabmuleigs(K,c,g,a)` computes the *K* largest eigenvalues and eigen-\n% vectors of the Gabor multiplier with symbol *c* and time shift *a*. The\n% number of channels is deduced from the size of the symbol *c*. The\n% window *g* will be used for both analysis and synthesis.\n%\n% `gabmuleigs(K,c,ga,gs,a)` does the same using the window the window *ga*\n% for analysis and *gs* for synthesis.\n%\n% `gabmuleigs(K,c,a)` does the same using the a tight Gaussian window of\n% for analysis and synthesis.\n%\n% If *K* is empty, then all eigenvalues/pairs will be returned.\n%\n% `gabmuleigs` takes the following parameters at the end of the line of input\n% arguments:\n%\n% 'tol',t Stop if relative residual error is less than the\n% specified tolerance. Default is 1e-9 \n%\n% 'maxit',n Do at most n iterations.\n%\n% 'iter' Call `eigs` to use an iterative algorithm.\n%\n% 'full' Call `eig` to sole the full problem.\n%\n% 'auto' Use the full method for small problems and the\n% iterative method for larger problems. This is the\n% default. \n%\n% 'crossover',c\n% Set the problem size for which the 'auto' method\n% switches. Default is 200.\n%\n% 'print' Display the progress.\n%\n% 'quiet' Don't print anything, this is the default.\n%\n% See also: gabmul, dgt, idgt, gabdual, gabtight\n\nwarning(['LTFAT: GABMULEIGS has been deprecated, please use FRAMEMULEIGS ' ...\n 'instead. See the help on FRAMEMULEIGS for more details.']);\n\n% Change this to 1 or 2 to see the iterative method in action.\nprintopts=0;\n\nif nargin<3\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\nif nargout==2\n doV=1;\nelse\n doV=0;\nend;\n\nM=size(c,1);\nN=size(c,2);\n\nistight=1;\nif numel(p3)==1\n % Usage: h=gabmuleigs(c,K,a); \n a=p3;\n L=N*a;\n ga=gabtight(a,M,L);\n gs=ga;\n arglist=varargin;\nelse \n if numel(varargin{1})==1\n % Usage: h=gabmuleigs(c,K,g,a); \n ga=p3;\n gs=p3;\n a=varargin{1};\n L=N*a;\n arglist=varargin(2:end);\n else \n if numel(varargin{2})==1\n % Usage: h=gabmuleigs(c,K,ga,gs,a); \n ga=p3;\n gs=varargin{1};\n a =varargin{2};\n L=N*a;\n istight=0;\n arglist=varargin(3:end);\n end; \n end;\nend;\n\ndefinput.keyvals.maxit=100;\ndefinput.keyvals.tol=1e-9;\ndefinput.keyvals.crossover=200;\ndefinput.flags.print={'quiet','print'};\ndefinput.flags.method={'auto','iter','full'};\n\n\n[flags,kv]=ltfatarghelper({},definput,arglist);\n\n\n% Do the computation. For small problems a direct calculation is just as\n% fast.\n\nif (flags.do_iter) || (flags.do_auto && L>kv.crossover)\n \n if flags.do_print\n opts.disp=1;\n else\n opts.disp=0;\n end;\n opts.isreal = false;\n opts.maxit = kv.maxit;\n opts.tol = kv.tol;\n \n % Setup afun\n afun(1,c,ga,gs,a,M,L);\n \n if doV\n [V,D] = eigs(@afun,L,K,'LM',opts);\n else\n D = eigs(@afun,L,K,'LM',opts);\n end;\n\nelse\n % Compute the transform matrix.\n bigM=tfmat('gabmul',c,ga,gs,a);\n\n if doV\n [V,D]=eig(bigM);\n else\n D=eig(bigM);\n end;\n\n\nend;\n\n% The output from eig and eigs is a diagonal matrix, so we must extract the\n% diagonal.\nD=diag(D);\n\n% Sort them in descending order\n[~,idx]=sort(abs(D),1,'descend');\nD=D(idx(1:K));\n\nif doV\n V=V(:,idx(1:K));\nend;\n\n% Clean the eigenvalues, if we know that they are real-valued\n%if isreal(ga) && isreal(gs) && isreal(c)\n% D=real(D);\n%end;\n\n% The function has been written in this way, because Octave (at the time\n% of writing) does not accept additional parameters at the end of the\n% line of input arguments for eigs\nfunction y=afun(x,c_in,ga_in,gs_in,a_in,M_in,L_in)\n persistent c;\n persistent ga;\n persistent gs;\n persistent a;\n persistent M;\n persistent L; \n \n if nargin>1\n c = c_in; \n ga = ga_in;\n gs = gs_in;\n a = a_in; \n M = M_in; \n L = L_in;\n else\n y=comp_idgt(c.*comp_dgt(x,ga,a,M,[0 1],0,0,0),gs,a,[0 1],0,0);\n end;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/deprecated/gabmuleigs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39282621149379554}}
{"text": "\nfunction exampleFilter\n% function exampleFilter\n%\n% Example of how the Kalman filter performs for real data\n\nload raw\n\n\n%Apply filter\nk=Kalman_Stack_Filter(raw);\nk75=Kalman_Stack_Filter(raw,0.75);\n\n\n%Set up image window\nminMax=[min(raw(:)),max(raw(:))];\nclf, colormap gray\n\nsubplot(1,3,1)\nimagesc(raw(:,:,1))\ntitle('original')\nset(gca,'clim',minMax), axis off equal\n\nsubplot(1,3,2)\nimagesc(k(:,:,1))\ntitle('filtered, gain=0.5')\nset(gca,'clim',minMax), axis off equal\n\nsubplot(1,3,3)\nimagesc(k75(:,:,1))\ntitle('filtered, gain=0.75')\nset(gca,'clim',minMax), axis off equal\n\n\n%Loop movie \ndisp('crtl-c to stop movie')\nwhile 1\n for i=1:size(k,3)\n \n subplot(1,3,1)\n set(get(gca,'children'),'CData',raw(:,:,i))\n \n subplot(1,3,2)\n set(get(gca,'children'),'CData',k(:,:,i))\n \n subplot(1,3,3)\n set(get(gca,'children'),'CData',k75(:,:,i))\n \n \n pause(0.05)\n drawnow\n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26334-kalman-filter-for-noisy-movies/exampleFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3928026260856127}}
{"text": "function generateOpenfieldPB(fieldSizeX, fieldSizeY, beamletSize);\n\nxP = -(fieldSizeX-beamletSize)/2 : beamletSize : (fieldSizeX-beamletSize)/2;\nyP = -(fieldSizeY-beamletSize)/2 : beamletSize : (fieldSizeY-beamletSize)/2;\n[xPosV, yPosV] = meshgrid(xP, yP);\nxPosV = xPosV(:);\nyPosV = yPosV(:);\nw_field = ones(size(xPosV));\nbeamlet_delta_x = beamletSize*ones(size(xPosV));\nbeamlet_delta_y = beamlet_delta_x;\n\nfilename = ['PB_', num2str(fieldSizeX), 'x', num2str(fieldSizeY), '_PBsize', num2str(beamletSize), 'cm.mat']\ndisp ('save PB info to above filename.')\nsave (filename, 'xPosV', 'yPosV', 'beamlet_delta_x', 'beamlet_delta_y', 'w_field');\n\n% Display generated PB information.\nfigure;hAxis2 = axes;hold on;\n%axis(hAxis2, 'manual');\n % w_colors = floor((w_field ./ max(w_field))*255)+1;\n %set(gcf, 'doublebuffer', 'on');\n for i=1:length(xPosV)\n patch([xPosV(i) - beamlet_delta_x(i)/2 xPosV(i) - beamlet_delta_x(i)/2 xPosV(i) + beamlet_delta_x(i)/2 xPosV(i) + beamlet_delta_x(i)/2 xPosV(i) - beamlet_delta_x(i)/2], [yPosV(i) - beamlet_delta_y(i)/2 yPosV(i) + beamlet_delta_y(i)/2 yPosV(i) + beamlet_delta_y(i)/2 yPosV(i) - beamlet_delta_y(i)/2 yPosV(i) - beamlet_delta_y(i)/2], w_field(i));\n end\n % axis([hAxis1 hAxis2], 'ij');\n % kids = get(hAxis2, 'children');\n % set(kids, 'edgecolor', 'none');\n % cMap = colormap('jet');\n % set(hAxis2, 'color', cMap(1,:));\n \nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/generateOpenfieldPB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.39270202141569543}}
{"text": "function [x,f,funEvals] = minConF_BC(funObj,x,LB,UB,options)\n% function [x,f] = minConF_BC(funObj,x,LB,UB,options)\n%\n% Function for using Two-Metric Projection to solve problems of the form:\n% min funObj(x)\n% s.t. LB_i <= x_i <= UB_i\n%\n% @funObj(x): function to minimize (returns gradient as second argument)\n%\n% options:\n% verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3:\n% debug)\n% optTol: tolerance used to check for progress (default: 1e-7)\n% maxIter: maximum number of calls to funObj (default: 250)\n% numDiff: compute derivatives numerically (0: use user-supplied\n% derivatives (default), 1: use finite differences, 2: use complex\n% differentials)\n% method: 'sd', 'lbfgs', 'newton'\n\nnVars = length(x);\n\n% Set Parameters\nif nargin < 5\n options = [];\nend\n[verbose,numDiff,optTol,maxIter,suffDec,interp,method,corrections,damped] = ...\n myProcessOptions(...\n options,'verbose',3,'numDiff',0,'optTol',1e-6,'maxIter',500,'suffDec',1e-4,...\n 'interp',1,'method','lbfgs','corrections',100,'damped',0);\n\n% Output Log\nif verbose >= 3\n fprintf('%10s %10s %15s %15s %15s\\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond');\nend\n\n% Make objective function (if using numerical derivatives)\nfunEvalMultiplier = 1;\nif numDiff\n if numDiff == 2\n useComplex = 1;\n else\n useComplex = 0;\n end\n funObj = @(x)autoGrad(x,useComplex,funObj);\n funEvalMultiplier = nVars+1-useComplex;\nend\n\n% Evaluate Initial Point\nx = projectBounds(x,LB,UB);\nif strcmp(method,'newton')\n [f,g,H] = funObj(x);\n secondOrder = 1;\nelse\n [f,g] = funObj(x);\n secondOrder = 0;\nend\nfunEvals = 1;\n\n% Compute Working Set\nworking = ones(nVars,1);\nworking((x < LB+optTol*2) & g >= 0) = 0;\nworking((x > UB-optTol*2) & g <= 0) = 0;\nworking = find(working);\n\n% Check Optimality\nif isempty(working)\n if verbose >= 1\n fprintf('All variables are at their bound and no further progress is possible at initial point\\n');\n end\n return;\nelseif norm(g(working)) <= optTol\n if verbose >=1\n fprintf('All working variables satisfy optimality condition at initial point\\n');\n end\n return;\nend\n\nif verbose >= 3\n switch method\n case 'sd'\n fprintf('Steepest Descent\\n');\n case 'lbfgs'\n fprintf('L-BFGS\\n');\n case 'bfgs'\n fprintf('BFGS\\n');\n case 'newton'\n fprintf('Newton\\n');\n end\nend\n\ni = 1;\nwhile funEvals <= maxIter\n\n % Compute Step Direction\n d = zeros(nVars,1);\n switch(method)\n case 'sd'\n d(working) = -g(working);\n case 'lbfgs'\n if i == 1\n d(working) = -g(working);\n old_dirs = zeros(nVars,0);\n old_stps = zeros(nVars,0);\n Hdiag = 1;\n else\n if damped\n [old_dirs,old_stps,Hdiag] = dampedUpdate(g-g_old,x-x_old,corrections,verbose==3,old_dirs,old_stps,Hdiag);\n else\n [old_dirs,old_stps,Hdiag] = lbfgsUpdate(g-g_old,x-x_old,corrections,verbose==3,old_dirs,old_stps,Hdiag);\n end\n curvSat = sum(old_dirs(working,:).*old_stps(working,:)) > 1e-10;\n d(working) = lbfgs(-g(working),old_dirs(working,curvSat),old_stps(working,curvSat),Hdiag);\n end\n g_old = g;\n x_old = x;\n case 'bfgs'\n if i == 1\n d(working) = -g(working);\n B = eye(nVars);\n else\n y = g-g_old;\n s = x-x_old;\n\n ys = y'*s;\n\n if i == 2\n if ys > 1e-10\n B = ((y'*y)/(y'*s))*eye(nVars);\n end\n end\n if ys > 1e-10\n B = B + (y*y')/(y'*s) - (B*s*s'*B)/(s'*B*s);\n else\n if verbose == 2\n fprintf('Skipping Update\\n');\n end\n end\n d(working) = -B(working,working)\\g(working);\n end\n g_old = g;\n x_old = x;\n\n case 'newton'\n [R,posDef] = chol(H(working,working));\n \n if posDef == 0\n d(working) = -R\\(R'\\g(working));\n else\n if verbose == 3\n fprintf('Adjusting Hessian\\n');\n end\n H(working,working) = H(working,working) + eye(length(working)) * max(0,1e-12 - min(real(eig(H(working,working)))));\n d(working) = -H(working,working)\\g(working);\n end\n otherwise\n fprintf('Unrecognized Method: %s\\n',method);\n break;\n end\n\n % Check that Progress can be made along the direction\n f_old = f;\n gtd = g'*d;\n if gtd > -optTol\n if verbose >= 2\n fprintf('Directional Derivative below optTol\\n');\n end\n break;\n end\n\n % Select Initial Guess to step length\n if i == 1 && ~secondOrder\n t = min(1,1/sum(abs(g(working))));\n else\n t = 1;\n end\n\n % Evaluate the Objective and Projected Gradient at the Initial Step\n x_new = projectBounds(x+t*d,LB,UB);\n if secondOrder\n [f_new,g_new,H] = funObj(x_new);\n else\n [f_new,g_new] = funObj(x_new);\n end\n funEvals = funEvals+1;\n\n % Backtracking Line Search\n lineSearchIters = 1;\n while f_new > f + suffDec*g'*(x_new-x) || ~isLegal(f_new)\n temp = t;\n if interp == 0 || ~isLegal(f_new) || ~isLegal(g_new)\n if verbose == 3\n fprintf('Halving Step Size\\n');\n end\n t = .5*t;\n else\n if verbose == 3\n fprintf('Cubic Backtracking\\n');\n end\n t = polyinterp([0 f gtd; t f_new g_new'*d]);\n end\n\n % Adjust if change is too small\n if t < temp*1e-3\n if verbose == 3\n fprintf('Interpolated value too small, Adjusting\\n');\n end\n t = temp*1e-3;\n elseif t > temp*0.6\n if verbose == 3\n fprintf('Interpolated value too large, Adjusting\\n');\n end\n t = temp*0.6;\n end\n\n % Check whether step has become too small\n if sum(abs(t*d)) < optTol\n if verbose == 3\n fprintf('Line Search failed\\n');\n end\n t = 0;\n f_new = f;\n g_new = g;\n break;\n end\n\n % Evaluate New Point\n x_new = projectBounds(x+t*d,LB,UB);\n [f_new,g_new] = funObj(x_new);\n funEvals = funEvals+1;\n lineSearchIters = lineSearchIters+1;\n\n end\n\n % Take Step\n x = x_new;\n f = f_new;\n g = g_new;\n\n % Compute Working Set\n working = ones(nVars,1);\n working((x < LB+optTol*2) & g >= 0) = 0;\n working((x > UB-optTol*2) & g <= 0) = 0;\n working = find(working);\n\n % Output Log\n if verbose >= 2\n fprintf('%10d %10d %15.5e %15.5e %15.5e\\n',i,funEvals*funEvalMultiplier,t,f,sum(abs(g(working))));\n end\n\n % Check Optimality\n if isempty(working)\n if verbose >= 1\n fprintf('All variables are at their bound and no further progress is possible\\n');\n end\n break;\n elseif norm(g(working)) <= optTol\n if verbose >=1\n fprintf('All working variables satisfy optimality condition\\n');\n end\n break;\n end\n\n % Check for lack of progress\n if sum(abs(t*d)) < optTol\n if verbose >= 1\n fprintf('Step size below optTol\\n');\n end\n break;\n end\n\n if abs(f-f_old) < optTol\n if verbose >= 1\n fprintf('Function value changing by less than optTol\\n');\n end\n break;\n end\n\n if funEvals*funEvalMultiplier > maxIter\n if verbose >= 1\n fprintf('Function Evaluations exceeds maxIter\\n');\n end\n break;\n end\n\n % If necessary, compute Hessian\n if secondOrder && lineSearchIters > 1\n [f_new,g_new,H] = funObj(x);\n end\n\n i = i + 1;\nend\nend\n\nfunction [x] = projectBounds(x,LB,UB)\nx(x < LB) = LB(x < LB);\nx(x > UB) = UB(x > UB);\nend", "meta": {"author": "ziyuw", "repo": "rembo", "sha": "7926c00a802ad33e7c7f61e3571a32bacaba3d00", "save_path": "github-repos/MATLAB/ziyuw-rembo", "path": "github-repos/MATLAB/ziyuw-rembo/rembo-7926c00a802ad33e7c7f61e3571a32bacaba3d00/src/utils/minConf/minConf/minConf_TMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3927020214156953}}
{"text": "function colorspace_demo(Cmd)\n% Demo for colorspace.m - 3D visualizations of various color spaces\n\n% Pascal Getreuer 2006\n\nif nargin == 0\n % Create a figure with a drop-down menu\n figure('Color',[1,1,1]);\n h = uicontrol('Style','popup','Position',[15,10,90,21],...\n 'BackgroundColor',[1,1,1],'Value',2,...\n 'string',{'sRGB','Y''PbPr','HSV','HSL','L*a*b*','L*u*v*','L*ch'});\n set(h,'Callback',sprintf('%s(get(%.20g,''Value''))',mfilename,h)); \n Cmd = 2;\nend\n\n% Plot a figure\nswitch Cmd\ncase 1\n [x,y,z,Tri] = makeshape('Cube');\n CData = [x,y,z];\n myplot((x-0.5)*0.8,(y-0.5)*0.8,(z)*0.8,Tri,CData);\n coloraxis('R''',5,0.5*0.8);\n coloraxis('G''',6,0.5*0.8); \n coloraxis('B''',3); \ncase 2\n [x,y,z,Tri] = makeshape('Cylinder');\n CData = colorspace('rgb<-ypbpr',[z,x/2,y/2]);\n myplot(x,y,0.8*z,Tri,CData);\n coloraxis('Y''',3);\n coloraxis('P_b',5,0.8); \n coloraxis('P_r',6,0.8); \ncase 3\n [x,y,z,Tri] = makeshape('Hexacone');\n CData = colorspace('rgb<-hsv',[(pi+atan2(-y,-x))*180/pi,sqrt(x.^2+y.^2),z]);\n myplot(x,y,z,Tri,CData);\n coloraxis('H',1);\n coloraxis('S',2);\n coloraxis('V',3);\ncase 4\n [x,y,z,Tri] = makeshape('Double Hexacone');\n CData = colorspace('rgb<-hsl',[(pi+atan2(-y,-x))*180/pi,sqrt(x.^2+y.^2),z]); \n myplot(x,y,2*z,Tri,CData);\n coloraxis('H',1);\n coloraxis('S',2); \n coloraxis('L',4);\ncase 5\n [x,y,z,Tri] = makeshape('Blobs');\n CData = colorspace('rgb<-lab',[z*100,x*100,y*100]);\n myplot(x,y,2*z,Tri,CData);\n coloraxis('L*',4);\n coloraxis('a*',5,2); \n coloraxis('b*',6,2); \ncase 6\n [x,y,z,Tri] = makeshape('Blobs');\n CData = colorspace('rgb<-luv',[z*100,x*125,y*125]);\n myplot(x,y,2*z,Tri,CData);\n coloraxis('L*',4);\n coloraxis('u*',5,2); \n coloraxis('v*',6,2);\ncase 7\n [x,y,z,Tri] = makeshape('Blobs');\n CData = colorspace('rgb<-lab',[z*100,x*100,y*100]);\n myplot(x,y,2*z,Tri,CData);\n coloraxis('L*',4);\n coloraxis('c',2); \n coloraxis('h',1);\nend\n\naxis equal;\naxis off;\npbaspect([1,1,1]);\nview(70,27);\nrotate3d on;\n\nreturn;\n\n\nfunction myplot(x,y,z,Tri,CData)\n% Plot a triangular mesh with color data\ncla;\nCData = min(max(CData,0),1);\npatch('Faces',Tri,'Vertices',[x,y,z],'FaceVertexCData',CData,...\n 'FaceColor','interp','EdgeColor','none');\nhold on;\nreturn;\n\n\nfunction coloraxis(Name,Type,h)\n% Draw color axes as 3D objects\nFontSize = 14;\n\nswitch Type\ncase 1\n set(text(-0.25,-1.3,1.1,Name),'FontWeight','bold',...\n 'FontSize',FontSize,'Color',[0,0,0]);\n t = linspace(0,pi*3/2,60);\n x = cos(t)*1.1;\n y = sin(t)*1.1;\n set(plot3(x,y,zeros(size(x)),'k-'),'LineWidth',2.5,'Color',[1,1,1]*0.8);\n x = [x,-0.1,0,-0.1];\n y = [y,-1.05,-1.1,-1.15];\n set(plot3(x,y,ones(size(x)),'k-'),'LineWidth',2.5); \ncase 2\n set(text(0,-0.6,0.15,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]);\n set(plot3([-0.05,0,0.05,0,0],[-0.9,-1,-0.9,-1,0],[0,0,0,0,0],'k-'),'LineWidth',2.5);\ncase 3\n set(text(0,0.15,1.3,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]);\n set(plot3([0,0,0,0,0],[-0.05,0,0.05,0,0],[1.6,1.7,1.6,1.7,0],'k-'),'LineWidth',2.5);\ncase 4\n set(text(0,0.15,2.4,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]);\n set(plot3([0,0,0,0,0],[-0.05,0,0.05,0,0],[2.4,2.5,2.4,2.5,0],'k-'),'LineWidth',2.5);\ncase 5\n set(text(0.6,0,h+0.15,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]);\n set(plot3([0.9,1,0.9,1,-1,-0.9,-1,-0.9],[-0.05,0,0.05,0,0,-0.05,0,0.05],...\n zeros(1,8)+h,'k-'),'LineWidth',2.5);\ncase 6\n set(text(0,0.6,h+0.15,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]);\n set(plot3([-0.05,0,0.05,0,0,-0.05,0,0.05],[0.9,1,0.9,1,-1,-0.9,-1,-0.9],...\n zeros(1,8)+h,'k-'),'LineWidth',2.5);\nend\nreturn;\n\n\nfunction [x,y,z,Tri] = makeshape(Shape)\n% Make a 3D shape: Shape = 'Cube', 'Cylinder', 'Cone', 'Double Cone', 'Blobs'\n\n% Cube\nN = 12; % Vertices per edge\n% Cylinder, Cone, Double Cone\nNth = 25; % Vertices over angles, (Nth - 1) should be a multiple of 12 \nNr = 4; % Vertices over radius\nNz = 8; % Vertices over z-dimension\n\nswitch lower(Shape)\ncase 'cube'\n [u,v] = meshgrid(linspace(0,1,N),linspace(0,1,N));\n u = u(:);\n v = v(:);\n x = [u;u;u;u;zeros(N^2,1);ones(N^2,1)];\n y = [v;v;zeros(N^2,1);ones(N^2,1);v;v];\n z = [zeros(N^2,1);ones(N^2,1);v;v;u;u];\n Tri = trigrid(N,N);\n Tri = [Tri;N^2+Tri;2*N^2+Tri;3*N^2+Tri;4*N^2+Tri;5*N^2+Tri];\ncase 'cylinder'\n Nth = ceil(Nth*0.75);\n [u,v] = meshgrid(linspace(0,pi*3/2,Nth),linspace(0,1,Nz));\n Tri = trigrid(Nth,Nz);\n x = cos(u(:));\n y = sin(u(:));\n z = v(:);\n [u,v] = meshgrid(linspace(0,pi*3/2,Nth),linspace(0,1,Nr));\n Tri = [Tri;Nth*Nz+trigrid(Nth,Nr);Nth*Nz+Nth*Nr+trigrid(Nth,Nr)];\n x = [x;v(:).*cos(u(:));v(:).*cos(u(:))];\n y = [y;v(:).*sin(u(:));v(:).*sin(u(:))];\n z = [z;zeros(Nth*Nr,1);ones(Nth*Nr,1)];\n [u,v] = meshgrid(linspace(0,1,Nr),linspace(0,1,Nz));\n Tri = [Tri;Nth*Nz+2*Nth*Nr+trigrid(Nr,Nz);Nth*Nz+2*Nth*Nr+Nr*Nz+trigrid(Nr,Nz)];\n x = [x;u(:);zeros(Nr*Nz,1)];\n y = [y;zeros(Nr*Nz,1);-u(:)];\n z = [z;v(:);v(:)];\ncase 'cone'\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz));\n Tri = trigrid(Nth,Nz);\n x = v(:).*cos(u(:));\n y = v(:).*sin(u(:));\n z = v(:);\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nr));\n Tri = [Tri;Nth*Nz+trigrid(Nth,Nr);];\n x = [x;v(:).*cos(u(:));];\n y = [y;v(:).*sin(u(:));];\n z = [z;ones(Nth*Nr,1)];\ncase 'double cone'\n Nz = floor(Nz/2)*2+1;\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz));\n Tri = trigrid(Nth,Nz);\n r = 1 - abs(2*v(:) - 1);\n x = r.*cos(u(:));\n y = r.*sin(u(:));\n z = v(:);\ncase 'hexacone'\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz));\n Tri = trigrid(Nth,Nz);\n r = 0.92./max(max(abs(cos(u)),abs(cos(u - pi/3))),abs(cos(u + pi/3)));\n x = v(:).*cos(u(:)).*r(:);\n y = v(:).*sin(u(:)).*r(:);\n z = v(:);\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nr));\n Tri = [Tri;Nth*Nz+trigrid(Nth,Nr);];\n v = 0.92*v./max(max(abs(cos(u)),abs(cos(u - pi/3))),abs(cos(u + pi/3)));\n x = [x;v(:).*cos(u(:));];\n y = [y;v(:).*sin(u(:));];\n z = [z;ones(Nth*Nr,1)];\ncase 'double hexacone'\n Nz = floor(Nz/2)*2+1;\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz));\n Tri = trigrid(Nth,Nz);\n r = 1 - abs(2*v - 1);\n r = 0.92*r./max(max(abs(cos(u)),abs(cos(u - pi/3))),abs(cos(u + pi/3)));\n x = r(:).*cos(u(:));\n y = r(:).*sin(u(:));\n z = v(:); \ncase 'blobs'\n Nz = 47;\n [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz));\n Tri = trigrid(Nth,Nz);\n r = sin(v(:)*pi*3).^2.*(1 - 0.6*abs(2*v(:) - 1));\n x = r.*cos(u(:));\n y = r.*sin(u(:));\n z = v(:); \nend\nreturn;\n\nfunction Tri = trigrid(Nu,Nv)\n% Construct the connectivity data for a grid of triangular patches\ni = (1:(Nu-1)*Nv-1).';\ni(Nv:Nv:end) = [];\nTri = [i,i+1,i+Nv;i+1,i+Nv+1,i+Nv];\nreturn;\n\n", "meta": {"author": "taoshiqian", "repo": "image_SDR_to_HDR", "sha": "37a2d6976edad995d5273f3316b13a1ce6d8e28b", "save_path": "github-repos/MATLAB/taoshiqian-image_SDR_to_HDR", "path": "github-repos/MATLAB/taoshiqian-image_SDR_to_HDR/image_SDR_to_HDR-37a2d6976edad995d5273f3316b13a1ce6d8e28b/colorspace/colorspace_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3922225509067182}}
{"text": "function [Ep,Cp,Eh,F,L,dFdp,dFdpp] = spm_nlsi_GN(M,U,Y)\n% Bayesian inversion of nonlinear models - Gauss-Newton/Variational Laplace\n% FORMAT [Ep,Cp,Eh,F] = spm_nlsi_GN(M,U,Y)\n%\n% [Dynamic] MIMO models\n%__________________________________________________________________________\n%\n% M.IS - function name f(P,M,U) - generative model\n% This function specifies the nonlinear model:\n% y = Y.y = IS(P,M,U) + X0*P0 + e\n% where e ~ N(0,C). For dynamic systems this would be an integration\n% scheme (e.g. spm_int). spm_int expects the following:\n%\n% M.f - f(x,u,P,M)\n% M.g - g(x,u,P,M)\n% M.h - h(x,u,P,M)\n% x - state variables\n% u - inputs or causes\n% P - free parameters\n% M - fixed functional forms and parameters in M\n%\n% M.FS - function name f(y,M) - feature selection\n% This [optional] function performs feature selection assuming the\n% generalized model y = FS(y,M) = FS(IS(P,M,U),M) + X0*P0 + e\n%\n% M.P - starting estimates for model parameters [optional]\n%\n% M.pE - prior expectation - E{P} of model parameters\n% M.pC - prior covariance - Cov{P} of model parameters\n%\n% M.hE - prior expectation - E{h} of log-precision parameters\n% M.hC - prior covariance - Cov{h} of log-precision parameters\n%\n% U.u - inputs (or just U)\n% U.dt - sampling interval\n%\n% Y.y - outputs (samples x observations x ...)\n% Y.dt - sampling interval for outputs\n% Y.X0 - confounds or null space (over size(y,1) samples or all vec(y))\n% Y.Q - q error precision components (over size(y,1) samples or all vec(y))\n%\n%\n% Parameter estimates\n%--------------------------------------------------------------------------\n% Ep - (p x 1) conditional expectation E{P|y}\n% Cp - (p x p) conditional covariance Cov{P|y}\n% Eh - (q x 1) conditional log-precisions E{h|y}\n%\n% log evidence\n%--------------------------------------------------------------------------\n% F - [-ve] free energy F = log evidence = p(y|f,g,pE,pC) = p(y|m)\n%\n%__________________________________________________________________________\n% Returns the moments of the posterior p.d.f. of the parameters of a\n% nonlinear model specified by IS(P,M,U) under Gaussian assumptions.\n% Usually, IS is an integrator of a dynamic MIMO input-state-output model\n%\n% dx/dt = f(x,u,P)\n% y = g(x,u,P) + X0*P0 + e\n%\n% A static nonlinear observation model with fixed input or causes u\n% obtains when x = []. i.e.\n%\n% y = g([],u,P) + X0*P0e + e\n%\n% but static nonlinear models are specified more simply using\n%\n% y = IS(P,M,U) + X0*P0 + e\n%\n% Priors on the free parameters P are specified in terms of expectation pE\n% and covariance pC. The E-Step uses a Fisher-Scoring scheme and a Laplace\n% approximation to estimate the conditional expectation and covariance of P\n% If the free-energy starts to increase, an abbreviated descent is\n% invoked. The M-Step estimates the precision components of e, in terms\n% of log-precisions. Although these two steps can be thought of in\n% terms of E and N steps they are in fact variational steps of a full\n% variational Laplace scheme that accommodates conditional uncertainty\n% over both parameters and log precisions (c.f. hyperparameters with hyper\n% priors)\n%\n% An optional feature selection can be specified with parameters M.FS.\n%\n% For generic aspects of the scheme see:\n%\n% Friston K, Mattout J, Trujillo-Barreto N, Ashburner J, Penny W.\n% Variational free energy and the Laplace approximation.\n% NeuroImage. 2007 Jan 1;34(1):220-34.\n%\n% This scheme handels complex data along the lines originally described in:\n%\n% Sehpard RJ, Lordan BP, and Grant EH.\n% Least squares analysis of complex data with applications to permittivity\n% measurements.\n% J. Phys. D. Appl. Phys 1970 3:1759-1764.\n%\n%__________________________________________________________________________\n% Copyright (C) 2001-2015 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_nlsi_GN.m 7279 2018-03-10 21:22:44Z karl $\n\n% options\n%--------------------------------------------------------------------------\ntry, M.nograph; catch, M.nograph = 0; end\ntry, M.noprint; catch, M.noprint = 0; end\ntry, M.Nmax; catch, M.Nmax = 128; end\n\n% figure (unless disabled)\n%--------------------------------------------------------------------------\nif ~M.nograph\n Fsi = spm_figure('GetWin','SI');\nend\n\n% check integrator\n%--------------------------------------------------------------------------\ntry\n M.IS;\ncatch\n M.IS = 'spm_int';\nend\n\n% composition of feature selection and prediction (usually an integrator)\n%--------------------------------------------------------------------------\ntry\n y = Y.y;\ncatch\n y = Y;\nend\n\ntry\n \n % try FS(y,M)\n %----------------------------------------------------------------------\n try\n y = feval(M.FS,y,M);\n IS = inline([M.FS '(' M.IS '(P,M,U),M)'],'P','M','U');\n \n % try FS(y)\n %------------------------------------------------------------------\n catch\n y = feval(M.FS,y);\n IS = inline([M.FS '(' M.IS '(P,M,U))'],'P','M','U');\n end\n \ncatch\n \n % otherwise FS(y) = y\n %----------------------------------------------------------------------\n try\n IS = inline([M.IS '(P,M,U)'],'P','M','U');\n catch\n IS = M.IS;\n end\nend\n\n% converted to function handle\n%--------------------------------------------------------------------------\nIS = spm_funcheck(IS);\n\n% paramter update eqation\n%--------------------------------------------------------------------------\nif isfield(M,'f'), M.f = spm_funcheck(M.f); end\nif isfield(M,'g'), M.g = spm_funcheck(M.g); end\nif isfield(M,'h'), M.h = spm_funcheck(M.h); end\n\n\n% size of data (samples x response component x response component ...)\n%--------------------------------------------------------------------------\nif iscell(y)\n ns = size(y{1},1);\nelse\n ns = size(y,1);\nend\nny = length(spm_vec(y)); % total number of response variables\nnr = ny/ns; % number response components\nM.ns = ns; % number of samples M.ns\n\n% initial states\n%--------------------------------------------------------------------------\ntry\n M.x;\ncatch\n if ~isfield(M,'n'), M.n = 0; end\n M.x = sparse(M.n,1);\nend\n\n% input\n%--------------------------------------------------------------------------\ntry\n U;\ncatch\n U = [];\nend\n\n% initial parameters\n%--------------------------------------------------------------------------\ntry\n spm_vec(M.P) - spm_vec(M.pE);\n fprintf('\\nParameter initialisation successful\\n')\ncatch\n M.P = M.pE;\nend\n\n% time-step\n%--------------------------------------------------------------------------\ntry\n dt = Y.dt;\ncatch\n dt = 1;\nend\n\n% precision components Q\n%--------------------------------------------------------------------------\ntry\n Q = Y.Q;\n if isnumeric(Q), Q = {Q}; end\ncatch\n Q = spm_Ce(ns*ones(1,nr));\nend\nnh = length(Q); % number of precision components\nnq = ny/length(Q{1}); % for compact Kronecker form of M-step\n\n\n% prior moments (assume uninformative priors if not specifed)\n%--------------------------------------------------------------------------\npE = M.pE;\ntry\n pC = M.pC;\ncatch\n np = spm_length(M.pE);\n pC = speye(np,np)*exp(16);\nend\n\n% confounds (if specified)\n%--------------------------------------------------------------------------\ntry\n nb = size(Y.X0,1); % number of bins\n nx = ny/nb; % number of blocks\n dfdu = kron(speye(nx,nx),Y.X0);\ncatch\n dfdu = sparse(ny,0);\nend\nif isempty(dfdu), dfdu = sparse(ny,0); end\n\n\n% hyperpriors - expectation (and initialize hyperparameters)\n%--------------------------------------------------------------------------\ntry\n hE = M.hE;\n if length(hE) ~= nh\n hE = hE + sparse(nh,1);\n end\ncatch\n hE = sparse(nh,1) - log(var(spm_vec(y))) + 4;\nend\nh = hE;\n\n% hyperpriors - covariance\n%--------------------------------------------------------------------------\ntry\n ihC = spm_inv(M.hC);\n if length(ihC) ~= nh\n ihC = ihC*speye(nh,nh);\n end\ncatch\n ihC = speye(nh,nh)*exp(4);\nend\n\n\n% unpack covariance\n%--------------------------------------------------------------------------\nif isstruct(pC);\n pC = spm_diag(spm_vec(pC));\nend\n\n% dimension reduction of parameter space\n%--------------------------------------------------------------------------\nV = spm_svd(pC,0);\nnu = size(dfdu,2); % number of parameters (confounds)\nnp = size(V,2); % number of parameters (effective)\nip = (1:np)';\niu = (1:nu)' + np;\n\n% second-order moments (in reduced space)\n%--------------------------------------------------------------------------\npC = V'*pC*V;\nuC = speye(nu,nu)/1e-8;\nipC = inv(spm_cat(spm_diag({pC,uC})));\n\n% initialize conditional density\n%--------------------------------------------------------------------------\nEu = spm_pinv(dfdu)*spm_vec(y);\np = [V'*(spm_vec(M.P) - spm_vec(M.pE)); Eu];\nEp = spm_unvec(spm_vec(pE) + V*p(ip),pE);\n\n\n% EM\n%==========================================================================\ncriterion = [0 0 0 0];\n\nC.F = -Inf; % free energy\nv = -4; % log ascent rate\ndFdh = zeros(nh,1);\ndFdhh = zeros(nh,nh);\nfor k = 1:M.Nmax\n \n % time\n %----------------------------------------------------------------------\n tStart = tic;\n \n % E-Step: prediction f, and gradients; dfdp\n %======================================================================\n try\n \n % gradients\n %------------------------------------------------------------------\n [dfdp,f] = spm_diff(IS,Ep,M,U,1,{V});\n dfdp = reshape(spm_vec(dfdp),ny,np);\n \n % check for stability\n %------------------------------------------------------------------\n normdfdp = norm(dfdp,'inf');\n revert = isnan(normdfdp) || normdfdp > exp(32);\n \n catch\n revert = true;\n end\n \n if revert && k > 1\n for i = 1:4\n \n % reset expansion point and increase regularization\n %--------------------------------------------------------------\n v = min(v - 2,-4);\n \n % E-Step: update\n %--------------------------------------------------------------\n p = C.p + spm_dx(dFdpp,dFdp,{v});\n Ep = spm_unvec(spm_vec(pE) + V*p(ip),pE);\n \n % try again\n %--------------------------------------------------------------\n try\n [dfdp,f] = spm_diff(IS,Ep,M,U,1,{V});\n dfdp = reshape(spm_vec(dfdp),ny,np);\n \n % check for stability\n %----------------------------------------------------------\n normdfdp = norm(dfdp,'inf');\n revert = isnan(normdfdp) || normdfdp > exp(32);\n \n catch\n revert = true;\n end\n \n % break\n %--------------------------------------------------------------\n if ~revert, break, end\n \n end\n end\n \n % convergence failure\n %----------------------------------------------------------------------\n if revert\n error('SPM:spm_nlsi_GN','Convergence failure.');\n end\n \n \n % prediction error and full gradients\n %----------------------------------------------------------------------\n e = spm_vec(y) - spm_vec(f) - dfdu*p(iu);\n J = -[dfdp dfdu];\n \n \n % M-step: Fisher scoring scheme to find h = max{F(p,h)}\n %======================================================================\n for m = 1:8\n \n % precision and conditional covariance\n %------------------------------------------------------------------\n iS = sparse(0);\n for i = 1:nh\n iS = iS + Q{i}*(exp(-32) + exp(h(i)));\n end\n S = spm_inv(iS);\n iS = kron(speye(nq),iS);\n Pp = real(J'*iS*J);\n Cp = spm_inv(Pp + ipC);\n \n % precision operators for M-Step\n %------------------------------------------------------------------\n for i = 1:nh\n P{i} = Q{i}*exp(h(i));\n PS{i} = P{i}*S;\n P{i} = kron(speye(nq),P{i});\n JPJ{i} = real(J'*P{i}*J);\n end\n \n % derivatives: dLdh = dL/dh,...\n %------------------------------------------------------------------\n for i = 1:nh\n dFdh(i,1) = trace(PS{i})*nq/2 ...\n - real(e'*P{i}*e)/2 ...\n - spm_trace(Cp,JPJ{i})/2;\n for j = i:nh\n dFdhh(i,j) = - spm_trace(PS{i},PS{j})*nq/2;\n dFdhh(j,i) = dFdhh(i,j);\n end\n end\n \n % add hyperpriors\n %------------------------------------------------------------------\n d = h - hE;\n dFdh = dFdh - ihC*d;\n dFdhh = dFdhh - ihC;\n Ch = spm_inv(real(-dFdhh));\n \n % update ReML estimate\n %------------------------------------------------------------------\n dh = spm_dx(dFdhh,dFdh,{4});\n dh = min(max(dh,-1),1);\n h = h + dh;\n \n % convergence\n %------------------------------------------------------------------\n dF = dFdh'*dh;\n if dF < 1e-2, break, end\n \n end\n \n \n % E-Step with Levenberg-Marquardt regularization\n %======================================================================\n \n % objective function: F(p) = log evidence - divergence\n %----------------------------------------------------------------------\n L(1) = spm_logdet(iS)*nq/2 - real(e'*iS*e)/2 - ny*log(8*atan(1))/2; ...\n L(2) = spm_logdet(ipC*Cp)/2 - p'*ipC*p/2;\n L(3) = spm_logdet(ihC*Ch)/2 - d'*ihC*d/2;\n F = sum(L);\n \n % record increases and reference log-evidence for reporting\n %----------------------------------------------------------------------\n try\n F0;\n if ~M.noprint\n fprintf(' actual: %.3e (%.2f sec)\\n',full(F - C.F),toc(tStart))\n end\n catch\n F0 = F;\n end\n \n % if F has increased, update gradients and curvatures for E-Step\n %----------------------------------------------------------------------\n if F > C.F || k < 3\n \n % accept current estimates\n %------------------------------------------------------------------\n C.p = p;\n C.h = h;\n C.F = F;\n C.L = L;\n C.Cp = Cp;\n \n % E-Step: Conditional update of gradients and curvature\n %------------------------------------------------------------------\n dFdp = -real(J'*iS*e) - ipC*p;\n dFdpp = -real(J'*iS*J) - ipC;\n \n % decrease regularization\n %------------------------------------------------------------------\n v = min(v + 1/2,4);\n str = 'EM:(+)';\n \n else\n \n % reset expansion point\n %------------------------------------------------------------------\n p = C.p;\n h = C.h;\n Cp = C.Cp;\n \n % and increase regularization\n %------------------------------------------------------------------\n v = min(v - 2,-4);\n str = 'EM:(-)';\n \n end\n \n % E-Step: update\n %======================================================================\n dp = spm_dx(dFdpp,dFdp,{v});\n p = p + dp;\n Ep = spm_unvec(spm_vec(pE) + V*p(ip),pE);\n \n \n \n % Graphics\n %======================================================================\n if exist('Fsi', 'var')\n spm_figure('Select', Fsi)\n \n \n % reshape prediction if necessary\n %------------------------------------------------------------------\n e = spm_vec(e);\n f = spm_vec(f);\n try\n e = reshape(e,ns,nr);\n f = reshape(f,ns,nr);\n end\n \n % subplot prediction\n %------------------------------------------------------------------\n x = (1:size(e,1))*dt;\n xLab = 'time (seconds)';\n try\n if length(M.Hz) == ns\n x = M.Hz;\n xLab = 'Frequency (Hz)';\n end\n end\n \n \n % plot real or complex predictions\n %------------------------------------------------------------------\n tstr = sprintf('%s: %i','prediction and response: E-Step',k);\n if isreal(spm_vec(y))\n \n subplot(2,1,1)\n plot(x,real(f)), hold on\n plot(x,real(f + e),':'), hold off\n xlabel(xLab)\n title(tstr,'FontSize',16)\n grid on\n \n else\n subplot(2,2,1)\n plot(x,real(f)), hold on\n plot(x,real(f + e),':'), hold off\n xlabel(xLab)\n ylabel('real')\n title(tstr,'FontSize',16)\n grid on\n \n subplot(2,2,2)\n plot(x,imag(f)), hold on\n plot(x,imag(f + e),':'), hold off\n xlabel(xLab)\n ylabel('imaginary')\n title(tstr,'FontSize',16)\n grid on\n end\n \n % subplot parameters\n %--------------------------------------------------------------\n subplot(2,1,2)\n bar(full(V*p(ip)))\n xlabel('parameter')\n tstr = 'conditional [minus prior] expectation';\n title(tstr,'FontSize',16)\n grid on\n drawnow\n \n end\n \n % convergence\n %----------------------------------------------------------------------\n dF = dFdp'*dp;\n if ~M.noprint\n fprintf('%-6s: %i %6s %-6.3e %6s %.3e ',str,k,'F:',full(C.F - F0),'dF predicted:',full(dF))\n end\n criterion = [(dF < 1e-1) criterion(1:end - 1)];\n if all(criterion)\n if ~M.noprint\n fprintf(' convergence\\n')\n end\n break\n end\n \nend\n\nif exist('Fsi', 'var')\n spm_figure('Focus', Fsi)\nend\n\n% outputs\n%--------------------------------------------------------------------------\nEp = spm_unvec(spm_vec(pE) + V*C.p(ip),pE);\nCp = V*C.Cp(ip,ip)*V';\nEh = C.h;\nF = C.F;\nL = C.L;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_nlsi_GN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3921251867086304}}
{"text": "%{\n * Copyright (C) 2013-2020, The Regents of The University of Michigan.\n * All rights reserved.\n * This software was developed in the Biped Lab (https://www.biped.solutions/) \n * under the direction of Jessy Grizzle, grizzle@umich.edu. This software may \n * be available under alternative licensing terms; contact the address above.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the Regents of The University of Michigan.\n * \n * AUTHOR: Bruce JK Huang (bjhuang[at]umich.edu)\n * WEBSITE: https://www.brucerobot.com/\n%}\n\nfunction cost = costIoU(theta_x, theta_y, theta_z, T, X, Y, intrinsic)\n H = eye(4);\n H(1:3,1:3) = rotx(theta_x) * roty(theta_y) * rotz(theta_z);\n H(1:3,4) = T';\n P = intrinsic * [eye(3) zeros(3,1)] * H;\n L_X_transformed = P * X; % transformed points in LiDAR frame\n C_X_transformed = L_X_transformed ./ L_X_transformed(3,:);\n cost = 0;\n for i=1:size(C_X_transformed,2)/4\n k = 4*(i-1) + 1;\n vertices_X = [C_X_transformed(1,k) C_X_transformed(1,k+1) C_X_transformed(1,k+3) C_X_transformed(1,k+2); \n C_X_transformed(2,k) C_X_transformed(2,k+1) C_X_transformed(2,k+3) C_X_transformed(2,k+2)];\n vertices_Y = [Y(1,k) Y(1,k+1) Y(1,k+3) Y(1,k+2); \n Y(2,k) Y(2,k+1) Y(2,k+3) Y(2,k+2)];\n% vertices_X = C_X_transformed(1:2,k:k+3);\n% vertices_Y = Y(1:2,k:k+3);\n \n% conv_X = convhull(vertices_X(1,:)', vertices_X(2,:)');\n% conv_Y = convhull(vertices_Y(1,:)', vertices_Y(2,:)');\n% [vertices_X(1,:), vertices_X(2,:)] = poly2cw(vertices_X(1,conv_X(1:4)), vertices_X(2,conv_X(1:4)));\n% [vertices_Y(1,:), vertices_Y(2,:)] = poly2cw(vertices_Y(1,conv_Y(1:4)), vertices_Y(2,conv_Y(1:4)));\n% pgon_X = polyshape(vertices_X(1,conv_X), vertices_X(2,conv_X));\n% pgon_Y = polyshape(vertices_Y(1,conv_Y), vertices_Y(2,conv_Y));\n \n [vertices_X(1,:), vertices_X(2,:)] = poly2cw(vertices_X(1, :), vertices_X(2, :));\n [vertices_Y(1,:), vertices_Y(2,:)] = poly2cw(vertices_Y(1, :), vertices_Y(2, :));\n \n pgon_X = polyshape(vertices_X(1, :), vertices_X(2, :));\n pgon_Y = polyshape(vertices_Y(1, :), vertices_Y(2, :));\n if all(issimplified([pgon_X, pgon_Y]))\n [I_polyout,~,~] = intersect(pgon_X, pgon_Y);\n\n [U_polyout,~,~] = union(pgon_X ,pgon_Y);\n I_area = max(area(I_polyout), 1e-5);\n U_area = area(U_polyout);\n cost = cost + I_area/U_area;\n else\n cost = -1e3;\n end\n end\n cost = -cost;\nend", "meta": {"author": "UMich-BipedLab", "repo": "extrinsic_lidar_camera_calibration", "sha": "d423c81e95c6de595e1dff79871385348b1c68f4", "save_path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration", "path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration/extrinsic_lidar_camera_calibration-d423c81e95c6de595e1dff79871385348b1c68f4/costIoU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3920874904722493}}
{"text": "function varargout = colorspace(Conversion,varargin)\n%COLORSPACE Transform a color image between color representations.\n% B = COLORSPACE(S,A) transforms the color representation of image A\n% where S is a string specifying the conversion. The input array A \n% should be a real full double array of size Mx3 or MxNx3. The output B \n% is the same size as A.\n%\n% S tells the source and destination color spaces, S = 'dest<-src', or \n% alternatively, S = 'src->dest'. Supported color spaces are\n%\n% 'RGB' sRGB IEC 61966-2-1\n% 'YCbCr' Luma + Chroma (\"digitized\" version of Y'PbPr)\n% 'JPEG-YCbCr' Luma + Chroma space used in JFIF JPEG\n% 'YDbDr' SECAM Y'DbDr Luma + Chroma\n% 'YPbPr' Luma (ITU-R BT.601) + Chroma \n% 'YUV' NTSC PAL Y'UV Luma + Chroma\n% 'YIQ' NTSC Y'IQ Luma + Chroma\n% 'HSV' or 'HSB' Hue Saturation Value/Brightness\n% 'HSL' or 'HLS' Hue Saturation Luminance\n% 'HSI' Hue Saturation Intensity\n% 'XYZ' CIE 1931 XYZ\n% 'Lab' CIE 1976 L*a*b* (CIELAB)\n% 'Luv' CIE L*u*v* (CIELUV)\n% 'LCH' CIE L*C*H* (CIELCH)\n% 'CAT02 LMS' CIE CAT02 LMS\n%\n% All conversions assume 2 degree observer and D65 illuminant.\n%\n% Color space names are case insensitive and spaces are ignored. When \n% sRGB is the source or destination, it can be omitted. For example \n% 'yuv<-' is short for 'yuv<-rgb'.\n%\n% For sRGB, the values should be scaled between 0 and 1. Beware that \n% transformations generally do not constrain colors to be \"in gamut.\" \n% Particularly, transforming from another space to sRGB may obtain \n% R'G'B' values outside of the [0,1] range. So the result should be \n% clamped to [0,1] before displaying:\n% image(min(max(B,0),1)); % Clamp B to [0,1] and display\n%\n% sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard\n% red-green-blue representation of colors used in digital imaging. The \n% components should be scaled between 0 and 1. The space can be \n% visualized geometrically as a cube.\n% \n% Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear\n% transformations. These spaces separate a color into a grayscale\n% luminance component Y and two chroma components. The valid ranges of\n% the components depends on the space.\n%\n% HSV (Hue Saturation Value) is related to sRGB by\n% H = hexagonal hue angle (0 <= H < 360),\n% S = C/V (0 <= S <= 1),\n% V = max(R',G',B') (0 <= V <= 1),\n% where C = max(R',G',B') - min(R',G',B'). The hue angle H is computed on\n% a hexagon. The space is geometrically a hexagonal cone.\n%\n% HSL (Hue Saturation Lightness) is related to sRGB by\n% H = hexagonal hue angle (0 <= H < 360),\n% S = C/(1 - |2L-1|) (0 <= S <= 1),\n% L = (max(R',G',B') + min(R',G',B'))/2 (0 <= L <= 1),\n% where H and C are the same as in HSV. Geometrically, the space is a\n% double hexagonal cone.\n%\n% HSI (Hue Saturation Intensity) is related to sRGB by\n% H = polar hue angle (0 <= H < 360),\n% S = 1 - min(R',G',B')/I (0 <= S <= 1),\n% I = (R'+G'+B')/3 (0 <= I <= 1).\n% Unlike HSV and HSL, the hue angle H is computed on a circle rather than\n% a hexagon. \n%\n% CIE XYZ is related to sRGB by inverse gamma correction followed by a\n% linear transform. Other CIE color spaces are defined relative to XYZ.\n%\n% CIE L*a*b*, L*u*v*, and L*C*H* are nonlinear functions of XYZ. The L*\n% component is designed to match closely with human perception of\n% lightness. The other two components describe the chroma.\n%\n% CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02 \n% chromatic adaptation matrix. The space is designed to model the \n% response of the three types of cones in the human eye, where L, M, S,\n% correspond respectively to red (\"long\"), green (\"medium\"), and blue\n% (\"short\").\n%\n% Author::\n% Pascal Getreuer 2005-2010\n\n\n%%% Input parsing %%%\nif nargin < 2, error('Not enough input arguments.'); end\n[SrcSpace,DestSpace] = parse(Conversion);\n\nif nargin == 2\n Image = varargin{1};\nelseif nargin >= 3\n Image = cat(3,varargin{:});\nelse\n error('Invalid number of input arguments.');\nend\n\nFlipDims = (size(Image,3) == 1);\n\nif FlipDims, Image = permute(Image,[1,3,2]); end\nif ~isa(Image,'double'), Image = double(Image)/255; end\nif size(Image,3) ~= 3, error('Invalid input size.'); end\n\nSrcT = gettransform(SrcSpace);\nDestT = gettransform(DestSpace);\n\nif ~ischar(SrcT) && ~ischar(DestT)\n % Both source and destination transforms are affine, so they\n % can be composed into one affine operation\n T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)]; \n Temp = zeros(size(Image));\n Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);\n Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);\n Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);\n Image = Temp;\nelseif ~ischar(DestT)\n Image = rgb(Image,SrcSpace);\n Temp = zeros(size(Image));\n Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);\n Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);\n Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);\n Image = Temp;\nelse\n Image = feval(DestT,Image,SrcSpace);\nend\n\n%%% Output format %%%\nif nargout > 1\n varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};\nelse\n if FlipDims, Image = permute(Image,[1,3,2]); end\n varargout = {Image};\nend\n\nreturn;\n\n\nfunction [SrcSpace,DestSpace] = parse(Str)\n% Parse conversion argument\n\nif ischar(Str)\n Str = lower(strrep(strrep(Str,'-',''),'=',''));\n k = find(Str == '>');\n \n if length(k) == 1 % Interpret the form 'src->dest'\n SrcSpace = Str(1:k-1);\n DestSpace = Str(k+1:end);\n else\n k = find(Str == '<');\n \n if length(k) == 1 % Interpret the form 'dest<-src'\n DestSpace = Str(1:k-1);\n SrcSpace = Str(k+1:end);\n else\n error(['Invalid conversion, ''',Str,'''.']);\n end \n end\n \n SrcSpace = alias(SrcSpace);\n DestSpace = alias(DestSpace);\nelse\n SrcSpace = 1; % No source pre-transform\n DestSpace = Conversion;\n if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end\nend\nreturn;\n\n\nfunction Space = alias(Space)\nSpace = strrep(strrep(Space,'cie',''),' ','');\n\nif isempty(Space)\n Space = 'rgb';\nend\n\nswitch Space\ncase {'ycbcr','ycc'}\n Space = 'ycbcr';\ncase {'hsv','hsb'}\n Space = 'hsv';\ncase {'hsl','hsi','hls'}\n Space = 'hsl';\ncase {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}\n return;\nend\nreturn;\n\n\nfunction T = gettransform(Space)\n% Get a colorspace transform: either a matrix describing an affine transform,\n% or a string referring to a conversion subroutine\nswitch Space\ncase 'ypbpr'\n T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];\ncase 'yuv'\n % sRGB to NTSC/PAL YUV\n % Wikipedia: http://en.wikipedia.org/wiki/YUV\n T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];\ncase 'ydbdr'\n % sRGB to SECAM YDbDr\n % Wikipedia: http://en.wikipedia.org/wiki/YDbDr\n T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];\ncase 'yiq'\n % sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];\n % Wikipedia: http://en.wikipedia.org/wiki/YIQ\n T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];\ncase 'ycbcr'\n % sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr\n % Wikipedia: http://en.wikipedia.org/wiki/YCbCr\n % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion\n T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];\ncase 'jpegycbcr'\n % Wikipedia: http://en.wikipedia.org/wiki/YCbCr\n T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;\ncase {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'}\n T = Space;\notherwise\n error(['Unknown color space, ''',Space,'''.']);\nend\nreturn;\n\n\nfunction Image = rgb(Image,SrcSpace)\n% Convert to sRGB from 'SrcSpace'\nswitch SrcSpace\ncase 'rgb'\n return;\ncase 'hsv'\n % Convert HSV to sRGB\n Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));\ncase 'hsl'\n % Convert HSL to sRGB\n L = Image(:,:,3);\n Delta = Image(:,:,2).*min(L,1-L);\n Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));\ncase {'xyz','lab','luv','lch','cat02lms'}\n % Convert to CIE XYZ\n Image = xyz(Image,SrcSpace);\n % Convert XYZ to RGB\n T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057];\n R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R\n G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G\n B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B\n % Desaturate and rescale to constrain resulting RGB values to [0,1] \n AddWhite = -min(min(min(R,G),B),0);\n R = R + AddWhite;\n G = G + AddWhite;\n B = B + AddWhite;\n % Apply gamma correction to convert linear RGB to sRGB\n Image(:,:,1) = gammacorrection(R); % R'\n Image(:,:,2) = gammacorrection(G); % G'\n Image(:,:,3) = gammacorrection(B); % B'\notherwise % Conversion is through an affine transform\n T = gettransform(SrcSpace);\n temp = inv(T(:,1:3));\n T = [temp,-temp*T(:,4)];\n R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);\n G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);\n B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);\n Image(:,:,1) = R;\n Image(:,:,2) = G;\n Image(:,:,3) = B;\nend\n\n% Clip to [0,1]\nImage = min(max(Image,0),1);\nreturn;\n\n\nfunction Image = xyz(Image,SrcSpace)\n% Convert to CIE XYZ from 'SrcSpace'\nWhitePoint = [0.950456,1,1.088754]; \n\nswitch SrcSpace\ncase 'xyz'\n return;\ncase 'luv'\n % Convert CIE L*uv to XYZ\n WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\n WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\n L = Image(:,:,1);\n Y = (L + 16)/116;\n Y = invf(Y)*WhitePoint(2);\n U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;\n V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;\n Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X\n Image(:,:,2) = Y; % Y\n Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z\ncase {'lab','lch'}\n Image = lab(Image,SrcSpace);\n % Convert CIE L*ab to XYZ\n fY = (Image(:,:,1) + 16)/116;\n fX = fY + Image(:,:,2)/500;\n fZ = fY - Image(:,:,3)/200;\n Image(:,:,1) = WhitePoint(1)*invf(fX); % X\n Image(:,:,2) = WhitePoint(2)*invf(fY); % Y\n Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z\ncase 'cat02lms'\n % Convert CAT02 LMS to XYZ\n T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]);\n L = Image(:,:,1);\n M = Image(:,:,2);\n S = Image(:,:,3);\n Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X \n Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y\n Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z\notherwise % Convert from some gamma-corrected space\n % Convert to sRGB\n Image = rgb(Image,SrcSpace);\n % Undo gamma correction\n R = invgammacorrection(Image(:,:,1));\n G = invgammacorrection(Image(:,:,2));\n B = invgammacorrection(Image(:,:,3));\n % Convert RGB to XYZ\n T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]);\n Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X \n Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y\n Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z\nend\nreturn;\n\n\nfunction Image = hsv(Image,SrcSpace)\n% Convert to HSV\nImage = rgb(Image,SrcSpace);\nV = max(Image,[],3);\nS = (V - min(Image,[],3))./(V + (V == 0));\nImage(:,:,1) = rgbtohue(Image);\nImage(:,:,2) = S;\nImage(:,:,3) = V;\nreturn;\n\n\nfunction Image = hsl(Image,SrcSpace)\n% Convert to HSL \nswitch SrcSpace\ncase 'hsv'\n % Convert HSV to HSL \n MaxVal = Image(:,:,3);\n MinVal = (1 - Image(:,:,2)).*MaxVal;\n L = 0.5*(MaxVal + MinVal);\n temp = min(L,1-L);\n Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));\n Image(:,:,3) = L;\notherwise\n Image = rgb(Image,SrcSpace); % Convert to sRGB\n % Convert sRGB to HSL\n MinVal = min(Image,[],3);\n MaxVal = max(Image,[],3);\n L = 0.5*(MaxVal + MinVal);\n temp = min(L,1-L);\n S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));\n Image(:,:,1) = rgbtohue(Image);\n Image(:,:,2) = S;\n Image(:,:,3) = L;\nend\nreturn;\n\n\nfunction Image = lab(Image,SrcSpace)\n% Convert to CIE L*a*b* (CIELAB)\nWhitePoint = [0.950456,1,1.088754];\n\nswitch SrcSpace\ncase 'lab'\n return;\ncase 'lch'\n % Convert CIE L*CH to CIE L*ab\n C = Image(:,:,2);\n Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a*\n Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b*\notherwise\n Image = xyz(Image,SrcSpace); % Convert to XYZ\n % Convert XYZ to CIE L*a*b*\n X = Image(:,:,1)/WhitePoint(1);\n Y = Image(:,:,2)/WhitePoint(2);\n Z = Image(:,:,3)/WhitePoint(3);\n fX = f(X);\n fY = f(Y);\n fZ = f(Z);\n Image(:,:,1) = 116*fY - 16; % L*\n Image(:,:,2) = 500*(fX - fY); % a*\n Image(:,:,3) = 200*(fY - fZ); % b*\nend\nreturn;\n\n\nfunction Image = luv(Image,SrcSpace)\n% Convert to CIE L*u*v* (CIELUV)\nWhitePoint = [0.950456,1,1.088754];\nWhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\nWhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));\n\nImage = xyz(Image,SrcSpace); % Convert to XYZ\nDenom = Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3);\nU = (4*Image(:,:,1))./(Denom + (Denom == 0));\nV = (9*Image(:,:,2))./(Denom + (Denom == 0));\nY = Image(:,:,2)/WhitePoint(2);\nL = 116*f(Y) - 16;\nImage(:,:,1) = L; % L*\nImage(:,:,2) = 13*L.*(U - WhitePointU); % u*\nImage(:,:,3) = 13*L.*(V - WhitePointV); % v*\nreturn; \n\n\nfunction Image = lch(Image,SrcSpace)\n% Convert to CIE L*ch\nImage = lab(Image,SrcSpace); % Convert to CIE L*ab\nH = atan2(Image(:,:,3),Image(:,:,2));\nH = H*180/pi + 360*(H < 0);\nImage(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C\nImage(:,:,3) = H; % H\nreturn;\n\n\nfunction Image = cat02lms(Image,SrcSpace)\n% Convert to CAT02 LMS\nImage = xyz(Image,SrcSpace);\nT = [0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834];\nX = Image(:,:,1);\nY = Image(:,:,2);\nZ = Image(:,:,3);\nImage(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z; % L\nImage(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z; % M\nImage(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z; % S\nreturn;\n\n\nfunction Image = huetorgb(m0,m2,H)\n% Convert HSV or HSL hue to RGB\nN = size(H);\nH = min(max(H(:),0),360)/60;\nm0 = m0(:);\nm2 = m2(:);\nF = H - round(H/2)*2;\nM = [m0, m0 + (m2-m0).*abs(F), m2];\nNum = length(m0);\nj = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;\nk = floor(H) + 1;\nImage = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);\nreturn;\n\n\nfunction H = rgbtohue(Image)\n% Convert RGB to HSV or HSL hue\n[M,i] = sort(Image,3);\ni = i(:,:,3);\nDelta = M(:,:,3) - M(:,:,1);\nDelta = Delta + (Delta == 0);\nR = Image(:,:,1);\nG = Image(:,:,2);\nB = Image(:,:,3);\nH = zeros(size(R));\nk = (i == 1);\nH(k) = (G(k) - B(k))./Delta(k);\nk = (i == 2);\nH(k) = 2 + (B(k) - R(k))./Delta(k);\nk = (i == 3);\nH(k) = 4 + (R(k) - G(k))./Delta(k);\nH = 60*H + 360*(H < 0);\nH(Delta == 0) = nan;\nreturn;\n\n\nfunction Rp = gammacorrection(R)\nRp = zeros(size(R));\ni = (R <= 0.0031306684425005883);\nRp(i) = 12.92*R(i);\nRp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055);\nreturn;\n\n\nfunction R = invgammacorrection(Rp)\nR = zeros(size(Rp));\ni = (Rp <= 0.0404482362771076);\nR(i) = Rp(i)/12.92;\nR(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4);\nreturn;\n\n\nfunction fY = f(Y)\nfY = real(Y.^(1/3));\ni = (Y < 0.008856);\nfY(i) = Y(i)*(841/108) + (4/29);\nreturn;\n\n\nfunction Y = invf(fY)\nY = fY.^3;\ni = (Y < 0.008856);\nY(i) = (fY(i) - 4/29)*(108/841);\nreturn;\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/colorspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239133, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39204820789155564}}
{"text": "function acc = st_to_cc_values ( nst, ist, jst, ast, ncc, n, icc, ccc )\n\n%*****************************************************************************80\n%\n%% ST_TO_CC_VALUES creates CC values from ST data.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 14 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NST, the number of ST elements.\n%\n% Input, integer IST(NST), JST(NST), the ST rows and columns.\n%\n% Input, real AST(NST), the ST values.\n%\n% Input, integer NCC, the number of CC elements.\n%\n% Input, integer N, the number of columns.\n%\n% Input, integer ICC(NCC), the CC rows.\n%\n% Input, integer CCC(N+1), the CC compressed columns.\n%\n% Output, real ACC(NCC), the CC values.\n%\n acc = zeros ( ncc, 1 );\n\n for kst = 1 : nst\n\n i = ist(kst);\n j = jst(kst);\n\n clo = ccc(j);\n chi = ccc(j+1);\n\n fail = 1;\n\n for kcc = clo : chi - 1\n if ( icc(kcc) == i )\n acc(kcc) = acc(kcc) + ast(kst);\n fail = 0;\n break\n end \n end\n\n if ( fail )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ST_TO_CC_VALUES - Fatal error!\\n' );\n fprintf ( 1, ' ST entry cannot be located in CC array.\\n' );\n fprintf ( 1, ' ST index KST = %d\\n', kst );\n fprintf ( 1, ' ST row IST(KST) = %d\\n', ist(kst) );\n fprintf ( 1, ' ST col JST(KST) = %d\\n', jst(kst) );\n fprintf ( 1, ' ST val AST(KST) = %g\\n', ast(kst) );\n error ( 'ST_TO_CC_VALUES - Fatal error!' );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/st_to_cc/st_to_cc_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.39204820430040094}}
{"text": "function [U,data,SS,R] = arap(V,F,b,bc,varargin)\n % ARAP Solve for the as-rigid-as-possible deformation according to various\n % manifestations including:\n % (1) \"As-rigid-as-possible Surface Modeling\" by [Sorkine and Alexa 2007]\n % (2) \"A local-global approach to mesh parameterization\" by [Liu et al.\n % 2010] or \"A simple geometric model for elastic deformation\" by [Chao et\n % al. 2010]\n % (3) Adapted version of \"As-rigid-as-possible Surface Modeling\" by\n % [Sorkine and Alexa 2007] presented in section 4.2 of or \"A simple\n % geometric model for elastic deformation\" by [Chao et al. 2010]\n %\n % U = arap(V,F,b,bc) given a rest mesh (V,F) and list of constraint vertex\n % indices (b) and their new postions (bc) solve for pose mesh positions (U),\n % using default choice for 'Energy'\n %\n % U = arap(V,F,b,bc,'ParameterName','ParameterValue',...)\n %\n % Inputs:\n % V #V by dim list of rest domain positions\n % F #F by {3|4} list of {triangle|tetrahedra} indices into V\n % b #b list of indices of constraint (boundary) vertices\n % bc #b by dim list of constraint positions for b\n % Optional:\n % 'Energy'\n % followed by a string specifying which arap energy definition to use.\n % One of the following:\n % 'spokes' \"As-rigid-as-possible Surface Modeling\" by [Sorkine and\n % Alexa 2007], rotations defined at vertices affecting incident\n % edges\n % 'elements' \"A local-global approach to mesh parameterization\" by\n % [Liu et al. 2010] or \"A simple geometric model for elastic\n % deformation\" by [Chao et al. 2010], rotations defined at\n % elements (triangles or tets) \n % 'spokes-and-rims' Adapted version of \"As-rigid-as-possible Surface\n % Modeling\" by [Sorkine and Alexa 2007] presented in section 4.2 of\n % or \"A simple geometric model for elastic deformation\" by [Chao et\n % al. 2010], rotations defined at vertices affecting incident\n % edges and opposite edges\n % 'V0' #V by dim list of initial guess positions\n % dim by dim by #C list of linear transformations initial guesses,\n % optional (default is to use identity transformations)\n % 'Data' see output\n % 'Groups'\n % followed by #V list of group indices (1 to k) for each vertex, such \n % that vertex i is assigned to group G(i)\n % 'Tol'\n % stopping critera parameter. If variables (linear transformation matrix\n % entries) change by less than 'tol' the optimization terminates,\n % default is 0.75 (weak tolerance)\n % 'MaxIter'\n % max number of local-global iterations, default is 100\n % 'Dynamic' \n % #V by dim list of external forces\n % 'TimeStep'\n % scalar time step value\n % 'Vm1' \n % #V by dim positions at time t-1\n % 'Tikhonov' followed by constant Tikhonov regularization parameter\n % alpha:\n % http://en.wikipedia.org/wiki/Tikhonov_regularization#Relation_to_probabilistic_formulation\n % 'Youngs' followed by young's modulus (only for dynamics)\n % 'Flat' followed by whether to add the constraint that Z=0 {false}\n % 'RemoveRigid' followed by whether to add a constraint that places an\n % arbitrary point at the origin and another along the x-axis {false}\n % 'Aeq'/'Beq' followed by #Aeq by dim*#V linear equality constraints\n % matrix and righthand sides respectively {[]}/{[]}\n % Outputs:\n % U #V by dim list of new positions\n % data struct of reusable data\n % .CSM dim*n by dim*n sparse matrix containing special laplacians along the\n % diagonal so that when multiplied by repmat(U,dim,1) gives covariance\n % matrix elements, can be used to speed up next time this function is\n % called, see function definitions\n %\n % Known issues: 'Flat',true + 'Energy','elements' should only need a 2D\n % rotation fit, but this does 3D to stay general (e.g. if one were to use\n % 'spokes' then the edge-set cannot be pre-mapped to a common plane)\n %\n % See also: takeo_arap\n %\n\n % parse input\n G = [];\n\n % number of vertices\n n = size(V,1);\n assert(isempty(b) || max(b) <= n,'b should be in bounds [1,size(V,1)]');\n assert(isempty(b) || min(b) >= 1,'b should be in bounds [1,size(V,1)]');\n\n indices = 1:n;\n max_iterations = 100;\n tol = 0.001;\n interior = indices(~ismember(indices,b));\n U = [];\n Vm1 = [];\n youngs = 1.2e9;\n % default is Sorkine and Alexa style local rigidity energy\n energy = [];\n % default is no external forces\n fext = [];\n % defaults is unit time step\n h = 1;\n % Tikhonov regularization alpha\n alpha_tik = 0;\n % flatten/parameterization\n flat = false;\n % remove rigid transformation invariance\n remove_rigid = false;\n G = [];\n debug = false;\n data = [];\n Aeq = [];\n Beq = [];\n ref_data = [];\n weight = [];\n\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Energy','V0','Data','Tikhonov','Groups','Tol', ...\n 'MaxIter','Dynamic','TimeStep','Vm1','RemoveRigid','Debug', ...\n 'Aeq','Beq','Flat','Ref','Weight','Youngs'}, ...\n {'energy','U','data','alpha_tik','G','tol','max_iterations','fext', ...\n 'h','Vm1','remove_rigid','debug','Aeq','Beq','flat','ref_data','weight','youngs'});\n v = 1;\n while v <= numel(varargin)\n param_name = varargin{v};\n if isKey(params_to_variables,param_name)\n assert(v+1<=numel(varargin));\n v = v+1;\n % Trick: use feval on anonymous function to use assignin to this workspace \n feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n else\n error('Unsupported parameter: %s',varargin{v});\n end\n v=v+1;\n end\n\n if isempty(energy)\n switch size(F,2)\n case 4\n energy = 'elements';\n case 3\n energy = 'spokes-and-rims';\n end\n end\n if isempty(fext)\n dynamic = false;\n fext = zeros(size(V));\n else\n dynamic = true;\n end\n\n\n if isempty(data)\n if strcmp(energy,'elements') && numel(G) ~= size(F,1) && numel(G) == n\n % groups are defined per vertex, convert to per face using mode\n data.G = mode(G(F),2);\n else\n data.G = G;\n end\n end\n\n if isempty(data.G)\n k = n;\n else\n k = max(data.G);\n end\n\n ref_map = [];\n if isempty(ref_data)\n if flat\n [ref_V,ref_F,ref_map] = plane_project(V,F);\n assert(strcmp(energy,'elements'),'flat only makes sense with elements');\n else\n ref_V = V;\n ref_F = F;\n end\n else\n ref_V = ref_data{1};\n ref_F = ref_data{2};\n ref_map = ref_data{3};\n end\n dim = size(ref_V,2);\n\n if isempty(bc)\n bc = sparse(0,dim);\n end\n\n assert(dim == size(bc,2));\n assert(size(Aeq,1) == size(Beq,1));\n assert((size(Aeq,2) == 0) || (size(Aeq,2) == dim*size(V,1)));\n\n if isempty(U)\n if(dim == 2) \n U = laplacian_mesh_editing(V,F,b,bc);\n else\n U = V;\n end\n U = U(:,1:dim);\n end\n assert(n == size(U,1));\n assert(dim == size(U,2));\n\n if dynamic\n V0 = U(:,1:dim);\n if isempty(Vm1)\n Vm1 = V0;\n end\n %% This parameter seem good for a 0.1m tall hotdog with h=0.0333\n % Larger --> more rigid\n dyn_alpha = h^2*youngs;\n % Smaller --> more damped\n mom = 1e10;\n M = massmatrix(ref_V,ref_F);\n if ~isempty(ref_map)\n M = ref_map*M*ref_map';\n end\n DQ = 0.5*mom*M;\n Dl = mom*M*(-2*V0 + Vm1) - h^2*fext;\n else\n dyn_alpha = 1;\n DQ = sparse(size(V,1),size(V,1));\n Dl = sparse(size(V,1),dim);\n end\n\n if ~isfield(data,'L') || isempty(data.L)\n if isempty(weight)\n data.L = cotmatrix(ref_V,ref_F);\n else\n wA = doublearea(ref_V,ref_F);\n wG = grad(ref_V,ref_F);\n data.L = -0.5*wG'*( repmat(wA.*weight,dim,1) .* wG);\n end\n\n if ~isempty(ref_map)\n data.L = ref_map*data.L*ref_map';\n end\n end\n\n rr.b = cell(dim,1);\n rr.bc = cell(dim,1);\n if ~isfield(data,'rr')\n data.rr = [];\n if ~isfield(data.rr,'preF')\n data.rr.preF = cell(dim,1);\n end\n end\n if ~isfield(data,'preF')\n data.preF = [];\n end\n if remove_rigid\n if ~isempty(b)\n warning('RemoveRigid`s constraints are not typically wanted if |b|>0');\n end\n % the only danger is picking two points which end up mapped very close to\n % each other\n [~,f] = farthest_points(V,dim);\n for c = 1:dim\n rr.b{c} = f([1:dim-(c-1)])';\n rr.bc{c} = zeros(numel(rr.b{c}),1);\n end\n % Immediately remove rigid transformation from initial guess\n U = bsxfun(@minus,U,U(f(1),:));\n % We know that f(1) is at origin\n switch dim\n case 3\n % rotate about y-axis so that f(2) has (x=0)\n theta = atan2(U(f(2),1),U(f(2),3));\n R = axisangle2matrix([0 1 0],theta);\n U = U*R;\n % rotate about x-axis so that f(2) has (y=0)\n theta = atan2(U(f(2),3),U(f(2),2))+pi/2;\n R = axisangle2matrix([1 0 0],theta);\n U = U*R;\n % rotate about z-axis so that f(3) has (x=0)\n theta = atan2(U(f(3),2),U(f(3),1))+pi/2;\n R = axisangle2matrix([0 0 1],theta);\n U = U*R;\n case 2\n % rotate so that f(2) is on y-axis (x=0)\n theta = atan2(U(f(2),2),U(f(2),1))+pi/2;\n R = [cos(theta) -sin(theta);sin(theta) cos(theta)];\n U = U*R;\n otherwise\n error('Unsupported dimension');\n end\n end\n\n all = [interior(:);b(:)]';\n\n % cholesky factorization\n %cholL = chol(-L(interior,interior),'lower');\n % Why lu and not cholesky?\n %[luL,luU,luP,luQ,luR] = lu(-L(interior,interior));\n\n %R = repmat(eye(dim,dim),[1 1 n]);\n\n if ~isfield(data,'ae') || isempty(data.ae)\n data.ae = avgedge(V,F);\n end\n\n % build covariance scatter matrix used to build covariance matrices we'll\n % later fit rotations to\n if ~isfield(data,'CSM') || isempty(data.CSM)\n %assert(size(ref_V,2) == dim);\n data.CSM = ...\n covariance_scatter_matrix(ref_V,ref_F,'Energy',energy);\n if ~isempty(ref_map)\n data.CSM = data.CSM * repdiag(ref_map',dim);\n end\n \n % if there are groups then condense scatter matrix to only build\n % covariance matrices for each group\n if ~isempty(G)\n G_sum = group_sum_matrix(data.G,k);\n %CSM = [G_sum sparse(k,n); sparse(k,n) G_sum] * CSM;\n data.CSM = repdiag(G_sum,dim) * data.CSM;\n end\n end\n\n % precompute rhs premultiplier\n if ~isfield(data,'K') || isempty(data.K)\n [~,data.K] = arap_rhs(ref_V,ref_F,[],'Energy',energy,'Weight',weight);\n if ~isempty(ref_map)\n data.K = repdiag(ref_map,dim) * data.K;\n end\n end\n\n % initialize rotations with identies (not necessary)\n R = repmat(eye(dim,dim),[1 1 size(data.CSM,1)/dim]);\n\n iteration = 1;\n U_prev = V;\n data.energy = inf;\n while true\n\n if iteration > max_iterations\n if debug\n fprintf('arap: Iter (%d) > max_iterations (%d)\\n',iteration,max_iterations);\n end\n break;\n end\n\n if iteration > 1\n change = max(abs(U(:)-U_prev(:)));\n if debug\n fprintf('arap: iter: %d, change: %g, energy: %g\\n', ...\n iteration,change/data.ae,data.energy);\n end\n if change/data.ae energy_prev\n if debug\n fprintf('arap: energy (%g) increasing (over %g) (iter %d)\\n', ...\n data.energy,energy_prev,iteration);\n end\n break;\n end\n\n %U(interior,:) = -L(interior,interior) \\ (B(interior,:) + L(interior,b)*bc);\n %U(interior,:) = -L(interior,all)*L(all,interior) \\ (L(interior,all)*B(all,:) + L(interior,all)*L(all,b)*bc);\n %U(interior,:) = luQ*(luU\\(luL\\(luP*(luR\\(B(interior,:)+L(interior,b)*bc)))));\n %U(interior,:)=cholL\\((B(interior,:)+L(interior,b)*bc)'/cholL)';\n iteration = iteration + 1;\n end\n U = U(:,1:dim);\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/arap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3919512802392236}}
{"text": "function [F,V,faceBoundaryMarker]=quadBox(boxDim,boxEl)\n\n\n%%\nF=[]; V=[]; faceBoundaryMarker=[];\n\n[Xtb,Ytb]=meshgrid(0:boxEl(1),0:boxEl(2));\n\n\n[Ylr,Zlr]=meshgrid(0:boxEl(2),0:boxEl(3));\n[f,v]=surf2patch(0*ones(size(Ylr)),Ylr,Zlr); %Left\nf=fliplr(f);\nF=[F;f+size(V,1)]; V=[V;v;]; faceBoundaryMarker=[faceBoundaryMarker; 1*ones(size(f,1),1)];\n\n[f,v]=surf2patch(boxEl(1)*ones(size(Ylr)),Ylr,Zlr); %Right\nF=[F;f+size(V,1)]; V=[V;v;]; faceBoundaryMarker=[faceBoundaryMarker; 2*ones(size(f,1),1)];\n\n[Yfb,Zfb]=meshgrid(0:boxEl(1),0:boxEl(3));\n[f,v]=surf2patch(Yfb,0*ones(size(Yfb)),Zfb); %Front\nF=[F;f+size(V,1)]; V=[V;v;]; faceBoundaryMarker=[faceBoundaryMarker; 3*ones(size(f,1),1)];\n\n[f,v]=surf2patch(Yfb,boxEl(2)*ones(size(Yfb)),Zfb); %Back\nf=fliplr(f);\nF=[F;f+size(V,1)]; V=[V;v;]; faceBoundaryMarker=[faceBoundaryMarker; 4*ones(size(f,1),1)];\n\n[f,v]=surf2patch(Xtb,Ytb,0*ones(size(Xtb))); %Bottom\nf=fliplr(f);\nF=[F;f+size(V,1)]; V=[V;v;]; faceBoundaryMarker=[faceBoundaryMarker; 5*ones(size(f,1),1)];\n\n[f,v]=surf2patch(Xtb,Ytb,boxEl(3)*ones(size(Xtb))); %Top\nF=[F;f+size(V,1)]; V=[V;v;]; faceBoundaryMarker=[faceBoundaryMarker; 6*ones(size(f,1),1)];\n\n\n%%\n% Remove double nodes by merging\n[F,V]=mergeVertices(F,V);\n\n%%\n% Scale coordinates\nmaxV=max(V,[],1);\nV=V./maxV(ones(size(V,1),1),:);\nV=V.*boxDim(ones(size(V,1),1),:);\nV=V-boxDim(ones(size(V,1),1),:)/2;\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/quadBox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.3919418687904979}}
{"text": "function Mh = hmxSingle(Mh)\n%+========================================================================+\n%| |\n%| OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA |\n%| openHmx is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : hmxSingle.m |\n%| # | VERSION : 0.40 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 14.03.2018 |\n%| ( === ) | SYNOPSIS : Convert H-Matrix to single precision |\n%| `---' | |\n%+========================================================================+\n\n% Position\nMh.pos = {single(Mh.pos{1}),single(Mh.pos{2})};\n\n%%% H-Matrix (recursion)\nif (Mh.typ == 0)\n for i = 1:4\n Mh.chd{i} = hmxSingle(Mh.chd{i});\n Mh.row{i} = single(Mh.row{i});\n Mh.col{i} = single(Mh.col{i});\n end\n Mh = hmxFusion(Mh);\n \n%%% Compressed leaf\nelseif (Mh.typ == 1)\n Mh.dat{1} = single(Mh.dat{1});\n Mh.dat{2} = single(Mh.dat{2});\n \n%%% Full leaf\nelseif (Mh.typ == 2)\n Mh.dat = single(Mh.dat);\n \n%%% Unknown type\nelse\n error('hmxSingle.m : unavailable case')\nend\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openHmx/hmxSingle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.39188477658757054}}
{"text": "% +IOSR\n% \n% Contents file for +IOSR and its subfolders.\n% \n% +IOSR\n% iosr.install - Set search paths, and download and install dependencies\n% \n% +IOSR/+ACOUSTICS\n% iosr.acoustics.irStats - Calculate RT, DRR, Cte, and EDT for impulse response file\n% iosr.acoustics.rtEst - Estimate reverberation time based on room size and absorption\n% \n% +IOSR/+AUDITORY\n% iosr.auditory.azimuth2itd - Convert azimuth in degrees to ITD\n% iosr.auditory.binSearch - Conduct a binary search\n% iosr.auditory.calcIld - Calculate normalised interaural level difference\n% iosr.auditory.chXcorr - Calculate cross-correlograms with a wide range of options\n% iosr.auditory.chXcorr2 - Calculate cross-correlograms with a range of options\n% chXcorr2_c.c\n% chXcorr_c.c\n% iosr.auditory.createWindow - Create a Hann or exp. window with specified onsets/offsets\n% iosr.auditory.dupWeight - Calculate duplex weighting coefficients for ITD and ILD\n% iosr.auditory.erbRate2hz - Convert ERB rate to Hz\n% iosr.auditory.freqMulti - Calculate frequency coefficient for ITD-azimuth warping\n% iosr.auditory.gammatoneFast - Produce an array of responses from gammatone filters via FFT\n% iosr.auditory.hz2erbRate - Convert Hz to ERB rate\n% iosr.auditory.iso226 - ISO 226:2003 Normal equal-loudness-level contours\n% iosr.auditory.itd2azimuth - Convert ITD to azimuth\n% iosr.auditory.lindemannInh - Signal pre-processing for Lindemann's cross-correlation\n% iosr.auditory.loudWeight - Calculate loudness weighting coefficients\n% iosr.auditory.makeErbCFs - Make a series of center frequencies equally spaced in ERB-rate\n% iosr.auditory.meddisHairCell - Calculate Ray Meddis' hair cell model for a number of channels\n% iosr.auditory.perceptualCentroid - Perceptual spectral centroid\n% iosr.auditory.perceptualCentroid2 - Alternative perceptual spectral centroid\n% iosr.auditory.xcorrLindemann - Cross-correlation based on Lindemann's precedence model\n% xcorrLindemann_c.c\n% \n% +IOSR/+BSS\n% iosr.bss.applyIdealMasks - Calculate and apply ideal masks via STFT\n% iosr.bss.applyMask - Apply a time-frequency mask to an STFT\n% iosr.bss.calcImr - Calculates the Ideal Mask Ratio (IMR)\n% iosr.bss.calcSnr - Calculate the separation SNR\n% iosr.bss.cfs2fcs - Calculate gammatone crossover frequencies\n% iosr.bss.example - Determine STFT parameters\n% iosr.bss.generateMixtures - Generate arrays of mixtures from targets and interferers\n% iosr.bss.getFullMask - Convert frame rate mask to a sample-by-sample mask\n% iosr.bss.idealMasks - Calculate ideal time-frequency masks from STFTs\n% iosr.bss.mixture - Class of sound source separation mixture\n% iosr.bss.resynthesise - Resynthesise a target from a time-frequency mask\n% iosr.bss.source - Class of sound source separation source\n% \n% +IOSR/+DSP\n% iosr.dsp.audio - Abstract superclass providing audio-related properties and methods\n% iosr.dsp.autocorr - Perform autocorrelation via FFT\n% iosr.dsp.convFft - Convolve two vectors using FFT multiplication\n% iosr.dsp.istft - Calculate the Inverse Short-Time Fourier Transform\n% iosr.dsp.lapwin - Laplace window\n% iosr.dsp.localpeaks - Find local peaks and troughs in a vector\n% iosr.dsp.ltas - Calculate the long-term average spectrum of a signal\n% iosr.dsp.matchEQ - Match the LTAS of a signal to an arbitrary spectral magnitude\n% iosr.dsp.rcoswin - Raised cosine window\n% iosr.dsp.rms - Calculate the rms of a vector or matrix\n% iosr.dsp.sincFilter - Apply a near-ideal low-pass or band-pass brickwall filter\n% iosr.dsp.smoothSpectrum - Apply 1/N-octave smoothing to a frequency spectrum\n% iosr.dsp.stft - Calculate the short-time Fourier transform of a signal\n% iosr.dsp.vsmooth - Smooth a vector using mathematical functions\n% \n% +IOSR/+FIGURES\n% iosr.figures.chMap - Create a monochrome-compatible colour map\n% iosr.figures.cmrMap - Create a monochrome-compatible colour map\n% iosr.figures.multiwaveplot - Stacked line plots from a matrix or vectors\n% iosr.figures.subfigrid - Create axis positions for subfigures\n% \n% +IOSR/+GENERAL\n% iosr.general.cell2csv - Output a cell array to a CSV file\n% iosr.general.checkMexCompiled - Check if mex file is compiled for system\n% iosr.general.getContents - Get the contents of a specified directory\n% iosr.general.updateContents - Create a Contents.m file including subdirectories\n% iosr.general.urn - Generate random number sequence without duplicates\n% \n% +IOSR/+STATISTICS\n% iosr.statistics.boxPlot - Draw a box plot\n% iosr.statistics.functionalBoxPlot - Draw a functional boxplot\n% iosr.statistics.functionalPlot - Abstract superclass for functional plots\n% iosr.statistics.functionalSpreadPlot - Draw a functional plot showing data spread\n% iosr.statistics.getRmse - Calculate the root-mean-square error between input data\n% iosr.statistics.laprnd - Pseudorandom numbers drawn from the Laplace distribution\n% iosr.statistics.qqPlot - Quantile-quantile plot with patch option\n% iosr.statistics.quantile - Quantiles of a sample via various methods\n% iosr.statistics.statsPlot - An abstract superclass for classes that plot statistics\n% iosr.statistics.tab2box - Prepare tabular data for boxPlot function\n% iosr.statistics.trirnd - Pseudorandom numbers drawn from the triangular distribution\n% \n% +IOSR/+SVN\n% iosr.svn.buildSvnProfile - Read data from files tagged with SVN keywords\n% iosr.svn.headRev - Retrieve the head revision for specified files\n% iosr.svn.readSvnKeyword - Read data from a file tagged with an SVN keyword\n% \n% This file was generated by updateContents.m on 31 May 2017 at 17:06:32.\n", "meta": {"author": "IoSR-Surrey", "repo": "MatlabToolbox", "sha": "4bff1bb2da7c95de0ce2713e7c710a0afa70c705", "save_path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox", "path": "github-repos/MATLAB/IoSR-Surrey-MatlabToolbox/MatlabToolbox-4bff1bb2da7c95de0ce2713e7c710a0afa70c705/+iosr/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3912514230200212}}
{"text": "function [fMshift, fProbability, fAICc, mProblikelihood, bH, bH2] = calc_loglikelihood_dM2(mCat1, mCat2)\n% function [fMshift, fProbability, fAICc, mProblikelihood, bH] = calc_loglikelihood_dM2(mCat1, mCat2);\n% ----------------------------------------------------------------------------------------------------\n% Calculate log-likelihood estimation of magnitude shift dM between to periods; use power-law\n% approximation to first time period for comparison\n%\n% Incoming variable\n% mCat1 : EQ catalog period 1\n% mCat2 : EQ catalog period 2 (Observed catalog)\n%\n% Outgoing variable\n% fProbability : log-likelihood probabilty\n% fMshift : Magnitude shift with the lowest max. lieklihood score\n% fAICc : Corrected Akaike Information Criterion\n% mProblikelihood : Solution matrix shift and likelihood score\n% bH : Result of KSTEST2 hypothesis test at 0.05 significance level\n% bH2 : Result of KSTEST2 hypothesis test at 0.05 significance level on EMR-model\n%\n% Author: J. Woessner, woessner@seismo.ifg,.ethz.ch\n% last update: 02.02.04\n\n% Initialize\nmProblikelihood = [];\nvfProbability = [];\nvMshift = [];\nvMc = [];\nfBinning = 0.1;\n\n% Determine exact time period\nfPeriod1 = max(mCat1(:,3)) - min(mCat1(:,3));\nfPeriod2 = max(mCat2(:,3)) - min(mCat2(:,3));\n\nmCat1Mod = mCat1;\n\nfor fMshift = -0.4:0.1:0.4\n % Apply shift\n mCat1Mod(:,6) = mCat1(:,6)+fMshift;\n % Initialize values\n fMinMag = floor(min([min(mCat1Mod(:,6)) min(mCat2(:,6))]));\n fMaxMag = ceil(max([max(mCat1Mod(:,6)) max(mCat2(:,6))]));\n %% Calculate model for best fitting Mc\n try\n [mResult, fMls, fMc, fMu, fSigma, mDataPred, vPredBest, fBvalue] = calc_McCdfnormal(mCat1Mod, fBinning);\n vPredFMD = mDataPred(:,1)'./fPeriod1;\n vMags = mDataPred(:,2)';\n [vModFMD,vBin1] = hist(mCat1Mod(:,6),fMinMag:0.1:fMaxMag);\n [vObsFMD,vBin2] = hist(mCat2(:,6),min(vMags):0.1:max(vMags));\n% figure_w_normalized_uicontrolunits(40)\n% plot(vBin2, vObsFMD./fPeriod2,'bo')\n% hold on\n% plot(vBin1, vModFMD./fPeriod1,'go')\n% plot(vMags,vPredFMD,'r*')\n% hold off\n% drawnow\n % Time normalization and round due to Poisson distribution calculation in calc_log10poisspdf\n vObsFMD = ceil(vObsFMD./fPeriod2);\n % Calculate the likelihoods for both models\n vProb_ = calc_log10poisspdf2(vObsFMD',vPredFMD');\n % Sum the probabilities\n fProbability = (-1) * sum(vProb_);\n vfProbability = [vfProbability; fProbability];\n vMshift = [vMshift; fMshift];\n vMc = [vMc; fMc];\n catch\n vfProbability = [vfProbability; NaN];\n vMshift = [vMshift; NaN];\n vMc = [vMc; NaN];\n end; % of try-catch\nend\n\ntry\n %%% Find the minimum loglikelihood score: if the minimum score is obtained several times, calculate MEAN\n %%% of the magnitude shift\n vdMloglikeli = [vfProbability vMshift];\n vSel = (vdMloglikeli == nan(vdMloglikeli(:,1)));\n vdMloglikeli = vdMloglikeli(vSel,:);\n if length(vdMloglikeli(:,1)) > 1\n fProbability = min(vdMloglikeli(:,1));\n fMshift = roundn(mean(vdMloglikeli(:,2)),-1);\n else\n fProbability = vdMloglikeli(:,1);\n fMshift = vdMloglikeli(:,2);\n end\n % KS-Test\n [bH,fPval,fKsstat] = kstest2(roundn(mCat2(:,6),-1),roundn(mCat1(:,6)+fMshift,-1),0.05,0);\n % Solution matrix\n mProblikelihood = [vMc vMshift vfProbability];\n nDegFree = 1; % Magnitude shift is the degree of freedom\n n_samples = length(mCat1(:,6))+length(mCat2(:,6));\n %% Corrected Akaike Information Criterion (AICc)\n fAICc = -2*(-fProbability)+2*nDegFree+2*nDegFree*(nDegFree+1)/(n_samples-nDegFree-1);\n\n % KSTest on Model\n vMag1 = [];\n mCat1Mod(:,6) = mCat1(:,6)+fMshift;\n [mResult, fMls, fMc, fMu, fSigma, mDataPred, vPredBest, fBvalue] = calc_McCdfnormal(mCat1Mod, fBinning);\n mPredFMD = mDataPred;\n %mPredFMD(:,1) = ceil(mDataPred(:,1)./fPeriod1);\n vSel = (mPredFMD(:,2) ~= 0); % Remove bins with zero frequency of zero events\n mData2 = mPredFMD(vSel,:);\n for nCnt=1:length(mData2(:,1))\n fM = repmat(mData2(nCnt,2),mData2(nCnt,1),1);\n vMag1 = [vMag1; fM];\n end\n [bH2,fPval2,fKsstat2] = kstest2(roundn(mCat2(:,6),-1),roundn(vMag1,-1),0.05,0);\n\ncatch\n mProblikelihood = [NaN NaN NaN];\n fAICc = NaN;\n fMshift = NaN;\n fProbability = NaN;\n bH = NaN;\n bH2 = NaN;\nend; % of try-catch\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/calc_loglikelihood_dM2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3911882903881094}}
{"text": "function mpc = case9target\n%CASE9TARGET Target injection power flow data for 9 bus, 3 generator case.\n% Please see CASEFORMAT for details on the case file format.\n%\n% Modified version of case9.m used as target for example CPF.\n\n% MATPOWER\n\n%% MATPOWER Case Format : Version 2\nmpc.version = '2';\n\n%%----- Power Flow Data -----%%\n%% system MVA base\nmpc.baseMVA = 100;\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [\n\t1\t3\t0\t0\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t2\t2\t0\t0\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t3\t2\t0\t0\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t4\t1\t0\t0\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t5\t1\t305.4\t123.15\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t6\t1\t0\t0\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t7\t1\t214.11\t71.09\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t8\t1\t0\t0\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n\t9\t1\t235.61\t81.44\t0\t0\t1\t1\t0\t345\t1\t1.1\t0.9;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\tPc1\tPc2\tQc1min\tQc1max\tQc2min\tQc2max\tramp_agc\tramp_10\tramp_30\tramp_q\tapf\nmpc.gen = [\n\t1\t72.3\t27.03\t300\t-300\t1.04\t100\t1\t250\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t2\t248\t0\t300\t-300\t1.025\t100\t1\t300\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t3\t124.59\t0\t300\t-300\t1.025\t100\t1\t270\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [\n\t1\t4\t0\t0.0576\t0\t250\t250\t250\t0\t0\t1\t-360\t360;\n\t4\t5\t0.017\t0.092\t0.158\t250\t250\t250\t0\t0\t1\t-360\t360;\n\t5\t6\t0.039\t0.17\t0.358\t150\t150\t150\t0\t0\t1\t-360\t360;\n\t3\t6\t0\t0.0586\t0\t300\t300\t300\t0\t0\t1\t-360\t360;\n\t6\t7\t0.0119\t0.1008\t0.209\t150\t150\t150\t0\t0\t1\t-360\t360;\n\t7\t8\t0.0085\t0.072\t0.149\t250\t250\t250\t0\t0\t1\t-360\t360;\n\t8\t2\t0\t0.0625\t0\t250\t250\t250\t0\t0\t1\t-360\t360;\n\t8\t9\t0.032\t0.161\t0.306\t250\t250\t250\t0\t0\t1\t-360\t360;\n\t9\t4\t0.01\t0.085\t0.176\t250\t250\t250\t0\t0\t1\t-360\t360;\n];\n\n%%----- OPF Data -----%%\n%% generator cost data\n%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t1500\t0\t3\t0.11\t5\t150;\n\t2\t2000\t0\t3\t0.085\t1.2\t600;\n\t2\t3000\t0\t3\t0.1225\t1\t335;\n];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/data/case9target.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3911495999748038}}
{"text": "function [g1, g2] = lfmaXlfmKernGradient(lfmKern1, lfmKern2, t1, t2, covGrad, meanVector)\n\n% LFMAXLFMKERNGRADIENT Compute a cross gradient between a LFMA and a LFM.\n% FORMAT\n% DESC computes cross gradient of parameters of a cross kernel\n% between two lfm kernels, one lfm kernel corresponds to the accel. and\n% the other corresponds to the position. It is supposed to be used together\n% with the multiple output kernel.\n% ARG lfmKern1 : the kernel structure associated with the first LFM\n% kernel (acceleration).\n% ARG lfmKern2 : the kernel structure associated with the second LFM\n% kernel (position).\n% ARG t1 : inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see lfmKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see lfmKernExtractParam.\n%\n% FORMAT\n% DESC computes cross gradient of parameters of a cross kernel\n% between two lfm kernels, one lfm kernel corresponds to the accel. and\n% the other corresponds to the position. It is supposed to be used together\n% with the multiple output kernel.\n% ARG lfmKern1 : the kernel structure associated with the first LFM\n% kernel (acceleration).\n% ARG lfmKern2 : the kernel structure associated with the second LFM\n% kernel (position).\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see lfmKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see lfmKernExtractParam.\n%\n% FORMAT\n% DESC computes cross gradient of parameters of a cross kernel\n% between two lfm kernels, one lfm kernel corresponds to the accel. and\n% the other corresponds to the position. It is supposed to be used together\n% with the multiple output kernel.\n% ARG lfmKern1 : the kernel structure associated with the first LFM\n% kernel (acceleration).\n% ARG lfmKern2 : the kernel structure associated with the second LFM\n% kernel (position).\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% ARG meanVec : precomputed factor that is used for the switching dynamical\n% latent force model.\n% RETURN g1 : gradient of the parameters of the first kernel, for\n% ordering see lfmKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for\n% ordering see lfmKernExtractParam.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, lfmvKernParamInit\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n\n% KERN\n\nsubComponent = false; % This is just a flag that indicates if this kernel is part of a bigger kernel (SDLFM)\n\nif nargin == 4\n covGrad = t2;\n t2 = t1;\nelseif nargin == 6\n subComponent = true;\n if numel(meanVector)>1\n if size(meanVector,1) == 1,\n if size(meanVector, 2)~=size(covGrad, 2)\n error('The dimensions of meanVector don''t correspond to the dimensions of covGrad')\n end\n else\n if size((meanVector'), 2)~=size(covGrad,2)\n error('The dimensions of meanVector don''t correspond to the dimensions of covGrad')\n end\n end\n else\n if numel(t1)==1 && numel(t2)>1\n % matGrad will be row vector and so should be covGrad\n dimcovGrad = length(covGrad);\n covGrad = reshape(covGrad, [1 dimcovGrad]);\n elseif numel(t1)>1 && numel(t2)==1\n % matGrad will be column vector and sp should be covGrad\n dimcovGrad = length(covGrad);\n covGrad = reshape(covGrad, [dimcovGrad 1]);\n end\n end\nend\n\nif size(t1, 2) > 1 || size(t2, 2) > 1\n error('Input can only have one column');\nend\nif lfmKern1.inverseWidth ~= lfmKern2.inverseWidth\n error('Kernels cannot be cross combined if they have different inverse widths.')\nend\n\n% Parameters of the simulation (in the order providen by kernExtractParam)\n\nm = [lfmKern1.mass lfmKern2.mass]; % Par. 1\nD = [lfmKern1.spring lfmKern2.spring]; % Par. 2\nC = [lfmKern1.damper lfmKern2.damper]; % Par. 3\nsigma2 = 2/lfmKern1.inverseWidth; % Par. 4\nsigma = sqrt(sigma2);\nS = [lfmKern1.sensitivity lfmKern2.sensitivity]; % Par. 5\n\nalpha = C./(2*m);\nomega = sqrt(D./m-alpha.^2);\n\n% Initialization of vectors and matrices\n\ng1 = zeros(1,5);\ng2 = zeros(1,5);\n\n% Precomputations\ncomputeH = cell(4,1);\ncomputeUpsilonMatrix = cell(2,1);\ncomputeUpsilonVector = cell(2,1);\ngradientUpsilonMatrix = cell(4,1);\ngradientUpsilonVector = cell(4,1);\ngamma1_p = alpha(1) + j*omega(1);\ngamma1_m = alpha(1) - j*omega(1);\ngamma2_p = alpha(2) + j*omega(2);\ngamma2_m = alpha(2) - j*omega(2);\npreExp1 = zeros(length(t1),2);\npreExp2 = zeros(length(t2),2);\npreExpg1 = zeros(length(t1),2);\npreExpgg1 = zeros(length(t1),2);\npreExpt1 = zeros(length(t1),2);\npreExpt2 = zeros(length(t2),2);\npreGamma(1) = gamma1_p + gamma2_p;\npreGamma(2) = gamma1_p + gamma2_m;\npreGamma(3) = gamma1_m + gamma2_p;\npreGamma(4) = gamma1_m + gamma2_m;\npreGamma2 = preGamma.^2;\npreConst = 1./preGamma;\npreConst2 = 1./(preGamma2);\npreFactors(1) = preConst(2) - preConst(1);\npreFactors(2) = preConst(3) - preConst(4);\npreFactors(3) = preConst(3) - preConst(1);\npreFactors(4) = preConst(2) - preConst(4);\npreFactors2(1) = -preConst2(2) + preConst2(1);\npreFactors2(2) = -preConst2(3) + preConst2(4);\npreFactors2(3) = -preConst2(3) + preConst2(1);\npreFactors2(4) = -preConst2(2) + preConst2(4);\npreExp1(:,1) = exp(-gamma1_p*t1);\npreExp1(:,2) = exp(-gamma1_m*t1);\npreExp2(:,1) = exp(-gamma2_p*t2);\npreExp2(:,2) = exp(-gamma2_m*t2);\npreExpg1(:,1) = (2*gamma1_p)*preExp1(:,1);\npreExpg1(:,2) = (2*gamma1_m)*preExp1(:,2);\npreExpgg1(:,1) = (gamma1_p^2)*preExp1(:,1);\npreExpgg1(:,2) = (gamma1_m^2)*preExp1(:,2);\npreExpt1(:,1) = t1.*preExpgg1(:,1);\npreExpt1(:,2) = t1.*preExpgg1(:,2);\npreExpt2(:,1) = t2.*exp(-gamma2_p*t2);\npreExpt2(:,2) = t2.*exp(-gamma2_m*t2);\n[computeH{1}, computeUpsilonMatrix{1}, computeUpsilonMatrixLocal{1}] = lfmComputeH3AP(gamma1_p, gamma1_m, sigma2, t1,t2,preFactors([1 2]), 0);\n[computeH{2}, computeUpsilonMatrix{2}, computeUpsilonMatrixLocal{2}] = lfmComputeH3AP(gamma2_p, gamma2_m, sigma2, t2,t1,preFactors([3 4]), 1);\n[computeH{3}, computeUpsilonVector{1}, computeUpsilonVectorLocal{1}] = lfmComputeH4AP(gamma1_p, gamma1_m, sigma2, t1, preGamma([1 2 4 3]), preExp2, 0 );\n[computeH{4}, computeUpsilonVector{2}, computeUpsilonVectorLocal{2}] = lfmComputeH4AP(gamma2_p, gamma2_m, sigma2, t2, preGamma([1 3 4 2]), preExpgg1, 1 );\npreKernel = ( computeH{1} + computeH{2}.' + computeH{3} + computeH{4}.');\n\n\n% Precompute derivatives\ngradientUpsilonMatrix{1} = lfmapGradientUpsilonMatrix(gamma1_p,sigma2,t1, t2, 0, computeUpsilonMatrixLocal{1}{1});\ngradientUpsilonMatrix{2} = lfmapGradientUpsilonMatrix(gamma1_m,sigma2,t1, t2, 0, computeUpsilonMatrixLocal{1}{2});\ngradientUpsilonMatrix{3} = lfmapGradientUpsilonMatrix(gamma2_p,sigma2,t2, t1, 1, computeUpsilonMatrixLocal{2}{1});\ngradientUpsilonMatrix{4} = lfmapGradientUpsilonMatrix(gamma2_m,sigma2,t2, t1, 1, computeUpsilonMatrixLocal{2}{2});\ngradientUpsilonVector{1} = lfmapGradientUpsilonVector(gamma1_p,sigma2,t1, computeUpsilonVectorLocal{1}{1});\ngradientUpsilonVector{2} = lfmapGradientUpsilonVector(gamma1_m,sigma2,t1, computeUpsilonVectorLocal{1}{2});\ngradientUpsilonVector{3} = lfmGradientUpsilonVector(gamma2_p,sigma2,t2);\ngradientUpsilonVector{4} = lfmGradientUpsilonVector(gamma2_m,sigma2,t2);\n\nif lfmKern1.isNormalised\n K0 = lfmKern1.sensitivity*lfmKern2.sensitivity/(8*sqrt(2)*lfmKern1.mass*lfmKern2.mass*prod(omega));\n K02 = 1/(8*sqrt(2)*prod(m)*prod(omega));\nelse\n K0 = sigma*sqrt(pi)*lfmKern1.sensitivity*lfmKern2.sensitivity/(8*lfmKern1.mass*lfmKern2.mass*prod(omega)); \n K02 = sigma*sqrt(pi)/(8*prod(m)*prod(omega));\nend\n\n% Gradient with respect to m, D and C\nfor ind_theta = 1:3 % Parameter (m, D or C)\n for ind_par = 0:1 % System (1 or 2)\n % Choosing the right gradients for m, omega, gamma1 and gamma2\n switch ind_theta\n case 1 % Gradient wrt m\n gradThetaM = [1-ind_par ind_par];\n gradThetaAlpha = -C./(2*(m.^2));\n gradThetaOmega = (C.^2-2*m.*D)./(2*(m.^2).*sqrt(4*m.*D-C.^2));\n case 2 % Gradient wrt D\n gradThetaM = zeros(1,2);\n gradThetaAlpha = zeros(1,2);\n gradThetaOmega = 1./sqrt(4*m.*D-C.^2);\n case 3 % Gradient wrt C\n gradThetaM = zeros(1,2);\n gradThetaAlpha = 1./(2*m);\n gradThetaOmega = -C./(2*m.*sqrt(4*m.*D-C.^2));\n end\n gradThetaGamma1 = gradThetaAlpha + j*gradThetaOmega;\n gradThetaGamma2 = gradThetaAlpha - j*gradThetaOmega;\n % Gradient evaluation\n gradThetaGamma11 = [gradThetaGamma1(1) gradThetaGamma2(1)];\n gradThetaGamma2 = [gradThetaGamma1(2) gradThetaGamma2(2)];\n gradThetaGamma1 = gradThetaGamma11;\n\n if ~ind_par % ind_par = k or d\n matGrad = K0 ...\n * ( lfmGradientH31( preFactors([1 2]), preFactors2([1 2]), gradThetaGamma1, ...\n gradientUpsilonMatrix{1}, gradientUpsilonMatrix{2}, computeUpsilonMatrix{1}{1}, ...\n computeUpsilonMatrix{1}{2}, 1) + ...\n lfmGradientH32( preGamma2, gradThetaGamma1, computeUpsilonMatrix{2}{1}, ...\n computeUpsilonMatrix{2}{2}, 1).' + ...\n lfmGradientH41( preGamma, preGamma2, gradThetaGamma1, preExp2, ...\n gradientUpsilonVector{1}, gradientUpsilonVector{2}, computeUpsilonVector{1}{1},...\n computeUpsilonVector{1}{2}, 1) + ...\n lfmGradientH42AP(preGamma, preGamma2, gradThetaGamma1, preExpg1, preExpgg1, preExpt1, ...\n computeUpsilonVector{2}{1}, computeUpsilonVector{2}{2}).'...\n - (gradThetaM(1+ind_par)/m(1+ind_par) ...\n + gradThetaOmega(1+ind_par)/omega(1+ind_par)) ...\n *preKernel);\n else % ind_par = r or d'\n matGrad = K0 ...\n * ( lfmGradientH31( preFactors([3 4]), preFactors2([3 4]), gradThetaGamma2, ...\n gradientUpsilonMatrix{3}, gradientUpsilonMatrix{4}, computeUpsilonMatrix{2}{1}, ...\n computeUpsilonMatrix{2}{2}, 1).' + ...\n lfmGradientH32( preGamma2([1 3 2 4]), gradThetaGamma2, computeUpsilonMatrix{1}{1}, ...\n computeUpsilonMatrix{1}{2}, 1) + ...\n lfmGradientH41( preGamma([1 3 2 4]), preGamma2([1 3 2 4]), gradThetaGamma2, preExpgg1, ...\n gradientUpsilonVector{3}, gradientUpsilonVector{4}, computeUpsilonVector{2}{1},...\n computeUpsilonVector{2}{2}, 1).' + ...\n lfmGradientH42(preGamma([1 3 2 4]), preGamma2([1 3 2 4]), gradThetaGamma2, preExp2, preExpt2, ...\n computeUpsilonVector{1}{1}, computeUpsilonVector{1}{2}, 1)...\n - (gradThetaM(1+ind_par)/m(1+ind_par) ...\n + gradThetaOmega(1+ind_par)/omega(1+ind_par)) ...\n *preKernel); \n end\n \n if subComponent\n if size(meanVector,1) ==1,\n matGrad = matGrad*meanVector;\n else\n matGrad = (meanVector*matGrad).';\n end\n end\n\n % Check the parameter to assign the derivative\n if ind_par == 0\n g1(ind_theta) = sum(sum(matGrad.*covGrad));\n else\n g2(ind_theta) = sum(sum(matGrad.*covGrad));\n end \n end\nend\n\n% Gradients with respect to sigma\nif lfmKern1.isNormalised\n matGrad = K0*(lfmGradientSigmaH3AP(gamma1_p, gamma1_m, sigma2, t1, t2, preFactors([1 2]), 0)...\n + lfmGradientSigmaH3AP(gamma2_p, gamma2_m, sigma2, t2, t1, preFactors([3 4]), 1).'...\n + lfmGradientSigmaH4AP(gamma1_p, gamma1_m, sigma2, t1, preGamma([1 2 4 3]), preExp2, 0 )...\n + lfmGradientSigmaH4AP(gamma2_p, gamma2_m, sigma2, t2, preGamma([1 3 4 2]), preExpgg1, 1 ).');\nelse\n matGrad = (prod(S)*sqrt(pi)/(8*prod(m)*prod(omega))) ...\n * (preKernel ...\n + sigma*(lfmGradientSigmaH3AP(gamma1_p, gamma1_m, sigma2, t1, t2, preFactors([1 2]), 0)...\n + lfmGradientSigmaH3AP(gamma2_p, gamma2_m, sigma2, t2, t1, preFactors([3 4]), 1).'...\n + lfmGradientSigmaH4AP(gamma1_p, gamma1_m, sigma2, t1, preGamma([1 2 4 3]), preExp2, 0 )...\n + lfmGradientSigmaH4AP(gamma2_p, gamma2_m, sigma2, t2, preGamma([1 3 4 2]), preExpgg1, 1 ).' )); \nend\n\nif subComponent\n if size(meanVector,1) ==1,\n matGrad = matGrad*meanVector;\n else\n matGrad = (meanVector*matGrad).';\n end\nend\ng1(4) = sum(sum(matGrad.*covGrad))*(-(sigma^3)/4);\ng2(4) = g1(4);\n\n% Gradients with respect to S\n\nmatGrad = K02*preKernel;\n\nif subComponent\n if size(meanVector,1) ==1,\n matGrad = matGrad*meanVector;\n else\n matGrad = (meanVector*matGrad).';\n end\nend\n\ng1(5) = sum(sum(S(2)*matGrad.*covGrad));\ng2(5) = sum(sum(S(1)*matGrad.*covGrad));\n\n\ng2(4) = 0; % Otherwise is counted twice, temporarly changed by Mauricio Alvarez\n\ng1 = real(g1);\ng2 = real(g2);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/lfmaXlfmKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3911495867054047}}
{"text": "function x_it=m_st_block(x_it,mparams)\n%m_st_block block preconditioner for Stokes equations\n% x_it = m_st_block(x_it,mparams);\n% input\n% x_it operand for preconditioning operator\n% mparams structure defining block preconditioning operator\n% output\n% x_it result of ilu preconditioning operation\n%\n% IFISS function: DJS, HCE; 9 April 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\n\nnv=size(mparams.Ast,1); np=size(mparams.Q,1);\nrv=x_it(1:nv); rp=x_it(nv+1:nv+np);\nzv=mparams.Ast\\rv; zp=mparams.Q\\rp;\nx_it = [zv;zp];\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/solvers/m_st_block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3908284946710617}}
{"text": "% start : starting time of audio signal in seconds(e.g. 0 second)\n% finish : e.g. ending time of audio signal in seconds (e.g. 30 second)\n% filename: the input file (wavfile)\n%\n%\n% segments: the signal segmentation with 20 msec accuracy based on RMS, \n% if segments(i) = 1 then there is a change, otherwize segments(i) = 0\n% The command find(segments == 1)/50 yields the signal segmentation times in sec \n%\n% classif: final classification of signal. classif(i) is the class\n% of the i^{th} (20 msec) interval of the given signal (see also Fig 2 (b))\n%\n% Fig 1 shows the propability of each class per segment\n%\n% Fig 2 (a) shows the segmentation of the audio signal\n% Fig 2 (b) shows the classification of the audio signal \n% Fig 2 (c) shows the RMS of the audio signal\n% \n% example to run: [classif, segments]=trmszc(0,60,'test3.wav')\n\nfunction [classif, segments]=trmszc(start,finish,filename)\n\nsegments = [];\nclassif = [];\n\n[Y1,FS,NBITS,OPTS]=wavread(filename,[1 5]);\nduration = finish-start;\nkanalia = size(Y1,2);\narxh = start*FS;\nm = 100;\ntimeread = 1;\n\nVt = 0*[1:50];\nVta = [];\nVtz = 0*[1:50];\nVtz1 = 0*[1:50];\n\nVtaz = [];\nVtaz1 = [];\n\nshma = [];\ntemp = [];\ny = 0;\npy = [1:1:50];\n\nscp = 0;\nsc = 0;\nVtp = [1:1:50];\ni=1;\n[PYs,FS,NBITS,OPTS]=wavread(filename,[arxh+1+(i-1)*timeread*FS arxh+i*timeread*FS]);\nsf11 = 0;\naVt = [];\n\n%READING - Computation of RMS-ZC-RMS*ZC per 20 msec\n\nfor i=1:floor(duration/timeread),\n [Ys,FS,NBITS,OPTS]=wavread(filename,[arxh+1+(i-1)*timeread*FS arxh+i*timeread*FS]);\n if kanalia==2,\n Ys = Ys(:,1)+Ys(:,2);\n end\n for j=1:timeread*50,\n y = Ys(round((j-1)*0.02*FS+1):floor(j*0.02*FS));\n rms = sqrt(sum(y.*y));\n Vtp = Vt;\n Vt = [Vt(2:50) rms];\n l = length(y);\n y1 = y(1:l-1);\n y2 = y(2:l);\n mm1 = y1.*y2;\n zc = 0.5*sum((abs(sign(mm1))-sign(mm1)));\n Vtz1 = [Vtz1(2:50) zc];\n zc = zc*rms;\n Vtz = [Vtz(2:50) zc];\n end\n \n m = mean(Vt);\n v = var(Vt);\n Vta = [Vta Vt];\n Vtaz = [Vtaz Vtz];\n Vtaz1 = [Vtaz1 Vtz1];\n\n \n if (v ~= 0 & m ~= 0)\n b(i) = v/m;\n a(i) = (m/b(i))-1;\n else\n b(i) = 1000000;\n a(i) = -1;\n end\nend\n\n\n%Computation of KVRMS\n\nl = length(Vta);\nftm(1) = mean(Vta(1:50));\nftv(1) = var(Vta(1:50));\nfor i=2:l-50,\n ftm(i) = ftm(i-1)+(Vta(i+49)-Vta(i-1))/50;\n ftv(i) = ftv(i-1) + ftm(i-1)*ftm(i-1) + ((Vta(i+49)*Vta(i+49)-Vta(i-1)*Vta(i-1))/50) - ftm(i)*ftm(i); \n \n if ftm(i)~= 0,\n kvrms(i) = ftv(i)/(ftm(i)*ftm(i));\n else\n kvrms(i) = 0;\n end\nend\n\nl = floor(duration/timeread);\nm = mean(kvrms);\nv = var(kvrms);\nb1111 = v/m;\na111 = (m/b1111)-1;\n\n\n%computation of similarity (omiot) between windows based on RMS distribution \nfor i=2:l,\n k = (a(i)+a(i-1)+2)/2;\n omiot1(i-1) = ((2/(b(i-1)+b(i)))^k)*(b(i-1)^((a(i)+1)/2))*(b(i)^((a(i-1)+1)/2))*gamma(k)/(sqrt(gamma(a(i-1)+1)*gamma(a(i)+1))); \n if omiot1(i-1) ~= omiot1(i-1),\n omiot1(i-1) = 0;\n end \nend\n\nfor i=3:l,\n k = (a(i)+a(i-2)+2)/2;\n omiot2(i-2) = ((2/(b(i-2)+b(i)))^k)*(b(i-2)^((a(i)+1)/2))*(b(i)^((a(i-2)+1)/2))*gamma(k)/(sqrt(gamma(a(i-2)+1)*gamma(a(i)+1))); \n if omiot2(i-2) ~= omiot2(i-2),\n omiot2(i-2) = 0;\n end\nend\n\nP = [];\n\n\n%Segmentation \n%Computation of propability P of change (at window i)\n\n\nfor i=2:l-1,\n P(i-1) =(1-omiot2(i-1))*(1-omiot1(i-1)+1-omiot1(i))*(1-omiot2(i-1));\nend\n\nfor i=2:l-1,\n P(i-1) =(1-omiot2(i-1));\nend\n\n\nP = [0 P 0];\n \nM = mean(P);\nV1 = mean(abs(P(1:l-3)-P(2:l-2)));\nV2 = mean(abs(P(1:l-4)-P(3:l-2)));\n\n\nV = (V1+V2)*0.25;\n\nV = 0.25*median(abs((P(1:l-4)-P(3:l-2))));\n\n\nPd(1) = P(1);\nPd(2) = P(2);\n\nfor i=3:l-2,\n m = mean(P([i-2:i-1 i+1:i+2]));\n m1 = max(P([i-2:i-1 i+1:i+2]));\n \n if (m < 0.1*M)\n m1 = 0.1*M;\n end\n d = (P(i)-m)/m1;\n \n if d < 0,\n d = 0;\n end\n Pd(i) = P(i)*d/V;\nend\nPd(l) = P(l);\nPd(l-1) = P(l-1);\n\n%window size = 1 sec \n\n%Selection of candicate windows where there is a change \n\nj = 0;\nfor i=3:l-3,\n if (Pd(i) > 5 & P(i) > P(i+1) & P(i) > P(i-1)),\n j = j+1;\n pos(j) = i;\n end\nend\n\n\nif j == 0,\n return;\nend\n\n\n%Computation of change with 20 msec accurancy \n\nk2 = 1;\nc = 25;\nfor k1=1:length(pos),\n i = 50*(pos(k1)-2); % msec\n for j=-c:50+c,\n if (ftv(i+j) ~= 0 & ftm(i+j) ~= 0),\n b1 = ftv(i+j)/ftm(i+j);\n a1 = ftm(i+j)/b1-1;\n else\n b1 = 10000;\n a1 = -1;\n end\n \n if (ftv(i+j+50) ~= 0 & ftm(i+j+50) ~= 0)\n b2 = ftv(i+j+50)/ftm(i+j+50);\n a2 = ftm(i+j+50)/b2-1;\n else\n b2 = 10000;\n a2 = -1;\n end\n k = (a2+a1+2)/2;\n Om(j+c+1) = ((2/(b1+b2))^k)*(b1^((a2+1)/2))*(b2^((a1+1)/2))*gamma(k)/(sqrt(gamma(a1+1)*gamma(a2+1))); \n if Om(j+c+1)~= Om(j+c+1),\n Om(j+c+1) = 0;\n end\n end\n [x posms(k1)] = min(Om);\n h = 1-Om;\n if mean(h(max(posms(k1)-25,1):min(2*c+51,posms(k1)+25))) > 0.1,\n msec(k2) = posms(k1)-1-c;\n mpos(k2) = pos(k1);\n k2 = k2+1;\n end\nend\n\n\n\nposms = [];\nposms = msec;\npos = [];\npos = mpos;\n\n\nfpos = start+pos-1+0.02*posms;\n\n\n\n\npfpos = floor(50*pos+posms-50);\n\nbvoise = 0.14339738781836;\nbmusic = 0.04399754659151;\namusic = 1.66349817725076;\navoise = 2.32677887950291;\n\n\npfpos = [1 pfpos length(kvrms)];\nl = length(pfpos)-1;\nV = [];\nPzero = [];\nFsp1 = [];\n\n%Classification for each segment \n\n\nfor i=1:l,\n \n d = 0;\n \n x1 = mean(kvrms([pfpos(i):pfpos(i+1)]));\n x = x1;\n y = Vtaz([pfpos(i)+d:pfpos(i+1)-d]);\n y = y/(2*max(Vta(pfpos(i)+d:pfpos(i+1)-d)) - min(Vta(pfpos(i)+d:pfpos(i+1)-d))-median(Vta(pfpos(i)+d:pfpos(i+1)-d)));\n \n thor(i) = 50*mean(exp(-y));\n \n Pmusic(i) = (x^amusic)*exp(-x/bmusic)/(gamma(amusic+1)*bmusic^(amusic+1));\n Pvoise(i) = 0.5*(x^avoise)*exp(-x/bvoise)/(gamma(avoise+1)*bvoise^(avoise+1));\n sm = 0.7*median(ftm(pfpos(i):pfpos(i+1)))+0.3*mean(ftm(pfpos(i):pfpos(i+1)));\n Pspace(i) = 6*exp((-sm*sm)/(2*0.6*0.6));\n \n zpos(i) = sum(exp(-10*Vtaz1([pfpos(i)+d:pfpos(i+1)-d])))/length(Vtaz1([pfpos(i)+d:pfpos(i+1)-d]));\n \n if zpos(i) > 0.08 | x > 3\n Pvoise(i) = 10;\n else\n Pmusic(i) = (x^amusic)*exp(-x/bmusic)/(gamma(amusic+1)*bmusic^(amusic+1));\n Pvoise(i) = 0.5*(x^avoise)*exp(-x/bvoise)/(gamma(avoise+1)*bvoise^(avoise+1));\n end\n \n V(i,:) = [Pmusic(i) Pvoise(i)];\n [Pmax(i) type(i)] = max(V(i,:));\n \n \n thor2(i) = 50*mean(exp(-4*y));\n Pmusicg(i) = 0;\n \n if thor2(i) > 3.5,\n Pvoiseg(i) = 10;\n else\n Pmusicg(i) = (x^amusic)*exp(-x/bmusic)/(gamma(amusic+1)*bmusic^(amusic+1));\n Pvoiseg(i) = 0.5*(x^avoise)*exp(-x/bvoise)/(gamma(avoise+1)*bvoise^(avoise+1));\n end\n \n Vg(i,:) = [Pmusicg(i) Pvoiseg(i)];\n [Pmaxg(i) typeg(i)] = max(Vg(i,:));\n \n Vk = (sign(Vtaz1([pfpos(i):pfpos(i+1)])));\n tempV = [];\n tempV = Vta([pfpos(i):pfpos(i+1)]);\n rr = max(tempV)+0.001;\n tempV1 = tempV/rr;\n Vk0 = Vk;\n \n for j = 1:length(Vk)\n if (tempV1(j) < 0.1 & tempV(j) < 1.5) | tempV(j) < 1\n Vk(j) = 0;\n end\n end\n Vk1 = Vk;\n \n for j = 1:length(Vk)\n if (tempV1(j) < 0.4 | tempV(j) < 2 | tempV(j) < mean(tempV(j))) \n Vk1(j) = 0;\n end\n end\n Zca = [];\n Zca = Vk1.*(Vtaz1([pfpos(i):pfpos(i+1)]));\n \n \n Pol = (ones(1,length(Vk)) - sign(Vk)).*Vk0; \n\n \n VZC = Pol.*Vtaz1([pfpos(i):pfpos(i+1)]);\n \n dVk = abs(Vk(2:length(Vk))-Vk(1:length(Vk)-1));\n \n \n \n Freq(i,1) = 50*sum(dVk)/(2*length(Vk)); %FSP%\n Freq(i,2) = length(Vk)/50;%duration in sec of the segment\n Freq(i,3) = sum(Freq(:,2)); \n Freq(i,4) = zpos(i);\n Freq(i,5) = thor2(i);\n Freq(i,6) = max(Zca);\n\n \n \n Pmusicg(i) = 0;\n Pvoiseg(i) = 0;\n if Freq(i,1) < 0.59 & Freq(i,2) > 2.5,\n Pmusicg(i) = 10;\n else\n Pmusicg(i) = (x^amusic)*exp(-x/bmusic)/(gamma(amusic+1)*bmusic^(amusic+1));\n Pvoiseg(i) = 0.5*(x^avoise)*exp(-x/bvoise)/(gamma(avoise+1)*bvoise^(avoise+1));\n if x > 3,\n Pvoiseg(i) = Pvoiseg(i)+0.1; \n \n end\n \n if x > 300 ,\n Pmusicg(i) = 9;\n end\n\n if thor2 > 3.5\n Pvoiseg(i) = 11;\n end\n if max(Zca) > 280,\n Pmusicg(i) = 11;\n max(Zca)\n \n end\n if Freq(i,1) > 4.62 & Freq(i,2) > 2.5 & (thor2(i) > 0.1 | zpos(i) > 0.05),\n Pvoiseg(i) = 12;\n end\n\t\t\n if zpos(i) > 0.15 \n Pvoiseg(i) = 13;\n end\n end\n Vg(i,:) = [Pmusicg(i) Pvoiseg(i)];\n [Pmaxg(i) typeg(i)] = max(Vg(i,:));\n\n\tFsp1 = [Fsp1 Vk]; \n \n \n if (Pspace(i) > 4 & thor2(i) < 1) | (Pspace(i) > 4.5),\n type(i) = 3; %silence\n typeg(i) = 3;\n end\n \n \n if (pfpos(i+1) - pfpos(i))/50 < 0.5 & i >= 1, % short segments\n type(i) = type(i-1);\n end\nend\n\n\n\n g = [];\n g1 = [];\n tt = [];\n pt = [];\n pm = [];\n ps = [];\n pv = [];\n pmf = [];\n \n \nfor i=1:l,\n tt = [tt type(i)*ones(1,pfpos(i+1)-pfpos(i))];\n pt = [pt Pmax(i)*ones(1,pfpos(i+1)-pfpos(i))];\n pm = [pm Pmusic(i)*ones(1,pfpos(i+1)-pfpos(i))];\n pv = [pv Pvoise(i)*ones(1,pfpos(i+1)-pfpos(i))];\n ps = [ps Pspace(i)*ones(1,pfpos(i+1)-pfpos(i))];\nend\n\nPosV = 100*sum(exp(-10*abs(tt-2*ones(1,length(tt)))))/length(tt);\nPosM = 100*sum(exp(-10*abs(tt-ones(1,length(tt)))))/length(tt);\n\n\n\nl1 = l;\nl = length(tt);\n\n\nl = l1;\n g = [];\n g1 = [];\n tt = [];\n pt = [];\n pm = [];\n ps = [];\n pv = [];\n pmf = [];\n\nfor i=1:l,\n tt = [tt typeg(i)*ones(1,pfpos(i+1)-pfpos(i))];\n pt = [pt Pmaxg(i)*ones(1,pfpos(i+1)-pfpos(i))];\n pm = [pm Pmusicg(i)*ones(1,pfpos(i+1)-pfpos(i))];\n pv = [pv Pvoiseg(i)*ones(1,pfpos(i+1)-pfpos(i))];\n ps = [ps Pspace(i)*ones(1,pfpos(i+1)-pfpos(i))];\nend\nl = length(tt);\n\n\n\nPosVg = 100*sum(exp(-10*abs(tt-2*ones(1,length(tt)))))/length(tt);\nPosMg = 100*sum(exp(-10*abs(tt-ones(1,length(tt)))))/length(tt);\n\n\nfigure(1);\nsubplot(5,1,1);\nplot([1:l]*(finish-start-1)/l+start,tt);\ntitle('classification type (1 : Music, 2: Voise, 3: Silence)');\nsubplot(5,1,2);\nplot([1:l]*(finish-start-1)/l+start,pt);\ntitle('~probability posibility of selected type');\nsubplot(5,1,3);\nplot([1:l]*(finish-start-1)/l+start,pm);\ntitle('~probability MUsic');\nsubplot(5,1,4);\nplot([1:l]*(finish-start-1)/l+start,pv);\ntitle('~probability Voise');\nsubplot(5,1,5);\nplot([1:l]*(finish-start-1)/l+start,ps);\ntitle('~probability silence');\n\n\n\nfor k = 1:length(Vta),\n if Vta(k) < 2 | Vta(k) < 0.1*max(Vta),\n Vtaz1(k) = 0;\n end\nend\nm = 100;\ntemp = [];\nh1 = [];\ntemp = Vtaz1;\nh1 = hist(temp,m);\nh1(1) = 0;\nh1 = h1/sum(h1);\na1 = [min(temp):(max(temp)-min(temp))/m:max(temp)-(max(temp)-min(temp))/m];\n\n\nsegbar = [];\nj = 1;\ni = 1;\nwhile i <= l,\n if j <= length(fpos) & round(50*fpos(j)) == i,\n segbar(i) = 1;\n j = j+1;\n else\n segbar(i) = 0;\n end\n i = i+1;\nend\n \nsegments = segbar;\n\nfigure(2);\nsubplot(3,1,1);\nstem([1:l]*(finish-start-1)/l+start,segbar);\naxis([0 duration 0 1]);\ntitle('Segmentation');\nxlabel('sec');\nsubplot(3,1,2);\nplot([1:l]*(finish-start-1)/l+start,tt);\naxis([0.5 duration 0 3.5]);\ntitle('classification type (1 : Music, 2: Voise, 3: Silence)');\nxlabel('sec');\nsubplot(3,1,3);\nplot(start+([1:length(Vta)]*duration/length(Vta)),Vta);\naxis([0 duration 0 (floor(max(Vta))+1)]);\ntitle('RMS');\nxlabel('sec');\n\n\nclassif = tt;\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42092-a-speechmusic-discriminator-based-on-rms-and-zero-crossings/trmszc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.39054806896717903}}
{"text": "function [mCat]=sr_makeSRC4(mCat,fTw,T)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This function removes events and creates a quiescence according to the\n% chosen input variables. The lat/lon position of the quiescence is\n% determined randomly.\n%\n% Input Variables\n% mCat Earthquake catalog in zmap-format\n% fTw Duration of PSQ\n% T Starting time of PSQ\n% fR Degree of rate change (0.75 = 75% reduction)\n%\n% Output Variables\n% mCat Catalog with PSQ%\n%\n% van Stiphout Thomas ; vanstiphout@sed.ethz.ch\n% Created: 14.08.2007\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndisp('zmap/src/thomas/seismicrates/sr_makeSRC4.m')\n\n% rate decrease for grid node\nfR=0.75;\nfLonPSQ=-116.4;\nfLatPSQ=34.3;\nnN=300;\nfLon0=fLonPSQ;\nfLat0=fLatPSQ;\n\n% get N nearest events for certain grid point\n% [caNodeIndices, vResolution_] = ex_CreateIndexCatalog(mCat, [fLon0 fLat0], 1, 0, nN, 99, 0.1, 0.1);\n% % transform cell array to matrix\n% vSel=cell2mat(caNodeIndices);\n\n% get events within certain radius of a grid point\n[caNodeIndices, vResolution] = ex_CreateIndexCatalog(mCat, [fLon0 fLat0], 1, 1, ...\n 100, 10, 0.1, 0.1);\n% transform cell array to matrix\ncaNodeIndices_=cell2mat(caNodeIndices);\nvSel=caNodeIndices_;\n% transform cell array to matrix\nvResolution_=cell2mat(vResolution);\n\n% control plots\n% figure;plot(mCat(:,1),mCat(:,2),'.k');\n% hold on;plot(mCat(vSel,1),mCat(vSel,2),'dr');\n\n\n% select from N events the one in the quiescence time period\nvSel3=find((mCat(vSel,3)>T-fTw) & (mCat(vSel,3) 4\n j1 = ceil(options.Ncomp/2); j2 = 2;\n else\n j1 = options.Ncomp; j2 = 1;\n end\n for j = 1:options.Ncomp\n subplot(j1,j2,j)\n plot(sp_profiles(:,j),'LineWidth',2.5)\n end\nend\n\n% group level\nsp_fit_group = struct();\nsp_fit_group.state = struct();\n\n% NNMF / PCA\npsd = zeros(ndim*K,options.Ncomp);\ncoh = zeros(ndim2*K,options.Ncomp);\nif strcmpi(options.Method,'NNMF')\n psd(keep_psd,:) = (Xpsd(:,keep_psd)' * sp_profiles); % ndim by components\n coh(keep_coh,:) = (Xcoh(:,keep_coh)' * sp_profiles);\n% opt = statset('maxiter',0);\n% [~,b] = nnmf(Xpsd,options.Ncomp,'algorithm','als',...\n% 'w0',sp_profiles,'Options',opt);\n% psd = b'; % regions by components\n% [~,b] = nnmf(Xcoh,options.Ncomp,'algorithm','als',...\n% 'w0',sp_profiles,'Options',opt);\n% coh = b'; % pairs of regions by components\nelse\n Xpsd(:,keep_psd) = Xpsd(:,keep_psd) - repmat(mean(Xpsd(:,keep_psd)),Nf,1);\n Xcoh(:,keep_coh) = Xcoh(:,keep_coh) - repmat(mean(Xcoh(:,keep_coh)),Nf,1);\n psd(keep_psd,:) = (Xpsd(:,keep_psd)' * sp_profiles); % ndim by components\n coh(keep_coh,:) = (Xcoh(:,keep_coh)' * sp_profiles);\nend\nif any(isnan(psd(:))) || any(isnan(coh(:))) \n warning('There are NaNs in the estimations for those states that were not used') \nend\nfor k = 1:K\n sp_fit_group.state(k).psd = zeros(options.Ncomp,ndim,ndim);\n sp_fit_group.state(k).coh = ones(options.Ncomp,ndim,ndim);\n ind = (1:ndim) + (k-1)*ndim;\n for i = 1:options.Ncomp\n sp_fit_group.state(k).psd(i,:,:) = diag(psd(ind,i));\n end\n ind = (1:ndim2) + (k-1)*ndim2;\n for i = 1:options.Ncomp\n graphmat = zeros(ndim);\n graphmat(ind_offdiag) = coh(ind,i);\n graphmat=(graphmat+graphmat') + eye(ndim);\n sp_fit_group.state(k).coh(i,:,:) = graphmat;\n end\nend\n\n% Subject level\nif N > 1 && nargout == 3\n for n = 1:N\n sp_fit{n} = struct();\n sp_fit{n}.state = struct();\n % prepare matrix\n Xpsd = zeros(Nf,ndim*K);\n keep_psd = true(1,ndim*K);\n for k = 1:K\n ind = (1:ndim) + (k-1)*ndim;\n Xpsd(:,ind)= squeeze(abs(psd_comps(n,k,:,:)));\n if any(isnan(var(Xpsd(:,ind)))) || any(isinf(var(Xpsd(:,ind))))\n keep_psd(ind) = false;\n warning(['Session ' num2str(n) ' did not use state ' num2str(k) '; PSD set to NaN'])\n end\n end\n Xcoh = zeros(Nf,K*ndim2);\n keep_coh = true(1,K*ndim2);\n for k = 1:K\n ind = (1:ndim2) + (k-1)*ndim2;\n ck = squeeze(abs(coh_comps(n,k,:,:,:)));\n Xcoh(:,ind) = ck(:,ind_offdiag);\n if any(isnan(var(Xcoh(:,ind)))) || any(isinf(var(Xcoh(:,ind))))\n keep_coh(ind) = false; \n warning(['Session ' num2str(n) ' did not use state ' num2str(k) '; Coh set to NaN'])\n end\n end\n % NNMF / PCA\n psd = zeros(ndim*K,options.Ncomp);\n coh = zeros(ndim2*K,options.Ncomp);\n if strcmpi(options.Method,'NNMF')\n opt = statset('maxiter',1);\n [~,b] = nnmf(Xpsd(:,keep_psd),options.Ncomp,'algorithm','als',...\n 'w0',sp_profiles,'Options',opt);\n psd(keep_psd,:) = b'; % regions by components\n [~,b] = nnmf(Xcoh(:,keep_coh),options.Ncomp,'algorithm','als',...\n 'w0',sp_profiles,'Options',opt);\n coh(keep_coh,:) = b';\n else\n Xpsd(:,keep_psd) = Xpsd(:,keep_psd) - repmat(mean(Xpsd(:,keep_psd)),Nf,1);\n Xcoh(:,keep_coh) = Xcoh(:,keep_coh) - repmat(mean(Xcoh(:,keep_coh)),Nf,1);\n psd(keep_psd,:) = (Xpsd(:,keep_psd)' * sp_profiles);\n coh(keep_coh,:) = (Xcoh(:,keep_coh)' * sp_profiles);\n end\n % Reshape stuff\n for k = 1:K\n sp_fit{n}.state(k).psd = zeros(options.Ncomp,ndim,ndim);\n sp_fit{n}.state(k).coh = ones(options.Ncomp,ndim,ndim);\n ind = (1:ndim) + (k-1)*ndim;\n for i = 1:options.Ncomp\n sp_fit{n}.state(k).psd(i,:,:) = diag(psd(ind,i));\n end\n ind = (1:ndim2) + (k-1)*ndim2;\n for i = 1:options.Ncomp\n graphmat = zeros(ndim);\n graphmat(ind_offdiag) = coh(ind,i);\n graphmat=(graphmat+graphmat') + eye(ndim);\n sp_fit{n}.state(k).coh(i,:,:) = graphmat;\n end\n end\n end\nelse\n sp_fit = sp_fit_group;\nend\n\nend\n\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/spectral/spectdecompose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3904126261839305}}
{"text": "function [centers, labels, info] = slkmeansex(X, n, estfunctor, clsfunctor, varargin)\n%SLKMEANSEX Performs Generalized K-means\n%\n% $ Syntax $\n% - [centers, labels] = slkmeansex(X, n, estfunctor, clsfunctor, ...)\n% - [centers, labels, info] = slkmeansex(X, n, estfunctor, clsfunctor, ...)\n%\n% $ Arguments $\n% - X: the samples to be clustered\n% - n: the number of samples\n% - estfunctor: the functor to estimate means(centers), as follows:\n% centers = estfunc(centers, X, K, weights, labels, ...)\n% when input centers is empty, it performs initial\n% estimation, otherwise, it performs updating. \n% In addition, it should ignore the samples with \n% labels being zeros or negative numbers.\n% - clsfunctor: the functor to classify samples\n% labels = clsfunc(centers, X, n, ...) \n% it should produce 1 x n row vector.\n% - centers: the clustered centers\n% - labels: the labels indicating which sample belong to which center\n% a 1 x n row vector.\n% - info: the information on iteration process\n%\n% $ Description $\n% - [centers, labels] = slkmeansex(X, n, estfunctor, clsfunctor, ...) \n% is a generalized version of K-means. It actually implements an\n% iterative process to estimate centers from clustered samples and\n% re-clustered the samples according to centers.\n% You can specify the following properties:\n% - 'K': the number of initial number of clusters\n% (default = 3)\n% - 'init_centers': the initial centers.\n% - 'maxiter': the maximum number of iterations\n% (default = 100);\n% - 'annthres': the threshold of annealing\n% when the sum of sample weights for a center\n% is below annthres * the total weight, the\n% center will be discarded. (default = 0)\n% - 'annfunc': the function to discard a set of centers\n% centers = annfunc(centers, inds_discard);\n% - 'weights': the weights of the samples (default = [])\n% - 'verbose': whether to show progress information\n% (default = true)\n%\n% $ Remarks $\n% - The X and centers can be in any form that conform to the specified\n% functors.\n%\n% - If init_centers is specified, K should be exactly the number of\n% initial centers.\n%\n% - If annthres is 0, then no centers will be discarded even some centers\n% have no support samples in the process. The estfunctor should keep\n% those centers unchanged.\n%\n% $ History $\n% - Created by Dahua Lin, on Aug 28, 2006\n% - Modified by Dahua Lin, on Aug 30, 2006\n% - utilize slevalfunctor and slsharedisp\n% - Modified by Dahua Lin, on Aug 31, 2006\n% - based on slreevallearn\n%\n\n%% parse and verify input arguments\n\nif nargin < 4\n raise_lackinput('slkmeansex', 4);\nend\n\nopts.K = 3;\nopts.init_centers = [];\nopts.maxiter = 100;\nopts.annthres = 0;\nopts.annfunc = [];\nopts.weights = [];\nopts.verbose = true;\nopts = slparseprops(opts, varargin{:});\n\nif opts.K > n\n error('sltoolbox:rterror', ...\n 'The initial K is larger than the number of samples');\nend\n\nif opts.annthres > 0\n if isempty(opts.annfunc)\n error('sltoolbox:invalidarg', ...\n 'You should specify annfunc when annthres > 0');\n end\nend\n\nw = opts.weights;\nif ~isempty(w)\n if ~isequal(w, [1 n])\n error('sltoolbox:sizmismatch', ...\n 'The weights should be a 1 x n row vector');\n end\nend\n\n\n%% Initialization\n\nslsharedisp_attach('slkmeansex', 'show', opts.verbose);\n\nslsharedisp('Intialize K-Means');\n\nif isempty(opts.init_centers)\n initcinds = randsample(n, opts.K);\n labels = zeros(1, n);\n labels(initcinds) = 1:opts.K;\n \n K = opts.K;\n centers = slevalfunctor(estfunctor, [], X, K, w, labels);\nelse\n K = opts.K;\n centers = opts.init_centers;\nend\n\nslsharedisp_incindent;\nslsharedisp('initial K = %d', K);\nslsharedisp_decindent;\n\nlabels = slevalfunctor(clsfunctor, centers, X, n);\n\n\n%% Updating\n\nslsharedisp('Update K-Means');\nslsharedisp_incindent;\n\nkm_estfunctor = {@kmeansex_est, estfunctor, opts};\nkm_evalfunctor = {@kmeansex_eval, clsfunctor};\nkm_cmpfunctor = {@kmeansex_cmp};\n\nmodels = {centers, K};\ndata = {X, n, w};\n[models, labels, info] = slreevallearn(models, labels, data, ...\n km_estfunctor, km_evalfunctor, km_cmpfunctor, ...\n 'iter', {'maxiter', opts.maxiter, 'titlebreak', false}, 'isrecorded', false);\n\ncenters = models{1};\n\nslsharedisp_decindent;\nslsharedisp_detach;\n\n%% Core functions\n\n% models = {centers, K}\n% data = {X, n, w}\n\nfunction models = kmeansex_est(models, data, labels, estfunctor, opts)\n\nX = data{1};\nw = data{3};\ncenters = models{1};\nK = models{2};\n\nif ~isempty(centers) && opts.annthres > 0 \n if isempty(w)\n w = ones(1, length(labels));\n end\n cw = sllabeledsum(w, labels, 1:K);\n wthres = opts.annthres * sum(cw) / K;\n if any(cw < wthres)\n inds_ann = find(cw < wthres);\n centers = feval(opts.annfunc, centers, inds_ann);\n K = K - length(inds_ann);\n \n models = {centers, K};\n return;\n end\nend\n\ncenters = slevalfunctor(estfunctor, centers, X, K, w, labels);\nmodels = {centers, K};\n\n\nfunction labels = kmeansex_eval(models, data, labels, clsfunctor)\n\nX = data{1};\nn = data{2};\ncenters = models{1};\n\nslignorevars(labels);\n \nlabels = slevalfunctor(clsfunctor, centers, X, n);\n\n\nfunction isconverged = kmeansex_cmp(models_prev, models, labels_prev, labels)\n \nK_prev = models_prev{2};\nK = models{2};\nn = length(labels);\n\nslsharedisp_attach('kmeansex_cmp');\n\nisconverged = false;\nif K == K_prev\n nchanged = sum(labels ~= labels_prev);\n slsharedisp('K = %d: %d / %d changed', K, nchanged, n);\n\n if nchanged == 0\n isconverged = true;\n end\nelse\n slsharedisp('K = %d ==> %d', K_prev, K);\nend\n\nslsharedisp_detach();\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n\n\n\n\n\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/cluster/slkmeansex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.38963015451860666}}
{"text": "function F = retrieveR(level, o, H, L)\n%------------------------------------------------------------------------------\n%\n% This function extracts a two-dimensional gridfunction F from H.\n% F is supposed to be uniquely determined by the integer level and\n% character o describing its type. F is defined on a rectangular\n% domain.\n% This function is a two-dimensional lifting scheme utility.\n%\n% F = 2D gridfunction of coefficients extracted from H.\n%\n% level = integer designated as the level of F.\n%\n% o = character, should be either 'a' or 'd',\n% describing the type of F:\n% 'a' relates to approximation (coefficients) and\n% 'd' relates to detail (coefficients)\n%\n% L = 2D integer array of bookkeeping, see function storeR.\n%\n% H = 1D array that functions as storage (heap). The coefficients of F\n% are extracted from H as a result of calling retrieveR.\n%\n% See also: storeR, retrieveQ\n%\n% Design and implementation by:\n% Dr. Paul M. de Zeeuw http://homepages.cwi.nl/~pauldz/\n% Last Revision: May 5, 2002.\n% (c) 1999-2002 Stichting CWI, Amsterdam.\n%------------------------------------------------------------------------------\nif isempty(L)\n if ~isempty(H)\n disp([' retrieveR - ERROR at type ' o ' with level ' num2str(level)]);\n error(' retrieveR - books empty but heap is not ')\n else \n F = [];\n end\nelse\n if isempty(H)\n disp([' retrieveR - ERROR at type ' o ' with level ' num2str(level)]);\n error(' retrieveR - books not empty but heap is ')\n else\n [nL, mL] = size(L);\n if mL ~= 6\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - books do not fit ')\n else \n jL = -1;\n j = 1;\n foundit = 0;\n while j <= nL && ~foundit\n if L(j, 1) == level\n switch o\n case 'a' , if L(j, 3) == 0 && L(j, 2) == 0\n jL = j;\n foundit = 1;\n end\n case 'd' , if L(j, 3) == 1 && L(j, 2) == 0 \n jL = j;\n foundit = 1;\n end\n otherwise\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - unknown type of coefficients ')\n end \n end\n j = j + 1;\n end\n if jL == -1\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - no such coefficients in heap')\n else\n nF = L(jL, 4);\n if nF < 1\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - unvalid 1st dimension of target')\n end\n mF = L(jL, 5);\n if mF < 1\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - unvalid 2nd dimension of target')\n end \n heaptr = L(jL, 6);\n if heaptr < 2\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - bookkeeping error ')\n else\n [nH, mH] = size(H);\n if mH ~=1\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - heap should be column vector')\n else\n beginptr = heaptr-nF*mF;\n if heaptr-1 > nH\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - heap not that large')\n elseif beginptr < 1\n disp([' retrieveR - ERROR at type ' o ' level ' num2str(level)]);\n error(' retrieveR - heap not that large, dimensions?')\n else\n F = reshape(H(beginptr:(heaptr-1)), nF, mF); \n end \n end\n end \n end \n end\n end\nend\n%------------------------------------------------------------------------------\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/retrieveR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.38963015451860655}}
{"text": "classdef vfa_t1 < AbstractModel\n% vfa_t1: Compute a T1 map using Variable Flip Angle\n%\n% Assumptions:\n%\n% Inputs:\n% VFAData Spoiled Gradient echo data, 4D volume with different flip angles in time dimension\n% (B1map) Normalized transmit excitation field map (B1+). B1+ is defined \n% as a normalized multiplicative factor such that:\n% FA_actual = B1+ * FA_nominal. (OPTIONAL).\n% (Mask) Binary mask to accelerate the fitting. (OPTIONAL)\n%\n% Outputs:\n% T1 Longitudinal relaxation time [s]\n% M0 Equilibrium magnetization\n%\n% Protocol:\n% VFAData Array [nbFA x 2]:\n% [FA1 TR1; FA2 TR2;...] flip angle [degrees] TR [s]\n%\n% Options:\n% None\n%\n% Example of command line usage:\n% Model = vfa_t1; % Create class from model\n% Model.Prot.VFAData.Mat=[3 0.015; 20 0.015]; %Protocol: 2 different FAs\n% data = struct; % Create data structure\n% data.VFAData = load_nii_data('VFAData.nii.gz');\n% data.B1map = load_nii_data('B1map.nii.gz');\n% FitResults = FitData(data,Model); %fit data\n% FitResultsSave_mat(FitResults);\n%\n% For more examples: qMRusage(vfa_t1)\n%\n%\n% Author: Ian Gagnon, 2017\n%\n% References:\n% Please cite the following if you use this module:\n% Fram, E.K., Herfkens, R.J., Johnson, G.A., Glover, G.H., Karis, J.P.,\n% Shimakawa, A., Perkins, T.G., Pelc, N.J., 1987. Rapid calculation of\n% T1 using variable flip angle gradient refocused imaging. Magn. Reson.\n% Imaging 5, 201?208\n% In addition to citing the package:\n% Karakuzu A., Boudreau M., Duval T.,Boshkovski T., Leppert I.R., Cabana J.F., \n% Gagnon I., Beliveau P., Pike G.B., Cohen-Adad J., Stikov N. (2020), qMRLab: \n% Quantitative MRI analysis, under one umbrella doi: 10.21105/joss.02343\n\nproperties (Hidden=true)\n onlineData_url = 'https://osf.io/7wcvh/download?version=3'; \nend\n\n properties\n MRIinputs = {'VFAData','B1map','Mask'};\n xnames = {'M0','T1'};\n voxelwise = 0;\n \n % Protocol\n Prot = struct('VFAData',struct('Format',{{'FlipAngle' 'TR'}},...\n 'Mat', [3 0.015; 20 0.015])); % You can define a default protocol here.\n\n % fitting options\n st = [2000 0.7]; % starting point\n lb = [0 0.00001]; % lower bound\n ub = [6000 5]; % upper bound\n fx = [0 0]; % fix parameters\n\n % Model options\n buttons = {};\n options= struct(); % structure filled by the buttons. Leave empty in the code\n\n % Simulation Options\n Sim_Single_Voxel_Curve_buttons = {'SNR',50};\n Sim_Optimize_Protocol_buttons = {'# of volumes',5,'Population size',100,'# of migrations',100};\n end\n\nmethods (Hidden=true)\n% Hidden methods goes here.\nend\n\n methods\n\n function obj = vfa_t1()\n obj.options = button2opts(obj.buttons);\n end\n\n function Smodel = equation(obj,x)\n % Generates a VFA signal based on input parameters\n x = mat2struct(x,obj.xnames); % if x is a structure, convert to vector\n\n % Equation: S=M0sin(a)*(1-E)/(1-E)cos(a); E=exp(-TR/T1)\n flipAngles = (obj.Prot.VFAData.Mat(:,1))';\n TR = obj.Prot.VFAData.Mat(1,2);\n E = exp(-TR/x.T1);\n Smodel = x.M0*sin(flipAngles/180*pi)*(1-E)./(1-E*cos(flipAngles/180*pi));\n end\n\n function FitResult = fit(obj,data)\n % T1 and M0\n flipAngles = (obj.Prot.VFAData.Mat(:,1))';\n TR = obj.Prot.VFAData.Mat(:,2);\n if obj.voxelwise == 0\n if (length(unique(TR))~=1), error('VFA data must have same TR'); end\n if ~isfield(data, 'B1map'), data.B1map = []; end\n if ~isfield(data, 'Mask'), data.Mask = []; end\n [FitResult.T1, FitResult.M0] = Compute_M0_T1_OnSPGR(double(data.VFAData), flipAngles, TR(1), data.B1map, data.Mask);\n elseif obj.voxelwise == 1\n if ~isfield(data,'B1map'), data.B1map=1; end\n [m0, t1] = mtv_compute_m0_t1(double(data.VFAData), flipAngles, TR(1), data.B1map);\n FitResult.T1 = t1;\n FitResult.M0 = m0;\n end\n end\n\n function plotModel(obj,x,data)\n if nargin<2 || isempty(x), x = obj.st; end\n x = mat2struct(x,obj.xnames);\n disp(x)\n flipAngles = obj.Prot.VFAData.Mat(:,1)';\n TR = obj.Prot.VFAData.Mat(1,2)';\n subplot(2,1,1)\n if exist('data','var')\n if isfield(data,'B1map')\n if ~isempty(data.B1map)\n B1map=data.B1map;\n end\n else\n B1map=1;\n end\n % Plot data and fitted signal\n plot(flipAngles,data.VFAData,'.','MarkerSize',16)\n else\n B1map=1;\n end\n E = exp(-TR/x.T1);\n Smodel = x.M0*sin(flipAngles/180*pi*B1map)*(1-E)./(1-E*cos(flipAngles/180*pi*B1map));\n hold on\n plot(flipAngles,Smodel,'x','MarkerSize',16)\n hold off\n title('Data points','FontSize',14);\n xlabel('Flip Angle [deg]','FontSize',12);\n ylabel('Signal','FontSize',12);\n legend('data', 'fitted','Location','best')\n set(gca,'FontSize',12)\n\n\n % Plot linear fit\n subplot(2,1,2)\n if exist('data','var')\n ydata = data.VFAData./sin(flipAngles/180*pi*B1map)';\n xdata = data.VFAData./tan(flipAngles/180*pi*B1map)';\n plot(xdata,ydata,'xb','MarkerSize',16)\n hold on\n end\n slope = exp(-TR/x.T1);\n intercept = x.M0*(1-slope);\n X=Smodel./tan(flipAngles/180*pi*B1map);\n mval = min(X);\n Mval = max(X);\n plot([mval Mval],intercept+slope*[mval Mval],'-r');\n hold off\n title(sprintf('Linear Fit: T1=%0.4f s; M0=%0.0f;',x.T1,x.M0),'FontSize',14);\n xlabel('[au]','FontSize',12);\n ylabel('[au]','FontSize',12);\n legend('linearized data', 'linear fit','Location','best')\n %txt=strcat('T1=',num2str(x.T1),'s M0=',num2str(x.M0));\n set(gca,'FontSize',12)\n\n% h = plot( fitresult, xData, yData,'+');\n% set(h,'MarkerSize',30)\n% legend( h, 'y vs. x', 'untitled fit 1', 'Location', 'NorthEast' );\n% p11 = predint(fitresult,x,0.95,'observation','off');\n% hold on\n% plot(x,p11,'m--'); drawnow;\n% hold off\n% % Label axes\n% xlabel( 'x' );\n% ylabel( 'y' );\n% grid on\n% saveas(gcf,['temp.jpg']);\n end\n function [FitResults, data] = Sim_Single_Voxel_Curve(obj, x, Opt,display)\n % Simulates Single Voxel\n %\n % :param x: [struct] fit parameters\n % :param Opt.SNR: [struct] signal to noise ratio to use\n % :param display: 1=display, 0=nodisplay\n % :returns: [struct] FitResults, data (noisy dataset)\n\n if ~exist('display','var'), display = 1; end\n Smodel = equation(obj, x);\n sigma = max(abs(Smodel))/Opt.SNR;\n data.VFAData = ricernd(Smodel,sigma)';\n data.B1map = 1;\n\n FitResults = fit(obj,data);\n if display\n plotModel(obj, FitResults, data);\n end\n end\n\n function SimVaryResults = Sim_Sensitivity_Analysis(obj, OptTable, Opt)\n % SimVaryGUI\n SimVaryResults = SimVary(obj, Opt.Nofrun, OptTable, Opt);\n end\n\n function SimRndResults = Sim_Multi_Voxel_Distribution(obj, RndParam, Opt)\n % SimVaryGUI\n SimRndResults = SimRnd(obj, RndParam, Opt);\n end\n\n\n end\n \n % CLI-only implemented static methods. Can be called directly from\n % class - no object needed.\n methods(Static)\n function Mz = analytical_solution(params)\n %ANALYTICAL_SOLUTION Analytical equations for the longitudinal magnetization of\n %steady-state gradient echo experiments.\n %\n % Reference: Stikov, N. , Boudreau, M. , Levesque, I. R.,\n % Tardif, C. L., Barral, J. K. and Pike, G. B. (2015), On the\n % accuracy of T1 mapping: Searching for common ground. Magn.\n % Reson. Med., 73: 514-522. doi:10.1002/mrm.25135\n %\n % params: Struct.\n % Properties: T1, TR, EXC_FA, constant (optional)\n %\n \n Mz = vfa_equation(params);\n \n end\n \n function signMaxAngle = ernst_angle(params)\n %ERNST_ANGLE Analytical equations for the longitudinal magnetization of\n %steady-state gradient echo experiments.\n %\n % Reference: Ernst, R. R. (1966). \"Application of Fourier \n % transform spectroscopy to magnetic resonance\". Review of \n % Scientific Instruments. 37: 93. doi:10.1063/1.171996\n %\n % params: Struct.\n % Properties: T1, TR\n %\n \n try\n T1 = params.T1;\n TR = params.TR;\n catch\n error('vfa_t1.ernst_equation: Incorrect parameters. Run `help vfa_t1.ernst_angle` for more info.')\n end\n\n signMaxAngle = acosd(exp(-TR./T1));\n \n end\n \n function [Mz, Msig] = bloch_sim(params)\n %BLOCH_SIM Bloch simulations of the GRE-IR pulse sequence.\n % Simulates 100 spins params. Nex repetitions of the IR pulse\n % sequences.\n %\n % params: Struct with the following fields:\n % EXC_FA: Excitation pulse flip angle in degrees.\n % TI: Inversion time (ms).\n % TR: Repetition time (ms).\n % TE: Echo time (ms).\n % T1: Longitudinal relaxation time (ms).\n % T2: Transverse relaxation time (ms).\n % Nex: Number of excitations\n %\n % (optional)\n % df: Off-resonance frequency of spins relative to excitation pulse (in Hz)\n % crushFlag: Numeric flag for perfect spoiling (1) or partial spoiling (2).\n % partialDephasingFlag: do partialDephasing (see below)\n % partialDephasing: Partial dephasing fraction (between [0, 1]). 1 = no dephasing, 0 = complete dephasing (sele\n % inc: Phase spoiling increment in degrees.\n %\n % Outputs:\n % Mz: Longitudinal magnetization at just prior to excitation pulse.\n % Msig: Complex signal produced by the transverse magnetization at time TE after excitation.\n %\n \n %% Setup parameters\n %\n \n alpha = deg2rad(params.EXC_FA);\n TR = params.TR;\n T1 = params.T1;\n \n TE = params.TE;\n T2 = params.T2;\n \n Nex = params.Nex;\n \n %% Optional parameers\n \n if isfield(params, 'df')\n df = params.df;\n else\n df = 0;\n end\n \n if isfield(params, 'crushFlag')\n crushFlag = params.crushFlag;\n else\n crushFlag = 1;\n end\n \n if isfield(params, 'partialDephasingFlag')\n partialDephasingFlag = params.partialDephasingFlag;\n else\n partialDephasingFlag = 0;\n end\n \n if isfield(params, 'partialDephasing')\n partialDephasing = params.partialDephasing;\n else\n partialDephasing = 1;\n end\n \n if isfield(params, 'inc')\n inc = deg2rad(params.inc);\n else\n inc = 0;\n end\n \n %% Simulate for every flip angless\n %\n \n for ii = 1:length(alpha)\n \n [Msig(ii), Mz(ii)] = vfa_blochsim( ...\n alpha(ii), ...\n T1, ...\n T2, ...\n TE, ...\n TR, ...\n crushFlag, ...\n partialDephasingFlag, ...\n partialDephasing, ...\n df, ...\n Nex, ...\n inc ...\n );\n \n end\n end\n \n function EXC_FA = find_two_optimal_flip_angles(params, sigFigs)\n %FIND_TWO_OPTIMAL_FLIP_ANGLES Calculate the two optimal flip\n %angles (having signals 71% of the signal at the Ernst angle).\n %\n % Simulates 100 spins params. Nex repetitions of the IR pulse\n % sequences.\n %\n % References:\n %\n % Deoni, S. C., Rutt, B. K. and Peters, T. M. (2003), Rapid \n % combined T1 and T2 mapping using gradient recalled \n % acquisition in the steady state. Magn. Reson. Med., 49: \n % 515-526. \n %\n % Schabel, M.C. & Morrell, G.R., 2009. Uncertainty in T(1) \n % mapping using the variable flip angle method with two flip \n % angles. Physics in medicine and biology, 54(1), pp.N1?8.\n \n \n if ~exist('sigFigs','var')\n sigFigs = 0;\n end\n \n % Set up search space of flip angle and signal values\n flipAngleSearchSpace = 0:1*10^(-sigFigs):90;\n \n params.EXC_FA = flipAngleSearchSpace;\n signals = vfa_t1.analytical_solution(params);\n \n % Get the Angle, find index in search space\n maxAngle = vfa_t1.ernst_angle(params);\n [~,maxRangeIndex] = min(abs(flipAngleSearchSpace-maxAngle));\n \n % Calculate signal at optimal flip angle values\n optAngleSignal= 0.71*signals(maxRangeIndex);\n \n % Calculate indices of optimal flip angles (smaller and larger\n % than the Ernst angle)\n [~,optRangeIndex_small] = min(abs(signals(1:maxRangeIndex)-optAngleSignal));\n [~,optRangeIndex_large_rel] = min(abs(signals(maxRangeIndex+1:end)-optAngleSignal));\n optRangeIndex_large = maxRangeIndex+optRangeIndex_large_rel;\n \n % Output optimal flip angle values\n EXC_FA = [flipAngleSearchSpace(optRangeIndex_small), flipAngleSearchSpace(optRangeIndex_large)];\n \n end\n end\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/src/Models/T1_relaxometry/vfa_t1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3895867412089813}}
{"text": "%==============================================================================\n%\n% function [yc,His] = lBFGS(fctn,yc,varargin)\n%\n% limited BFGS optimizer\n%\n% Input:\n% ------\n% fctn function handle\n% yc starting guess \n% varargin optional parameter, see below\n%\n% Output:\n% -------\n% yc numerical optimizer (current iterate)\n% His iteration history\n%==============================================================================\n\nfunction [yc,His] = lBFGS(fctn,yc,varargin)\n\nif nargin ==0, % help and minimal example\n help(mfilename); \n E9_MRIhead_MLIRlBFGS_NGF_mbElas; \n yc = 'endOfMinimalExample'; \n His = [];\n return;\nend;\n\n% parameter initialization -----------------------------------------------\nmaxIter = 10; % maximum number of iterations\ntolJ = 1e-3; % for stopping, objective function\ntolY = 1e-2; % - \" - , current value\ntolG = 1e-2; % - \" - , norm of gradient\nsolver = regularizer;\nmaxLBFGS = 5; % maximum number of BFGS vectors\nLSmaxIter = 10; % maximum number of line search iterations\nLSreduction = 1e-4; % minimal reduction in line search\nvecNorm = @norm; % norm to be used for dJ and dy \nyStop = []; % used for stopping in multi-level framework\nJstop = []; % \nPlots = @(iter,para) []; % for plots;\n\nfor k=1:2:length(varargin), % overwrites default parameter\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\nobjFctn = fctn([]);\n\nif isempty(yStop), yStop = yc; end; % yStop used for stopping only\n% -- end parameter set-up ----------------------------------------------\n\n% some output\nFAIRmessage([mfilename '(JM 2009/01/31)']);\nfprintf('[ maxIter=%d / maxLBFGS=%d / tolJ=%s / tolY=%s / tolG=%s / length(yc)=%d ]\\n',...\n maxIter,maxLBFGS,num2str(tolJ),num2str(tolY),num2str(tolG),length(yc));\n\n% -- initialize --------------------------------------------------------- \nSTOP = zeros(5,1);\n\nzBFGS = []; % memory for BFGS gradient directions\nsBFGS = []; % memory for BFGS directions\nnBFGS = 0; % counter for number of limited BFGS directions\n\nif isempty(Jstop),\n % evaluate objective function for stopping values and plots\n [Jstop,para] = fctn(yStop); Jstop = abs(Jstop) + (Jstop == 0);\n Plots('stop',para);\nend;\n\n% evaluate objective function for starting values and plots\n[Jc,para,dJ,H0] = fctn(yc); \nPlots('start',para);\niter = 0; yOld = 0*yc; Jold = Jc; y0 = yc;\n\nhisStr = {'iter','J','Jold-J','|\\nabla J|','|dy|','LS'};\nhis = zeros(maxIter+2,6);\nhis(1,1:3) = [-1,Jstop,Jstop-Jc];\nhis(2,:) = [0,Jc,Jstop-Jc,vecNorm(dJ),vecNorm(yc-yStop),0];\n\n% some output\nfprintf('%4s %-12s %-12s %-12s %-12s %4s\\n%s\\n',...\n hisStr{:},char(ones(1,64)*'-'));\ndispHis = @(var) ...\n fprintf('%4d %-12.4e %-12.3e %-12.3e %-12.3e %4d\\n',var);\ndispHis(his(1,:));\n% -- end initialization ------------------------------------------------\n\n\n% ==============================================================================\n% MAIN LOOP\n% ==============================================================================\nwhile 1,\n % check stopping rules\n STOP(1) = abs(Jold-Jc) <= tolJ*(1+abs(Jstop));\n STOP(2) = (iter>0) && (norm(yc-yOld) <= tolY*(1+norm(y0)));\n STOP(3) = norm(dJ) <= tolG*(1+abs(Jstop));\n STOP(4) = norm(dJ) <= 1e3*eps;\n STOP(5) = (iter >= maxIter);\n if all(STOP(1:3)) || any(STOP(4:5)), break; end;\n\n iter = iter + 1;\n \n \n % update at most maxLBFGS BFGS directions\n if iter > 1,\n zz = (dJ - dJold)';\n ss = yc - yOld;\n if zz'*ss > 0, \n start = 2-(nBFGSfac,\n dy = (fac/maxdy)*dy;\n %H0 = fac*H0;%speye(length(dy),length(dy));\n end;\n else\n H0 = norm(dJ) * speye(length(dy),length(dy));\n end;\n end;\n % perform Armijo line-search\n [t,yt,LSiter] = Armijo(fctn,yc,dy,Jc,dJ,...\n 'LSmaxIter',LSmaxIter,'LSreduction',LSreduction);\n if (t == 0), \n break; \n end; % break if line-search fails\n\n % update variables\n yOld = yc; Jold = Jc; dJold = dJ; yc = yt;\n [Jc,para,dJ] = fctn(yc); % evaluate objective function\n \n % some output\n his(iter+2,:) = [iter,Jc,Jold-Jc,vecNorm(dJ),vecNorm(yc-yOld),LSiter];\n dispHis(his(iter+1,:));\n para.normdY = vecNorm(yc - yOld);\n Plots(iter,para);\n \nend;%while; % end of iteration loop\n% ==============================================================================\n\n% clean up\nHis.str = hisStr;\nHis.his = his(1:iter+2,:);\nfprintf('STOPPING:\\n');\nfprintf('%d[ %-10s=%16.8e <= %-25s=%16.8e]\\n',STOP(1),...\n '(Jold-Jc)',(Jold-Jc),'tolJ*(1+|Jstop|)',tolJ*(1+abs(Jstop)));\nfprintf('%d[ %-10s=%16.8e <= %-25s=%16.8e]\\n',STOP(2),...\n '|yc-yOld|',norm(yc-yOld),'tolY*(1+norm(yc)) ',tolY*(1+norm(yc)));\nfprintf('%d[ %-10s=%16.8e <= %-25s=%16.8e]\\n',STOP(3),...\n '|dJ|',norm(dJ),'tolG*(1+abs(Jstop)',tolG*(1+abs(Jstop)));\nfprintf('%d[ %-10s=%16.8e <= %-25s=%16.8e]\\n',STOP(4),...\n 'norm(dJ)',norm(dJ),'eps',1e3*eps);\nfprintf('%d[ %-10s= %-14d >= %-25s= %-14d]\\n',STOP(5),...\n 'iter',iter,'maxIter',maxIter);\n\nFAIRmessage([mfilename,' : done !']);\n\n%------------------------------------------------------------------------------\n\nfunction[d] = bfgsrec(solver,n,S,Z,H,d)\n\nmaxIterCG = 10; tolCG = 1e-2;\nif isempty(solver) \n if isstruct(H),\n if isfield(H,'solver'), \n solver = H.solver;\n elseif isfield(H,'d2S') && isfield(H.d2S,'solver'), \n solver = H.d2S.solver;\n else\n error('solver has not been defined')\n end;\n\n end\nend\n\nif n == 0, \n switch solver,\n case {'MG-elastic'}\n d = MGsolver(d,H);\n case {'pcg'}\n L = tril(H); % Symmetric Gauss Seidel Preconditioning,\n D = diag(H); % L is lower, D is diagonal, U = L'\n SGS = @(x) L\\(D.*(L'\\x));\n d = pcg(H,d,tolCG,maxIterCG,SGS);\n case 'PCG-curvature',\n M = @(x) H.d2D.M;\n Afctn = @(x) M(x) + H.d2S.d2S(x,H.omega,H.m);\n % preconditioner\n Ddiag = H.d2D.M;\n D = Ddiag + H.d2S.diag(H.omega,H.m);\n PC = @(x) D.\\x; % Jacobi preconditioner\n [d,flag,relres,iter] = pcg(Afctn,d,tolCG,maxIterCG,PC);\n\n otherwise,\n if isnumeric(H),\n % if H is a matrix, solve the linear system using MATLAB's backslash\n d = H\\d;\n else\n error('nyi - solver %s', solver)\n end;\n end; \nelse\n alpha = (S(:,n)'*d)/(Z(:,n)'*S(:,n));\n d = d - alpha*Z(:,n);\n d = bfgsrec(solver,n-1,S,Z,H,d);\n d = d + (alpha - (Z(:,n)'*d)/(Z(:,n)'*S(:,n)))*S(:,n);\nend;\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/numerics/lBFGS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3895321675725951}}
{"text": "\nfunction F_enhance= RSWHEg_gray( F )\n% Bi Bi histogram equalization with recursively seperated weighted histgram\n% equalization with mean and mean\n% clear all;\n% close all;\n% clc;\n%close figure;\n% x0=imread('pout.tif');\n%x0=imread('eswar.jpg');\n% x0=imread('54.tif');\n% x0=imread('source24_1.tif');\n% figure;\n% imshow(x0);\n% x0=imread('untitled.bmp');\n %x0=imread('plane.bmp');\n%x0=uint8(x0);\n% \n% %x0=imread('12.bmp');\n% %u=double(i);\n% h = [0.0086,0.0856,0.0086;\n% 0.0856,0.8561,0.0856;\n% 0.0086,0.0856,0.0086];\n% h = h/sum1(h(:)); % Normalize the filter\n% uSmooth = conv2padded(double(x0),double(h));\n%figure(1);\n%imshow(uint8(uSmooth));\n %luma=uint8(uSmooth(:,:,1));\n% XM=0;\n% y0=rgb2ycbcr(x0);\nluma=F;%(y0(:,:,1));\n%luma=wiener2(luma);\n%luma=luma-60;\n[m,n]=size(luma);\n%luma=luma;\n% cb=y0(:,:,2);\n% cr=y0(:,:,3);\nk=mean(mean(luma));\nXM=k;\nXG=round(255/2);\n[pixelCounts bins] = imhist(luma, 256);\n[m12,xmax]=max(imhist(luma,256));\n[m21,xmin]=min(imhist(luma,256));\nPmax=(max(imhist(luma,256))/(m*n));\nPmin=(min(imhist(luma,256))/(m*n));\nbeta=Pmax*((abs(XM-XG))/(xmax-xmin));\nr=round(k);\nl=length(luma(luma<=r));\n listindex=find(luma<=r);\n k1=reshape(luma(listindex),l,1);%obtained below fist mean values put it into an arry\n k2=mean(k1);%find mean of mean in first half\n k3=round(k2);%round to nearest integer to find pdf and cdf till first quarter\n sum1=0;\n l1=length(luma(luma<=k3));%find all values in luma falls below fist mean\n listindex1=find(luma<=k3);%all values in luma falls below fist mean given in their locations\n k4=reshape(luma(listindex1),l1,1);%arrange all fist mean values in a vector\n xpdf=hist(k4,[0:k3]);%pdf from 0:r\n xpdf=xpdf/(m*n);\n %alpa0=max(cumsum(xpdf/(m*n)));%from line 39 to 48 new rswhe code add this to other quarters\n alpa=(cumsum(xpdf));\n alpa0=alpa(end);\n %xpdf=xpdf/l1;%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form 0 to r.\n sum1=0;\n for l2=0:k3\n \n pw(l2+1)=(Pmax*((xpdf(l2+1)-Pmin)/(Pmax-Pmin))).^alpa0+beta;\n sum1=sum1+pw(l2+1);\n end\n for l2=0:k3\n pwn(l2+1)=pw(l2+1)/(sum1);\n end\n %plot(pwn);\n %(imhist(luma));\n %xlabel('gray levels up to mean');\n %ylabel('pdf up to mean');\n %title('histogram for half an image up to mean');\n %sk=xpdf*triu(ones(k3+1));\n sk=pwn*triu(ones(k3+1));\n% figure(2);\n% plot(sk);\n% xlabel('gray levels upto 1st mean');\n% ylabel('cdf upto mean');\n% title('cdf for half of an image up to ist mean');\n % alpha=0.7;\n for l2=0:k3\n if(xpdf(l2+1)>0)\n list1=find(k4==l2);%find value in an vector i.e converted from matrix\n %list(list1)=alpha*sk(l2+1)*(k3+1)+(1-alpha)*(k3+1);\n list(list1)=(sk(l2+1)*(k3+1));%map dont disturb to get bhe as\n %list(list1)=alpha*sk(l2+1)*(k3+1)+(1-alpha)*(k3+1);\n %it is 13/3/2011\n ert(l2+1)=(sk(l2+1)*(k3+1));\n end\n end\n p=zeros(m,n); \n p(listindex1)= list; %listindex1 mxn locations list transformed values.\n% figure(3);\n% imshow(p);\n% xlabel('gray levels up to first mean');\n% ylabel('luma component equilized image up to first mean');\n% title('processed luma image up to first mean');\n k=mean(mean(luma));\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2nd quarter\nr=round(k);\nl=length(luma(luma<=r));\n listindex=find(luma<=r);\n k1=reshape(luma(listindex),l,1);%obtained below fist mean values put it into an arry\n k2=mean(k1);%find mean of mean in first half\n k3=round(k2);%round to nearest integer to find pdf and cdf till first quarter\n% sum1=0;\n b=k3;\n% l2=length(luma(luma>k3));%find all values in luma falls below fist mean\n listindex2=find((luma>k3)&(luma<=r));%all values in luma falls below fist mean given in their locations\n l2=length(listindex2);\n k5=reshape(luma(listindex2),l2,1);%arrange all fist mean values in a vector\n x2pdf=hist(k5,[k3+1:r]);%pdf from 0:r\n x2pdf=x2pdf/(m*n);%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form 0 to r.\n %alpa1=max(cumsum(x2pdf/(m*n)));%from line 39 to 48 new rswhe code add this to other quarters\n alpa=(cumsum(x2pdf));%/(m*n)))\n alpa1=alpa(end);\n %x2pdf=x2pdf/l2;%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form 0 to r.\n sum1=0;\n for l2k=0:r-(k3+1)\n pw1(l2k+1)=(Pmax*((x2pdf(l2k+1)-Pmin)/(Pmax-Pmin))).^alpa1+beta;\n sum1=sum1+pw1(l2k+1);\n end\n for l2k=0:r-(k3+1)\n pw1n(l2k+1)=pw1(l2k+1)/(sum1);\n end\n% figure(4);\n% plot(x2pdf);\n% xlabel('gray levels 2nd mean');\n% ylabel('pdf of 2nd mean');\n% title('histogram for 2nd mean');\n sk2=pw1n*triu(ones(r-k3));\n% figure(5);\n% plot(sk2);\n% xlabel('gray levels of 2nd mean');\n% ylabel('cdf upto mean');\n% title('cdf for half of an image of 2nd mean');\n k2u=1;\n for l3=k3+1:r\n if(pw1n(k2u)>0)\n list2=find(k5==l3);%find value in an vector i.e converted from matrix\n %list1(list2)=alpha*(sk2(k2u)*(r-k3)+(k3+1))+(1-alpha)*(k3+1);\n list1(list2)=((k3+1)+(sk2(k2u))*(r-k3-1));%map dont disturb to\n %list1(list2)=alpha*(sk2(k2u)*(r-k3)+(k3+1))+(1-alpha)*(k3+1);\n %get BHE 13/3/2011\n ert(l3)=((k3+1)+(sk2(k2u))*(r-k3-1));\n end\n k2u=k2u+1;\n \n end\n \n p(listindex2)= list1;\n% figure(6);\n% imshow(p);\n% xlabel('gray levels up to first 2nd mean');\n% ylabel('luma component equilized image 2nd mean');\n% title('processed luma image up to 2nd mean');\n %lupper30=length(luma(luma>r);\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n lupper30=length(luma(luma>r));\n%for i=0:r\n %if(luma(luma<=r))\n listindexupper3=find(luma>r);\n % end\n%end\n k1upper=reshape(luma(listindexupper3),lupper30,1);\n mean3=mean(k1upper);\n r3=round(mean3);\n %length30=length((luma<=r3)&(luma>r));\n listindexupper30=find((luma>r)&(luma<=r3));\n length30=length(listindexupper30);\n k30upper=reshape(luma(listindexupper30),length30,1);\n \n %length30=length((luma<=r3)&(luma>r));\n% sum1=0;\nalpa=0;\n xpdfupper30=hist(k30upper,[r+1:r3]);%pdf from r+1:r3\n xpdfupper30=xpdfupper30/(m*n);%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form r+1 to 255.\n%alpa2=max(cumsum(xpdfupper30/(m*n)));%from line 39 to 48 new rswhe code add this to other quarters\nalpa=(cumsum(xpdfupper30));%/(m*n)))\nalpa2=alpa(end);\n %x3pdf=xpdfupper30/length30;%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form 0 to r.\nsum1=0;\n for l2k=0:r3-(r+1)\n %pw2(l2k+1)=(Pmax*((x3pdf(l2k+1)-Pmin)/(Pmax-Pmin))).^alpa2+beta;\n pw2(l2k+1)=(Pmax*((xpdfupper30(l2k+1)-Pmin)/(Pmax-Pmin))).^alpa2+beta;\n sum1=sum1+pw2(l2k+1);\n end\n for l2k=0:r3-(r+1)\n pw2n(l2k+1)=pw2(l2k+1)/(sum1);\n end \n% figure(7);\n% plot(pw2n);\n% xlabel('gray levels 3rd mean');\n% ylabel('pdf of 3rd mean');\n% title('histogram for upper half an image 3rd mean');\n skupper30=pw2n*triu(ones(r3-r));\n% figure(8);\n% plot(skupper30);\n% xlabel('gray levels after mean');\n% ylabel('cdf after mean');\n% title('cdf for upper half of an image after mean');\n k3u=1;\n for k3upper=(r+1):r3\n if(pw2n(k3u)>0)\n list1upper30=find(k30upper==k3upper);%find value in an vector i.e converted from matrix\n listnew(list1upper30)=((r+1)+skupper30(k3u)*(r3-r-1));%map dont\n %listnew(list1upper30)=alpha*(skupper30(k3u)*(r3-r)+(r+1))+(1-alpha)*(r+1);\n %disturg to get original heq 14/3/2011\n %listnew(list1upper30)=alpha*(skupper30(k3u)*(r3-r)+(r+1))+(1-alpha)*(r+1);\n ert(k3upper)=((r+1)+skupper30(k3u)*(r3-r-1));\n end\n k3u=k3u+1;\n\n end\n \n% p2=zeros(m,n);\n \n p(listindexupper30)= listnew;\n% figure(9);\n% imshow(p);\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n listindexupper40=find(luma>r3);\n lupper40=length(listindexupper40);\n % end\n%end\n k1upper40=reshape(luma(listindexupper40),lupper40,1);\n %sum1=0;\n %for i=0:r\n alpa=0;\n xpdfupper40=hist(k1upper40,[r3+1:255]);%pdf from r+1:255\n xpdfupper40=xpdfupper40/(m*n);%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form r+1 to 255.\nalpa=(cumsum(xpdfupper40));%/(m*n)));%from line 39 to 48 new rswhe code add this to other quarters\nalpa3=alpa(end);\n % x4pdf=xpdfupper40/lupper40;%normalized pdf to get nk/n,l=sum1 of xpdf,total no of pixels form 0 to r.\nsum1=0;\n for l2k=0:(255-(r3+1))\n pw3(l2k+1)=(Pmax*((xpdfupper40(l2k+1)-Pmin)/(Pmax-Pmin))).^alpa3+beta;\n sum1=sum1+pw3(l2k+1);\n end\n for l2k=0:(255-(r3+1))\n pw3n(l2k+1)=pw3(l2k+1)/(sum1);\n end \n% figure(10);\n% plot(xpdfupper40);\n% xlabel('gray levels after 4mean');\n% ylabel('pdf after 4mean');\n% title('histogram for upper half an image after 4mean');\n skupper40=pw3n*triu(ones(255-r3));\n% figure(11);\n% plot(skupper40);\n% xlabel('gray levels after 4mean');\n% ylabel('cdf after 4mean');\n% title('cdf for upper half of an image after 4mean');\n k4u=1;\n for k4upper=(r3+1):255\n if(pw3n(k4u)>0)\n list1upper40=find(k1upper40==k4upper);%find value in an vector i.e converted from matrix\n %for k2u=1:58\n %listnew4(list1upper40)=alpha*(198+skupper40(k4u))*(255-r3)+(1-alpha)*(r3+1);\n listnew4(list1upper40)=(r3+1)+skupper40(k4u)*(255-r3-1);%map\n %listnew4(list1upper40)=alpha*((r3+1+skupper40(k4u))*(255-r3))+(1-alpha)*(r3+1);\n % listnew4(list1upper40)=alpha*(198+skupper40(k4u)*(255-r3))+(1-alpha)*(r3+1);\n %dont disturb to get original bbhe 14/3/2011\n %end\n ert(k4upper)=(r3+1)+skupper40(k4u)*(255-r3-1);\n end\n k4u=k4u+1;\n end\n \n% for i=0:l-1\n %p3=zeros(m,n);\n% if (p(listindex))\n% p(:)=list;\n% end\n% end\n \n p(listindexupper40)= listnew4;\n% figure(12);\n% imshow(p);\n% xlabel('gray levels after 4mean');\n% ylabel('luma component equilized image after 4mean');\n% title('processed luma image after 4mean');\n ommmmm=p;\n F_enhance=ommmmm;\n end\n %ommmmm=p1+p;\n% figure(13);\n% imshow(ommmmm);\n% colormap('gray');\n% xlabel('gray level');\n% ylabel('combined lower and upper half luma component equilized image');\n% title('combined luma image');\n% % figure(8);\n% image(om);\n% % for j1=0:255\n% % count=0;\n% % for i1=0:m*n-1\n% % if om(i1+1)==j1\n% % count=count+1;\n% % end\n% % end\n% % prob(j1+1)=count/m*n;\n% % end\n% % figure(16);\n% % plot(prob);\n% % \n% % for j2=0:255\n% % count1=0;\n% % for i2=0:m*n-1\n% % if luma(i2+1)==j2\n% % count1=count1+1;\n% % end\n% % end\n% % prob2(j2+1)=count1/m*n;\n% % end\n% % figure(17);\n% % plot(prob2); \n% % xlabel('gray levels after mean');\n% % ylabel('luma component equilized image after mean');\n% % title('processed luma image after mean');\n% % ommmmm=p1+p;\n% % figure(7);\n% % colormap('gray');\n% % xlabel('gray level');\n% % ylabel('combined lower and upper half luma component equilized image');\n% % title('combined luma image');\n% % image(ommmmm);\n%k=imshow(ommmmm);\n% cat1=cat(3,ommmmm,cb,cr);\n% % figure(14);\n% % imshow(cat1);\n% % % xlabel('gray level(ycbcr)');\n% % ylabel('combined lower and upper half luma,cromablue,croma red component equilized image');\n% % title('luma croma b and r color processed image');\n% catconversion=ycbcr2rgb(uint8(cat1));\n% figure(15);\n% imshow(uint8(ommmmm));\n% xlabel('gray level(rgb)');\n% ylabel('combined lower and upper half RGB component equilized image');\n% title('converted from ycbcr2rgb color(RGB) processed image');\n% YM=0;\n% YM=mean(mean(ommmmm));\n% AMBE=abs(XM-YM);\n% disp('Absolute mean brightness error=');\n% disp(AMBE);\n %MSE = meanSquareError(luma, ommmmm);\n % figure(16);\n%disp('mean Square Error = ');\n%disp(MSE);\n%PSNR1 = PSNR(luma, ommmmm);\n%figure(17);\n% disp('Peak Signal to Noise Ratio = ');\n% disp(PSNR1);\n% E=entropy(uint8(ommmmm));\n% disp('Entropy=');\n% disp(E);\n% figure(16);\n% (imhist(uint8(ommmmm)));\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/MGFF/RSWHEg_gray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3894045015155844}}
{"text": " function X = nufft(x, st)\n%function X = nufft(x, st)\n%|\n%| Compute d-dimensional NUFFT of signal/image x\n%|\n%| in\n%|\tx\t[N1 N2 ... Nd (L)]\tL input image(s) of size\n%|\t\t\t\t\t\tN1 x N2 x ... x Nd\n%|\tst\tstructure\t\tprecomputed by nufft_init()\n%| out\n%|\tX\t[M (L)]\t\t\toutput spectra\n%|\n%| Copyright 2003-5-30, Jeff Fessler, University of Michigan\n\n% if no arguments, then run some self tests\nif (nargin < 1) || (nargin == 1 && streq(x, 'test'))\n\thelp([mfilename '.m'])\n\n\tprintm('Starting nufft() self test; after a wait, shows small errors')\n\tif 0\n\t\tJd = [5 4 4];\n\t\tNd = [23 15 19];\n\t\talpha_user = {1, 1, 1}; % default alpha, beta\n\t\tbeta_user = {0.5, 0.5, 0.5};\n\telse\n\t\tJd = [5 6];\n\t\tNd = [60 75];\n\t\talpha_user = {1, 1};\n\t\tbeta_user = {0.5, 0.5};\n\tend\n\tKd = 2 * Nd;\n\tgam = 2*pi ./ Kd;\n\tn_shift = zeros(size(Nd));\n\n\tif 1\n\t\toldarg = {Nd(1), Nd(2), Jd(1), Jd(2), Kd(1), Kd(2)};\n\t\tprintm('err alf1 %g best %g', ...\n\t\t\tmax(col(nufft2_err_mm('all', oldarg{:}, 1))), ...\n\t\t\tmax(col(nufft2_err_mm('all', oldarg{:}, 'best'))) )\n\tend\n\trng(0)\n\tx = randn(Nd);\n%\tx = [[1:Nd(1)]'*ones(1,3), ones(Nd(1), Nd(2)-3)]; % test signal\n%\tx = zeros(N1, N2); x(1,1) = 1;\n\tif 0 % test with uniform frequency locations\n\t\to1 = 2 * pi * [0:(N1-1)]' / N1;\n\t\to2 = 2 * pi * [0:(N2-1)]' / N2;\n\t\t[o1, o2] = ndgrid(o1, o2);\n\t\tXf = fft2(x);\n\telse\n\t\tif length(Nd) == 3 % nonuniform frequencies\n\t\t\t[o1, o2, o3] = ndgrid(linspace(0,gam(1),11), ...\n\t\t\t\tlinspace(0,gam(2),13), linspace(0,gam(3),5));\n\t\t\tom = [\t[o1(:); [0 7.2 2.6 3.3]'], ...\n\t\t\t\t[o2(:); [0 4.2 -1. 5.5]'], ...\n\t\t\t\t[o3(:); [0 1.1 -2. 3.4]'] ];\n\t\telse\n\t\t\t[o1, o2] = ndgrid(linspace(-3*gam(1),3*gam(1),41), ...\n\t\t\t\tlinspace(-2*gam(2),gam(2),31));\n\t\t\tom = [\t[o1(:); [0 7.2 2.6 3.3]'], ...\n\t\t\t\t[o2(:); [0 4.2 -1. 5.5]'] ];\n\t\tend\n\t\tY.d = dtft(x, om, 'n_shift', n_shift);\n\tend\n\n\ts.tab = nufft_init(om, Nd, Jd, Kd, n_shift, 'table', 2^12, 'minmax:kb');\n\tY.tab = nufft(x, s.tab);\n\tprintm('table0\t\tmax%%diff = %g', max_percent_diff(Y.d, Y.tab))\n\n\ts.mmkb = nufft_init(om, Nd, Jd, Kd, n_shift, 'minmax:kb');\n\tY.mmkb = nufft(x, s.mmkb);\n\tprintm('minmax:kb\tmax%%diff = %g', max_percent_diff(Y.d, Y.mmkb))\n\n\tif 0 % test multiple input case\n\t\txx = x; xx(:,:,:,2) = x; xx(:,:,:,3) = x;\n\t\tY.tmp = nufft(xx, s.mmkb);\n\t\tY.tmp = Y.tmp(:,1);\n\t\tprintm('multi\tmax%%diff = %g', max_percent_diff(Y.mmkb, Y.tmp))\n\treturn\n\tend\n\n\t% kaiser with minmax best alpha,m\n\ts.kb = nufft_init(om, Nd, Jd, Kd, n_shift, 'kaiser');\n\tY.kb = nufft(x, s.kb);\n\tprintm('kaiser\t\tmax%%diff = %g', max_percent_diff(Y.d, Y.kb))\n\n\t% kaiser with user-specified supoptimal alpha,m for comparison\n\ts.ku = nufft_init(om, Nd, Jd, Kd, n_shift, 'kaiser', ...\n\t\ts.kb.kb_alf + 0.1*ones(size(s.kb.kb_alf)), s.kb.kb_m);\n\tY.ku = nufft(x, s.ku);\n\tprintm('kaiser-user\tmax%%diff = %g', max_percent_diff(Y.d, Y.ku))\n\n\ts.mmtu = nufft_init(om, Nd, Jd, Kd, n_shift, 'minmax:tuned');\n\tY.mmtu = nufft(x, s.mmtu);\n\tprintm('minmax:tuned\tmax%%diff = %g', max_percent_diff(Y.d, Y.mmtu))\n\n\ts.mm = nufft_init(om, Nd, Jd, Kd, n_shift, 'minmax:user', ...\n\t\talpha_user, beta_user);\n\tY.mm = nufft(x, s.mm);\n\tprintm('minmax:user\tmax%%diff = %g', max_percent_diff(Y.d, Y.mm))\n\n\tif 0 % test 'uniform' scaling\n\t\ts.un = nufft_init(om, Nd, Jd, Kd, n_shift, 'uniform')\n\t\tY.un = nufft(x, s.un);\n\t\tprintm('user-unif max%%diff = %g', max_percent_diff(Y.mm, Y.un))\n\treturn\n\tend\n\n%\ts1 = nufft_init(om, Nd, Jd, Kd, n_shift, 'loop', 'kaiser');\n%\tprintm('kb loop max %% difference = %g', max_percent_diff(sn.p,s1.p))\n\n if 0 % test against old 2D version\n\ts2 = nufft2_init_kb(om, oldarg{:}, n_shift, 'kaiser');\n%\tY2 = nufft2(x, s2);\n%\tprintm('KB 2d vs nd max%%diff = %g', max_percent_diff(Y2, Y.kb))\n\tprintm('KB 2d vs nd max%%diff = %g', max_percent_diff(s2.p,s.kb.p))\n\n\ts2 = nufft2_init(om, oldarg{:}, n_shift, 0, 'best');\n\tprintm('tuned 2d vs nd max%%diff = %g', max_percent_diff(s2.p,s.mmtu.p))\n\n\ts2 = nufft2_init(om, oldarg{:}, n_shift, 0); % minmax\n\tprintm('user 2d vs nd max%%diff = %g', max_percent_diff(s2.p,s.mm.p))\n\n end\nreturn\nend\n\nNd = st.Nd;\nKd = st.Kd;\n\ndims = size(x);\ndd = length(Nd);\nif ndims(x) < dd, fail 'input signal has too few dimensions', end\nif any(dims(1:dd) ~= Nd), fail 'input signal has wrong size', end\n\n\n% the usual case is where L=1, i.e., there is just one input signal.\nif ndims(x) == dd\n\tx = x .* st.sn; % apply scaling factors\n\tXk = col(fftn_fast(x, Kd)); % [*Kd] oversampled FFT, padded at end\n\n% otherwise, collapse all excess dimensions into just one\nelse\n\txx = reshape(x, [prod(Nd) prod(dims((dd+1):end))]); % [*Nd *L]\n\tL = size(xx, 2);\n\tXk = zeros(prod(Kd), L, class(xx)); % [*Kd *L]\n\tfor ll=1:L\n\t\txl = reshape(xx(:,ll), [Nd 1]); % l'th signal\n\t\txl = xl .* st.sn; % scaling factors\n\t\tXk(:,ll) = col(fftn_fast(xl, [Kd 1]));\n\tend\nend\n\n\n% interpolate using precomputed sparse matrix\n% or with tabulated interpolator\nif ~isfield(st, 'interp_table')\n\tX = st.p * Xk; % [M *L]\nelse\n\tX = feval(st.interp_table, st, Xk);\nend\n\nif ndims(x) > dd\n\tX = reshape(X, [st.M dims((dd+1):end)]); % [M (L)]\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/nufft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3893324859417779}}
{"text": "function [clusterID,EventType,AlgoInfo] = calc_decluster_gardKnop(mCatalog,nMethod,SetMain)\n\t% decluster earthquake catalog using the Windowing technique in space and time (Knopoff & Gardner)\n\t%\n\t% [mCatDecluster, mCatAfter, vCluster, vCl, vMainCluster] = CALC_DECLUSTER_GARDKNOP(mCatalog,nMethod)\n\t% ----------------------------------------------------------------------------------------------------------\n\t% \n\t% Decluster earthquake catalog using the Windowing technique in space and time by \n\t% Knopoff & Gardner, GJR astr. Soc, 28, 311-313, 1972\n\t% Gardner & Knopoff, BSSA, 64,5, 1363-1367, 1974\n\t% using different windows\n\t% \n\t% Incoming variables\n\t% mCatalog : Incoming earthquake catalog (ZMAP format)\n\t% nMethod : Window length for declustering (see calc_windows.m)\n\t% 1: Gardener & Knopoff, 1974\n\t% 2: Gruenthal pers. communication\n\t% 3: Urhammer, 1986 \n\t% \n\t% Outgoing variables:\n\t% mCatDecluster : Declustered earthquake catalog\n\t% mCatAfter : Catalog of aftershocks (and foreshocks)\n\t% vCluster : Vector indicating only aftershocks/foreshocls in cluster using a cluster number\n\t% vCl : Vector indicating all events in clusters using a cluster number\n\t% vMainCluster : Vector indicating mainshocks of clusters using a cluster number\n\t%\n\t% J. Woessner, woessner@seismo.ifg.ethz.ch\n\t% last update: 29.08.02\n\t\n\t%% Added:\n\t% 31.07.02 Correction for problem of mainshocks with a cluster number as aftershocks belong to two sequences\n\t% 31.07.02 Corrected fMaxClusterMag(nMagCount) to fMaxClusterMag, since counting variable not needed\n\t% 31.07.02 Improved resizing time window by adding time difference from initial event to bigger aftershock \n\t% 13.08.02 Added waitbars\n\t% 28.08.02 Changed distance determination using now distance and repmat\n\t% 29.08.02 Cluster determination strategy change: Now selecting all aftershocks using the window of the first shock,\n\t% adding the events from the bigger aftershocks (later labelled mainshocks); calc_decluster_ver3.m keeps\n\t% resizing technique \n\t\n\t%%% Remember: Improve zero length cluster problem which might appear\n\t\n\t%% Initialize Vectors and Matrices\n\t\n\timport mapseis.declustering.calc_windows_gardKnop;\n\t\n\t%edited for MapSeis: DE 2011\n\t%This is the first release of the Gardner Knopoff method for mapseis, the code is mainly the same as the zmap version, there might be\n\t%lot to gain performancewise in case of a rewriting of the code, but for know this should be alright.\n\t\n\t\n\tif nargin<3\n\t\tSetMain=false;\n\tend\n\t\n\t\t\n\tmCatDecluster = [];\n\tmCatAfter = [];\n\tvCluster = zeros(length(mCatalog),1); % Initialize all events as mainshock\n\tvCl = zeros(length(mCatalog),1); % Initialize all events as mainshock\n\tvSel = zeros(length(mCatalog),1); % Initialize all events as mainshock\n\tvMainCluster = zeros(length(mCatalog),1); % Initialize\n\t\n\t%[B,MagSortID] = sort(mCatalog(:,6),'descend');\n\t\n\t[nXSize, nYsize] = size(mCatalog);\n\tif nXSize == 0\n\t disp('Load new catalog');\n\t return\n\tend\n\t\n\tvDecDate = mCatalog(:,3);\n\tnCount = 0; % Variable of cluster number\n\t\n\tfMagThreshold = min(mCatalog(:,6)); % Set Threshold to minimum magnitude of catalog\n\thWaitbar1 = waitbar(0,'Identifying clusters...');\n\tset(hWaitbar1,'Numbertitle','off','Name','Decluster percentage');\n\tfor nEvent=1:length(mCatalog(:,6)) \n\t %nEvent\n\t %nCount\n\t %nEvent=MagSortID(iCount);\n\t if vCluster(nEvent) == 0\n\t \n\t fMagnitude(nEvent) = mCatalog(nEvent, 6);\n\t \n\t %% Define first aftershock zone and determine magnitude of strongest aftershock\n\t fMag = fMagnitude(nEvent);\n\t [fSpace, fTime] = calc_windows_gardKnop(fMagnitude(nEvent), nMethod);\n\t fSpaceDeg = km2deg(fSpace);\n\t \n\t %% This first if is for events with no location given\n\t if isnan(mCatalog(nEvent,1)) %Does this ever happen??? Maybe in a special study (DE)\n\t %Select what's on the same time??? (DE)\n\t vSel = (mCatalog(:,3) == mCatalog(nEvent,3));\n\t \n\t else \n\t \t%Select what is in range (DE)\n\t mPos = [mCatalog(nEvent, 1) mCatalog(nEvent,2)];\n\t mPos = repmat(mPos,length(mCatalog(:,1)), 1);\n\t mDist = abs(distance(mCatalog(:,1), mCatalog(:,2), mPos(:,1), mPos(:,2)));\n\t vSel = ((mDist <= fSpaceDeg) & (vDecDate(:,1)-vDecDate(nEvent,1) >= 0) &...\n\t (vDecDate(:,1)-vDecDate(nEvent,1) <= fTime) & vCluster(nEvent) == 0); \n\t \n\t end;% End of isnan(mCatalog)\n\t \n\t %maybe here and especially later is a change needed, because it might be expensive to find the \"positon\" \n\t %in th array later (DE)\n\t mTmp = mCatalog(vSel,:);\n\t \n\t if length(mTmp(:,1)) == 1 % Only one event thus no cluster; IF to determine cluster or not\n\t fMaxClusterMag = fMag;\n\t \n\t else\n\t fMaxClusterMag = max(mTmp(:,6));\n\t [nIndiceMaxMag] = find(mTmp(:,6) == fMaxClusterMag);\n\t fTimeMaxClusterMag = mTmp(max(nIndiceMaxMag),3);\n\t \n\t %can't stand while loops, try to eliminate it (DE) %probably just sort the whole catalog with magnitude\n\t %The while looks ugly but the time it uses is small\n\t % Search for event with bigger magnitude in cluster and add to cluster\n\t while fMaxClusterMag-fMag > 0\n\t [fSpace, fTime] = calc_windows_gardKnop(fMaxClusterMag, nMethod);\n\t fSpaceDeg = km2deg(fSpace);\n\t \n\t %% Adding aftershocks from bigger aftershock\n\t mPos = [mTmp(min(nIndiceMaxMag),1) mTmp(min(nIndiceMaxMag),2)];\n\t mPos = repmat(mPos,length(mCatalog(:,1)), 1);\n\t mDist = abs(distance(mCatalog(:,1), mCatalog(:,2), mPos(:,1), mPos(:,2)));\n\t vSel2 = ((mDist <= fSpaceDeg) & (vDecDate(:,1)-mTmp(min(nIndiceMaxMag),3) >= 0) &...\n\t (vDecDate(:,1)-mTmp(min(nIndiceMaxMag),3) <= fTime) & vCluster == 0);\n\t mTmp = mCatalog(vSel2,:);\n\t %vSel = (vSel > 0 | vSel2 > 0); % Actual addition %>0 not needed both are logical vectors (DE)\n\t vSel = vSel|vSel2;\n\t if isempty(mTmp) % no events in aftershock zone \n\t break;\n\t end;\n\t \n\t fMag = fMaxClusterMag;\n\t fMaxClusterMag = max(mTmp(:,6));\n\t [nIndiceMaxMag] = find(mTmp(:,6) == fMaxClusterMag);\n\t fTimeMaxClusterMag = mTmp(max(nIndiceMaxMag),3);\n\t \n\t if fMaxClusterMag - fMag == 0 % no bigger event in aftershock zone\n\t break;\n\t end;\n\t \n\t end; % End of while\n\t \n\t nCount = nCount + 1; % Set cluster number\n\t \n\t end; % End of if length(mTmp)\n\t\n\t [vIndice]=find(vSel); % Vector of indices with Clusters\n\t vTmpCluster(vIndice,:) = nCount;\n\t %length(vTmpCluster(vIndice,:));\n\t nI=1; % Variable counting the length of the cluster\n\t % Select the right numbers for the cluster using the indice vector vIndice\n\t % First: Insert cluster number after check for length\n\t % Second: Check if it's a mainshock\n\t % Third: Keep the former cluster indice;\n\t while nI <= length(vIndice)\n\t if (~isempty(vTmpCluster(vIndice(nI))) & length(vTmpCluster(vIndice,:)) > 1 & vCluster(vIndice(nI)) == 0)\n\t vCluster(vIndice(nI)) = vTmpCluster(vIndice(nI));\n\t %vEventnr(vIndice,:) = nEvent;\n\t elseif (~isempty(vTmpCluster(vIndice(nI))) & length(vTmpCluster(vIndice,:)) == 1 & vCluster(vIndice(nI)) == 0)\n\t vCluster(vIndice(nI)) = 0;\n\t else\n\t vCluster(vIndice(nI)) = vCluster(vIndice(nI));\n\t end;\n\t nI=nI+1;\n\t end; %End of while nI\n\t % nCount = nCount + 1; % Set cluster number %% Watch\n\t % end; % End of if to determine cluster or not %% Watch\n\t %%% Check if the Cluster is not just one event which can happen in case of keeping the former \n\t %%% cluster number in preceeding while-Loop\n\t vSelSingle = (vCluster == nCount);\n\t [vIndiceSingle] = find(vSelSingle);\n\t %vTmpSingle(vIndiceSingle,:);\n\t if length(vIndiceSingle) == 1\n\t %nCount\n\t %vIndiceSingle\n\t vCluster(vIndiceSingle)=0; % Set the event as mainsock\n\t nCount = nCount-1; % Correct the cluster number down by one\n\t end;\n\t\n\t end; % End of if checking if vCluster == 0 \n\t if rem(nEvent,100) == 0\n\t waitbar(nEvent/length(mCatalog(:,6)))\n\t end; % End updating waitbar\n\tend; % End of FOR over mCatalog \n\tclose(hWaitbar1);\n\t%nCount\n\t%% vCL Cluster vector with mainshocks in it; vCluster is now modified to get rid of mainshocks\n\tvCl = vCluster; \n\t\n\t%% Matrix with cluster indice, magnitude and time \n\tmTmpCat = [vCluster mCatalog(:,6) mCatalog(:,3)];\n\t%% Delete largest event from cluster series and add to mainshock catalog\n\thWaitbar2 = waitbar(0,'Identifying mainshocks in clusters...');\n\tset(hWaitbar2,'Numbertitle','off','Name','Mainshock identification ');\n\tfor nCevent = 1:nCount\n\t %nCevent\n\t vSel4 = (mTmpCat(:,1) == nCevent); % Select cluster \n\t mTmpCat2 = mCatalog(vSel4,:); \n\t fTmpMaxMag = max(mTmpCat2(:,6)); % Select max magnitude of cluster\n\t vSelMag = (mTmpCat2(:,6) == fTmpMaxMag);\n\t [nMag] = find(vSelMag);\n\t if length(nMag) == 1\n\t vSel5 = (mTmpCat(:,1) == nCevent & mTmpCat(:,2) == fTmpMaxMag); % Select the event\n\t [vIndiceMag] = find(vSel5); % Find indice \n\t vCluster(vIndiceMag) = 0; % Set cluster value to zero, so it is a mainshock\n\t vMainCluster(vIndiceMag) = nCevent; % Set mainshock vector to cluster number\n\t elseif length(nMag) == 0\n\t disp('Nothing in ')\n\t nCevent\n\t else\n\t vSel = (mTmpCat(:,1) == nCevent & mTmpCat(:,2) == fTmpMaxMag);\n\t mTmpCat3 = mCatalog(vSel,:);\n\t [vIndiceMag] = min(find(vSel)); % Find minimum indice of event with max magnitude in cluster\n\t vCluster(vIndiceMag) = 0; % Set cluster value to zero, so it is a mainshock\n\t vMainCluster(vIndiceMag) = nCevent; % Set mainshock vector to cluster number\n\t end;\n\t if rem(nCevent,20) == 0\n\t waitbar(nCevent/nCount)\n\t end; % End updating waitbar\n\tend; % End of For nCevent\n\tclose(hWaitbar2);\n\t%% Create a catalog of aftershocks (mCatAfter) and of declustered catalog (mCatDecluster)\n\tvSel = (vCluster(:,1) > 0);\n\t%mCatDecluster=mCatalog(~vSel,:);\n\t%mCatAfter = mCatalog(vSel,:);\n\t\n\t\n\t\n\t%create the wanted output for mapseis\n\t%clusterID,EventType,AlgoInfo\n\tEventType = categorical(ones(length(mCatalog,1)),...\n\t\t[0 1 2 3],...\n\t\t{'unclassified','single event','mainshock','aftershock'}); \n\tclusterID=vCl;\n\t\n\t%the type first\n\tEventType(vCl~=0)='mainshock';\n\tEventType(vCluster~=0)='aftershock';\n\tclusterID(clusterID==0)=NaN;\n\t\n\t%The original does not set a mainshock if all earhquakes in a cluster have the same Magnitude, this part will \n\t%if SetMain is set to true choose the first eq as mainshock, which is as the catalog should be sorted by time\n\t%the first in the list\n\t%Also does the original code determine the length of the clusters, this here will do it\n\tuniqueClust=unique(clusterID(~isnan(clusterID)));\n\tClusterLength=zeros(numel(uniqueClust),1);\n\tif SetMain\n\t\tfor i=1:numel(ClusterLength);\n\t\t\tClusterLength(i)=sum(clusterID==uniqueClust(i));\n\t\t\t\n\t\t\tif all(EventType(clusterID==uniqueClust(i))=='aftershock')\n\t\t\t\tTheInder=find(clusterID==uniqueClust(i));\n\t\t\t\tEventType(TheInder(1))='mainshock';\n\t\t\tend\n\t\tend\n\t\t\n\telse\n\t\tfor i=1:numel(ClusterLength);\n\t\t\tClusterLength(i)=sum(clusterID==uniqueClust(i));\n\t\tend\n\n\t\n\tend\n\t\t\n\tCalcParameter.Method=nMethod;\n\tCalcParameter.SetMain=SetMain;\t\n\t\n\tAlgoInfo.Type='Gardner-Knopoff-mapseis-v1';\n\tAlgoInfo.UsedConfig=CalcParameter;\n\tAlgoInfo.CalculationDate=date;\n\tAlgoInfo.ClusterLengths=ClusterLength;\n\tAlgoInfo.largest_Eq=[];\n\t\t\nend\t\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/+declustering/calc_decluster_gardKnop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3892375693540293}}
{"text": "function [gp, diagnosis] = svigp(gp, x, y, varargin)\n%SVIGP Stochastic variational inference for GP\n%\n% Description\n% GP = SVIGP(GP, X, Y, OPTIONS) optimises the variational, likelihood\n% and covariance function parameters of a sparse SVI GP model\n% given matrix X of training inputs and vector Y of training targets.\n% The model follows the description in Hensman, Fusi and Lawrence\n% (2013). Supported likelihood functions are gaussian (for regression)\n% and probit (for classification).\n%\n% [GP, DIAGNOSIS] = SVIGP(GP, X, Y, OPTIONS) also returns values\n% monitored during the iteration. The structure DIAGNOSIS contains\n% the energy in the field e, the likelihood and covariance function\n% parameters in the field w, and the mean log predictive density (if xt\n% and yt is provided) in the field mlpd. The first dimension corresponds\n% to the main iteration in all these arrays. The second dimension\n% corresponds to the minibatch iteration in e and w. The third dimension\n% corresponds to the different parameters in w.\n%\n% OPTIONS is optional parameter-value pair\n% xt - test inputs. Used for monitoring the mean log\n% predictive density, N.B. the monitoring needs\n% both xt and yt.\n% yt - observed yt in test points. Used for monitoring\n% the mean log predictive density, N.B. the\n% monitoring needs both xt and yt.\n% z - optional observed quantity in triplet\n% (x_i,y_i,z_i) Some likelihoods may use this. For\n% example, in case of Poisson likelihood we have\n% z_i=E_i, that is, expected value for ith case.\n% zt - optional observed quantity in triplet\n% (xt_i,yt_i,zt_i) Some likelihoods may use this.\n% For example, in case of Poisson likelihood we\n% have z_i=E_i, that is, the expected value for the\n% ith case. N.B. used only in the monitoring of the\n% mean log predictive density.\n% X_u - inducing inputs. If omitted, kmeans clustering is\n% applied and the resulting cluster centroids are\n% selected. The number of inducing variables is\n% then controlled by the parameter nu (see below).\n% nu - the number of inducing variables if X_u is\n% omitted. Can be given as an absolute value or\n% relative to the input size. The default is\n% min(floor(0.1*n),1500), where n is the number\n% of training inputs.\n% m - initial mean of the inducing variables. The\n% default is zero vector.\n% S - initial covariance of the inducing variables. The\n% default is 0.1 times identity matrix.\n% n_minibatch - absolute or relative size of the minibatches\n% (relative to the number of the training inputs).\n% Does not have to be divisible with the number of\n% training inputs. The default is 0.1 (relative).\n% maxiter - the maximum number of iterations (default 5000).\n% Providing 0 initialises the gp structure\n% parameters without optimisation.\n% momentum - momentum term for the covariance function\n% parameters (default 0.9)\n% mu1 - initial step size of the variational parameters\n% (default 0.01).\n% mu2 - initial step size of the likelihood and\n% covariance function parameters (default 1e-5)\n% tol - tolerance of energy for the convergence\n% (default 1e-6).\n% step_size - function handle for the step size as a function\n% of the iteration. The default function is f(i) =\n% 1/(1+i/n_minibatch), where n_minibatch is the\n% size of the minibatches.\n% lik_sigma2 - likelihood variance in the case of non-gaussian\n% likelihood (default 0.1).\n% lik_sigma2_prior - prior for the likelihood variance in the case of\n% non-gaussian likelihood. The default is \n% prior_loggaussian('mu',-2, 's2', 0.5).\n% display - Control the amount of diagnostic verbosity.\n% 'off' displays nothing, 'final' display the\n% final output, and 'iter' displays output at\n% each iteration. Alternatively by providing a\n% scalar value, fewer iterations can be displayed,\n% e.g. value 10 displays only every tenth\n% value (default behaviour).\n%\n% See also\n% GP_SET, GPSVI_PRED, GPSVI_PREDGRAD, GPSVI_E, GPSVI_G, DEMO_SVI*\n%\n% References:\n% Hensman, J., Fusi, N. and Lawrence, N. D. (2013). Gaussian processes\n% for big data. arXiv preprint arXiv:1309.6835.\n\n% Copyright (c) 2014 Ville Tolvanen\n% Copyright (c) 2014 Tuomas Sivula\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n\nip=inputParser;\nip.FunctionName = 'SVIGP';\nip.addRequired('gp',@isstruct);\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('xt', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('yt', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('z', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('zt', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('X_u', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('nu', [], @(x) isreal(x) && isscalar(x) && x > 0)\nip.addParamValue('m', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('S', [], @(x) isnumeric(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('n_minibatch', 0.1, @(x) isreal(x) && isscalar(x) && x > 0)\nip.addParamValue('maxiter', 2000, @(x) isreal(x) && isscalar(x) && x >= 0)\nip.addParamValue('momentum', 0.9, @(x) isreal(x) && isscalar(x) && x > 0)\nip.addParamValue('mu1', 0.01, @(x) isreal(x) && isscalar(x) && x > 0)\nip.addParamValue('mu2', 1e-5, @(x) isreal(x) && isscalar(x) && x > 0)\nip.addParamValue('tol', 1e-6, @(x) isreal(x) && isscalar(x))\nip.addParamValue('step_size', [], @(x) isa(x,'function_handle'))\nip.addParamValue('lik_sigma2',0.1, @(x) isscalar(x) && x>=0);\nip.addParamValue('lik_sigma2_prior',prior_loggaussian('mu',-2, 's2', 0.5), ...\n @(x) isstruct(x) || isempty(x));\nip.addParamValue('display', 10, @(x) ismember(x,{'final','iter','off'}) ...\n || (isreal(x) && isscalar(x) && x > 1) )\n\nip.parse(gp, x,y,varargin{:});\nx=ip.Results.x;\ny=ip.Results.y;\nz=ip.Results.z;\nxt=ip.Results.xt;\nyt=ip.Results.yt;\nzt=ip.Results.zt;\nX_u=ip.Results.X_u;\nnu=ip.Results.nu;\nm=ip.Results.m;\nS=ip.Results.S;\nn_minibatch=ip.Results.n_minibatch;\nmomentum=ip.Results.momentum;\nmu1=ip.Results.mu1;\nmu2=ip.Results.mu2;\nstep_size=ip.Results.step_size;\nmaxiter=ip.Results.maxiter;\ntol=ip.Results.tol;\nlik_sigma2 = ip.Results.lik_sigma2;\nlik_sigma2_prior = ip.Results.lik_sigma2_prior;\ndisplay = ip.Results.display;\n\n% Initialise the diagnosis output structure\ndiagnosis = struct();\n\n% Check if latent method SVI has been set\nif ~isfield(gp, 'latent_method') || ~isequal(gp.latent_method, 'SVI')\n gp=gp_set(gp, 'latent_method', 'SVI');\nend\n\n% Check if latent method is not gaussian or probit\nif ~strcmp(gp.lik.type, 'Gaussian') && ~strcmp(gp.lik.type, 'Probit')\n error('Supported likelihoods for SVIGP are gaussian and probit.')\nend\n\n% Process parameters\nif xor(isempty(xt), isempty(yt))\n warning('Need both xt and yt for monitoring mean log predictive density.');\nend\nn=size(x,1);\n\nif n_minibatch < 1\n n_minibatch = max(floor(n_minibatch*n),1);\nend\nif n_minibatch > n\n n_minibatch = max(floor(0.1*n),1);\n warning('Too many minibatches, using floor(0.1*n) = %d instead.', ...\n n_minibatch)\nend\n\nif isempty(step_size)\n step_size=@(iter) 1/(1+iter./n_minibatch);\nend\n\n% Handle the inducing inputs\nif ~ismember('X_u',ip.UsingDefaults)\n gp.X_u = X_u;\nend\nif isempty(gp.X_u)\n % Assign X_u by clustering\n if isempty(nu)\n nu = min(max(floor(0.1.*n),1),1500);\n elseif nu < 1\n nu = max(floor(nu.*n),1);\n end\n fprintf('Assign inducing inputs by clustering\\n')\n Sw=warning('off','stats:kmeans:EmptyCluster');\n [~,X_u] = kmeans(x, nu,'Start','uniform',...\n 'EmptyAction','singleton');\n warning(Sw);\n gp.X_u = X_u;\nend\ngp.nind = size(gp.X_u,1);\n\n% Handle the rest of the parameters\nif ~ismember('m',ip.UsingDefaults)\n if length(m) == gp.nind\n gp.m = m;\n else\n error('The size of m does not match with X_u')\n end\nelseif ~isfield(gp, 'm') || length(gp.m) ~= gp.nind\n gp.m = zeros(gp.nind,1);\nend\n\nif ~ismember('S',ip.UsingDefaults)\n if ismatrix(S) && all(size(S) == gp.nind)\n gp.S = S;\n else\n error('The size of S does not match with X_u')\n end\nelseif ~isfield(gp, 'S') || any(size(gp.S) ~= gp.nind)\n gp.S = 0.1*eye(gp.nind);\n % gp.S = gp_trcov(gp,gp.X_u);\nend\ngp.t1=gp.S\\gp.m;\ngp.t2=-0.5.*inv(gp.S);\n\n% Handle the likelihood variance\nif ~isfield(gp.lik, 'sigma2')\n gp.lik.sigma2 = lik_sigma2;\n gp.lik.p.sigma2 = lik_sigma2_prior;\n gp.lik.fh.lp = @lik_lp;\n gp.lik.fh.lpg = @lik_lpg;\nend\n\n% Return prematurely if only initialising\nif maxiter == 0\n return\nend\n\n% Parameters\nw = gp_pak(gp);\nw0 =w;\nnh1 = numel(gp.t1) + numel(gp.t2);\nnh2 = length(w)-nh1;\n\n% Initial step-size vector\nmu0 = mu1.*ones(size(w));\nmu0(end-nh2+1:end)=mu2;\n\n% Size of minibatches\nnb=n_minibatch;\n% Number of minibatches\nnbb=ceil(n/nb);\n\n% Monitored values\nif nargout > 1\n e_all = zeros(maxiter,nbb);\n w_all = zeros(maxiter,nbb,nh2);\n if ~isempty(xt) && ~isempty(yt)\n mlpd_all = zeros(maxiter,1);\n rmse_all = zeros(maxiter,1);\n end\nend\ng_old=zeros(size(w));\nmomentum=momentum.*ones(size(w));\netot_old=Inf;\n\n% Preprocess conditions for iteration\ndisp_iter = strcmp(display, 'iter');\ndisp_i = 0;\ndisp_count = display;\n\n% Iterate until convergence or maxiter\nconverged = 0;\ntry_fix_mu2 = 0;\nfor iter = 1:maxiter\n \n % Divide the data into minibatches\n inds = cell(nbb,1);\n ind = randperm(n);\n for i=1:nbb-1\n inds{i} = ind((i-1)*nb+1:i*nb);\n end\n inds{nbb} = ind((nbb-1)*nb+1:end);\n \n % Compute the step-size\n mu = mu0.*step_size(iter);\n \n % Iterate all the minibatches\n etot = 0;\n broken = 0;\n for i=1:nbb\n if isempty(z)\n zi = [];\n else\n zi = z(inds{i},:);\n end\n gp.data_prop=length(inds{i})./n;\n [e,~,~,param] = gpsvi_e(w,gp,x(inds{i},:),y(inds{i},:), 'z', zi);\n etot = etot+e;\n g = gpsvi_g(w,gp,x(inds{i},:),y(inds{i},:), 'z', zi, ...\n 'gpsvi_e_param', param);\n g = mu.*g + momentum.*g_old;\n g_old = g;\n w = w+g;\n if nargout > 1\n e_all(iter,i) = e;\n w_all(iter,i,:) = w(end-nh2+1:end);\n end\n if ~isnan(etot) ...\n && all(~isinf(exp(w(end-nh2+1:end)))) ...\n && all(exp(w(end-nh2+1:end))~=0) ...\n && ~any(isnan(g)) ...\n && ~isnan(gpsvi_e(w+g,gp,x(inds{i},:),y(inds{i},:), 'z', zi))\n gp = gp_unpak(gp,w);\n elseif ~try_fix_mu2\n fprintf('Bad parameter values, decreasing mu2.\\n');\n try_fix_mu2 = 1;\n mu2 = 0.1*mu2;\n mu0(end-nh2+1:end)=mu2;\n w = w0;\n g_old = zeros(1,nh1+nh2);\n broken = 1;\n break\n else\n fprintf('Bad parameter values, decreasing step-size and momentum.\\n');\n mu0 = 0.1.*mu0;\n momentum = 0.5*momentum;\n w = w0;\n g_old = zeros(1,nh1+nh2);\n broken = 1;\n break\n end\n gpsvi_e('clearcache',gp);\n end\n if broken\n continue\n end\n etot=etot/nbb;\n \n % Analyse and print\n if isscalar(display)\n if disp_count == display\n disp_i = 1;\n disp_count = 1;\n else\n disp_i = 0;\n disp_count = disp_count +1;\n end\n end\n if ~isempty(xt) && ~isempty(yt) ...\n && ( disp_iter || nargout > 1 || disp_i)\n [Eft,~,lpyt] = gpsvi_pred(gp,x,y,xt,'yt',yt, 'z', zi, 'zt', zt);\n lpyt = mean(lpyt);\n if nargout > 1\n mlpd_all(iter) = lpyt;\n rmse = sqrt(mean((yt-Eft).^2));\n rmse_all(iter) = rmse;\n end\n if disp_iter || disp_i\n fprintf('iter=%d/%d, e=%.3f, mlpd=%.4g, rmse=%.4g, de=%.5g\\n', ...\n iter, maxiter, etot, lpyt, rmse, abs(etot-etot_old));\n end\n elseif disp_iter || disp_i\n fprintf('iter=%d/%d, e=%.3f, de=%.5g\\n', ...\n iter, maxiter, etot, abs(etot-etot_old));\n end\n \n % Check for convergence\n if abs(etot-etot_old) 1 || disp_i)\n fprintf(['Final values:\\n' ...\n 'e=%.3f, mlpd=%.4g, rmse=%.4g\\n'], etot, lpyt, rmse);\n elseif ~isempty(xt) && ~isempty(yt)\n [Eft,~,lpyt] = gpsvi_pred(gp,x,y,xt,'yt',yt, 'z', z, 'zt', zt);\n fprintf(['Final values:\\n' ...\n 'e=%.3f, mlpd=%.4g, rmse=%.4g\\n'], ...\n etot, mean(lpyt)), sqrt(mean((yt-Eft).^2));\n else\n fprintf('Final energy: %.3f\\n', etot);\n end\nend\n\n% Save the monitored values\nif nargout > 1\n diagnosis.e = e_all(1:iter,:);\n diagnosis.w = w_all(1:iter,:,:);\n if ~isempty(xt) && ~isempty(yt)\n diagnosis.mlpd = mlpd_all(1:iter);\n diagnosis.rmse = rmse_all(1:iter);\n end\nend\n\nend\n\n\nfunction lp = lik_lp(lik, varargin)\n%LIK_LP log(prior) of the likelihood parameters\n%\n% Description\n% LP = LIK_LP(LIK) takes a likelihood structure LIK and\n% returns log(p(th)), where th collects the parameters. This\n% subfunction is needed if there are likelihood parameters.\n% Added for non-gaussian likelihoods in SVIGP.\n%\n% See also\n% LIK_*, SVIGP\n\n\n% If prior for sigma2sion parameter, add its contribution\nlp=0;\nif ~isempty(lik.p.sigma2)\n lp = lik.p.sigma2.fh.lp(lik.sigma2, lik.p.sigma2) +log(lik.sigma2);\nend\nend\n\n\nfunction lpg = lik_lpg(lik)\n%LIK_LPG d log(prior)/dth of the likelihood parameters\n%\n% Description\n% E = LIK_NEGBIN_LPG(LIK) takes a likelihood structure LIK and\n% returns d log(p(th))/dth, where th collects the parameters.\n% This subfunction is needed if there are likelihood parameters.\n% Added for non-gaussian likelihoods in SVIGP.\n%\n% See also\n% LIK_*, SVIGP\n\nlpg=[];\nif ~isempty(lik.p.sigma2)\n % Evaluate the gprior with respect to sigma2\n ggs = lik.p.sigma2.fh.lpg(lik.sigma2, lik.p.sigma2);\n lpg = ggs(1).*lik.sigma2 + 1;\n if length(ggs) > 1\n lpg = [lpg ggs(2:end)];\n end\nend\nend\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/svigp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3891667850349823}}
{"text": "function [a,n,r,epe,eph,epw,usol_c,vsol_c] = mg_ns_q1cd(xy,ev,flowsol,domain,lncoarse,lnfine,outbnd)\n%mg_ns_q1cd convection-diffusion matrix generator for GMG (Navier-Stokes)\n% [a,n,r,epe,eph,epw,usol_c,vsol_c] = mg_ns_q1cd(xy,ev,flowsol,domain,lncoarse,lnfine,outbnd) \n% input\n% xy vertex coordinate vector \n% ev element mapping matrix\n% flowsol current velocity field\n% domain domain parameter, 1 for square, 3 for step\n% lncoarse coarse grid index, log2(nc) for nc x nc square grid\n% lnfine finest grid index, log2(nf) for nf x nf square grid\n% outbnd location of outflow boundary\n% output \n% a discrete diffusion operator\n% n discrete convection operator\n% r mass matrix\n% epe viscosity normalised element peclet numbers \n% eph flow specific element lengths \n% epw centroid evaluated wind \n% usol_c first convection coefficient on coarse grid nodes\n% vsol_c second convection coefficient on coarse grid nodes \n%\n% IFISS function: HCE; 18 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\n\n% Modification of DJS routine mg_q1cd to allow convection coefficients to \n% be passed via flowsol. Analogous to femq1_cd.\n\n% Square domain\nif domain==1, \n% Size of fine grid, obtained from underlying flow solution flowsol\n nfine = length(flowsol)/2;\n nf = sqrt(nfine);\n x=xy(:,1); y=xy(:,2);\n nvtx=length(x); nel=length(ev(:,1));\n\n% Get flow values at coarse grid points\n lshift = lnfine - lncoarse;\n usol=flowsol(1:nfine); \n usol_grid = reshape(usol,nf,nf);\n usol_grid_c = usol_grid(1:2^lshift:nf,1:2^lshift:nf);\n usol_c = reshape(usol_grid_c,nvtx,1);\n vsol=flowsol(nfine+1:2*nfine); \n vsol_grid = reshape(vsol,nf,nf);\n vsol_grid_c = vsol_grid(1:2^lshift:nf,1:2^lshift:nf);\n vsol_c = reshape(vsol_grid_c,nvtx,1);\n\n% Step domain\nelseif domain==3,\n% Various counts of fine/coarse points in small part (1) and large part (2) of step\n% Logic borrowed from AR routine step_mg_prolong\n nelf = 2^lnfine;\n nfine = (((outbnd+1)/2)*nelf+1)*(nelf+1) - (nelf/2)^2;\n nelc = 2^lncoarse;\n ncoarse = (((outbnd+1)/2)*nelc+1)*(nelc+1) - (nelc/2)^2;\n nfh1 = (nelf/2); nfv1 = (nelf/2+1); nf1 = nfh1*nfv1;\n nfh2 = (outbnd*nelf/2+1); nfv2 = nelf+1; nf2 = nfh2*nfv2;\n nch1 = (nelc/2); ncv1 = (nelc/2+1); nc1 = nch1*ncv1;\n nch2 = (outbnd*nelc/2+1); ncv2 = nelc+1; nc2 = nch2*ncv2;\n\n% Get flow values at coarse grid points\n lshift = lnfine-lncoarse;\n usol=flowsol(1:nfine);\n usol1_grid = reshape(usol(1:nf1),nfh1,nfv1);\n usol1_grid_c = usol1_grid(1:2^lshift:nfh1,1:2^lshift:nfv1);\n usol1_c = reshape(usol1_grid_c,nc1,1);\n usol2_grid = reshape(usol(nf1+1:nfine),nfh2,nfv2);\n usol2_grid_c = usol2_grid(1:2^lshift:nfh2,1:2^lshift:nfv2);\n usol2_c = reshape(usol2_grid_c,nc2,1);\n usol_c = [usol1_c;usol2_c];\n vsol=flowsol(nfine+1:2*nfine);\n vsol1_grid = reshape(vsol(1:nf1),nfh1,nfv1);\n vsol1_grid_c = vsol1_grid(1:2^lshift:nfh1,1:2^lshift:nfv1);\n vsol1_c = reshape(vsol1_grid_c,nc1,1);\n vsol2_grid = reshape(vsol(nf1+1:nfine),nfh2,nfv2);\n vsol2_grid_c = vsol2_grid(1:2^lshift:nfh2,1:2^lshift:nfv2);\n vsol2_c = reshape(vsol2_grid_c,nc2,1);\n vsol_c = [vsol1_c;vsol2_c];\nend\n\n%\nx=xy(:,1); y=xy(:,2);\nnvtx=length(x);\nnel=length(ev(:,1));\nlx=max(x)-min(x); ly=max(y)-min(y);\nhx=max(diff(x)); hy=max(diff(y));\n%\n% Initialise global matrices\na = sparse(nvtx,nvtx);\nn = sparse(nvtx,nvtx);\nr = sparse(nvtx,nvtx);\n%\n% Set up 2x2 Gauss points\ngpt=1.0e0/sqrt(3.0e0);\ns(1) = -gpt; t(1) = -gpt; wt(1) = 1;\ns(2) = gpt; t(2) = -gpt; wt(2) = 1;\ns(3) = gpt; t(3) = gpt; wt(3) = 1;\ns(4) = -gpt; t(4) = gpt; wt(4) = 1;\n\n%\n% Inner loop over elements \nfor ivtx = 1:4\n xl_v(:,ivtx) = x(ev(:,ivtx));\n yl_v(:,ivtx) = y(ev(:,ivtx)); \n xsl(:,ivtx) = usol_c(ev(:,ivtx));\n ysl(:,ivtx) = vsol_c(ev(:,ivtx));\nend\nae = zeros(nel,4,4);\nne = zeros(nel,4,4);\nre = zeros(nel,4,4);\n% Loop over 2x2 Gauss points\nfor igpt = 1:4\n sigpt=s(igpt);\n tigpt=t(igpt);\n wght=wt(igpt);\n% Evaluate derivatives etc\n [jac,invjac,phi,dphidx,dphidy] = deriv(sigpt,tigpt,xl_v,yl_v);\n u_x = zeros(nel,1); u_y=zeros(nel,1);\n for k=1:4\n u_x(:) = u_x(:) + xsl(:,k) .* phi(:,k);\n u_y(:) = u_y(:) + ysl(:,k) .* phi(:,k);\t \n end \n for j = 1:4\n for i = 1:4\n ae(:,i,j) = ae(:,i,j) + dphidx(:,i).*dphidx(:,j) .* invjac(:);\n ae(:,i,j) = ae(:,i,j) + dphidy(:,i).*dphidy(:,j) .* invjac(:);\n re(:,i,j) = re(:,i,j) + phi(:,i).*phi(:,j) .* jac(:);\n%%% ne(:,i,j) = ne(:,i,j) + flowx(:) .* phi(:,i) .* dphidx(:,j);\n%%% ne(:,i,j) = ne(:,i,j) + flowy(:) .* phi(:,i) .* dphidy(:,j);\n ne(:,i,j) = ne(:,i,j) + wght*u_x(:).*phi(:,i).*dphidx(:,j);\n ne(:,i,j) = ne(:,i,j) + wght*u_y(:).*phi(:,i).*dphidy(:,j);\n end\n\tend\n% End of Gauss point loop\nend\n%\n% Perform assembly of global matrix and source vector \nfor krow=1:4\n nrow=ev(:,krow);\t \n for kcol=1:4\n ncol=ev(:,kcol);\t \n a = a + sparse(nrow,ncol,ae(:,krow,kcol),nvtx,nvtx);\n r = r + sparse(nrow,ncol,re(:,krow,kcol),nvtx,nvtx);\n n = n + sparse(nrow,ncol,ne(:,krow,kcol),nvtx,nvtx);\n end\nend\n%\n% Computation of element Peclet number (at the centroid) \n% Rectangle specific calculation here\nhx=abs(xl_v(:,2)-xl_v(:,1)); hy=abs(yl_v(:,3)-yl_v(:,2));\n[jac,invjac,phi,dphidx,dphidy] = deriv(0,0,xl_v,yl_v);\nu_x = zeros(nel,1); u_y=zeros(nel,1);\nfor k=1:4\n u_x(:) = u_x(:) + xsl(:,k) .* phi(:,k);\n u_y(:) = u_y(:) + ysl(:,k) .* phi(:,k);\t \nend \nflowx = u_x(:); flowy = u_y(:);\nflow_l2 = sqrt(flowx(:) .* flowx(:) + flowy(:) .* flowy(:));\nif all(flowx==0), flow_h=hy;\nelseif all(flowy==0), flow_h=hx;\nelse\n angle = atan(abs(flowy./flowx));\n flow_h = min([hx./cos(angle),hy./sin(angle)],[],2);\nend\neph = flow_h;\nepe = flow_h.*flow_l2/2;\nepw = flow_l2;\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/solvers/mg_ns_q1cd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.38898926434105313}}
{"text": "function [Ef, Varf, xtnn, xt1, xt2] = gp_cpred(gp,x,y,xt,ind,varargin)\n%GP_CPRED Conditional predictions using specific covariates\n%\n% Description\n% GP_CPRED(GP,X,Y,XT,IND,OPTIONS) does predictions using only\n% covariates specified in vector IND. Other covariates are fixed to\n% either mean, median or values chosen by user. Returns predictions for\n% latent values, variance and corresponding inputs. If IND=0, only time\n% is used as a covariate for Cox-PH model.\n%\n% OPTIONS is optional parameter-value pair\n% method - which value to fix the not used covariates, 'median'\n% (default), 'mean' or 'mode'\n% var - vector specifying optional values for not used covariates,\n% elements corresponding to mean/median values should \n% be set to NaN. \n% plot - option for plotting, 'off' (default) or 'on'\n% normdata - a structure with fields xmean, xstd, ymean, and ystd\n% to allow plotting in the original data scale (see\n% functions normdata and denormdata)\n% target - option for choosing what is computed 'mu' (default),\n% 'f' or 'cdf'\n% tr - Euclidean distance treshold for not using grid points when\n% doing predictions with 2 covariates, default 0.25\n% predcf - an index vector telling which covariance functions are \n% used for prediction. Default is all (1:gpcfn). \n% See additional information below.\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, expected value \n% for ith case. \n% zt - optional observed quantity in triplet (xt_i,yt_i,zt_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, the expected \n% value for the ith case. \n\n\nip=inputParser;\nip.FunctionName = 'GP_CPRED';\nip.addRequired('gp',@(x) isstruct(x) || iscell(x));\nip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addRequired('xt', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\nip.addParamValue('yt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('zt', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addRequired('ind', @(x) ~isempty(x) && isvector(x))\nip.addParamValue('var', [], @(x) isreal(x))\nip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('predcf', [], @(x) isempty(x) || ...\n isvector(x) && isreal(x) && all(isfinite(x)&x>0))\nip.addParamValue('tstind', [], @(x) isempty(x) || iscell(x) ||...\n (isvector(x) && isreal(x) && all(isfinite(x)&x>0)))\nip.addParamValue('method', 'median', @(x) ismember(x, {'median', 'mean' 'mode'}))\nip.addParamValue('plot', 'off', @(x) ismember(x, {'on', 'off'}))\nip.addParamValue('tr', 0.25, @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('target', 'mu', @(x) ismember(x,{'f','mu','cdf'}))\nip.addParamValue('prct', [5 50 95], @(x) isreal(x) && all(isfinite(x(:))))\nip.addParamValue('normdata', struct(), @(x) isempty(x) || isstruct(x))\nip.addParamValue('xlabels', [], @(x) isempty(x) || iscell(x));\nip.parse(gp, x, y, xt, ind, varargin{:});\nzt=ip.Results.zt;\noptions=struct();\noptions.predcf=ip.Results.predcf;\noptions.prct=ip.Results.prct;\noptions.tstind=ip.Results.tstind;\nmethod = ip.Results.method;\nvars = ip.Results.var;\nplot_results = ip.Results.plot;\ntr = ip.Results.tr;\ntarget = ip.Results.target;\nif strcmp(target,'f')\n options = rmfield(options,'prct');\nend\nyt=ip.Results.yt;\nif ~isempty(yt)\n options.yt=yt;\nend\nz=ip.Results.z;\nif ~isempty(z)\n options.z=z;\nend\nif ~isempty(zt)\n options.zt=zt;\nend\nif isempty(zt)\n options.zt=z;\nend\n% normdata\nnd=ip.Results.normdata;\nipnd=inputParser;\nipnd.FunctionName = 'normdata';\nipnd.addParamValue('xmean',zeros(1,size(x,2)),@(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))));\nipnd.addParamValue('xstd',ones(1,size(x,2)),@(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))));\nipnd.addParamValue('xlog',zeros(1,size(x,2)),@(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))));\nipnd.addParamValue('ymean',0,@(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))));\nipnd.addParamValue('ystd',1,@(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))));\nipnd.addParamValue('ylog',0,@(x) isempty(x) || (isreal(x) && all(isfinite(x(:)))));\nipnd.parse(nd);\nnd=ipnd.Results;\n\n[tmp, nin] = size(x);\n\nif iscell(gp)\n liktype=gp{1}.lik.type;\nelse\n liktype=gp.lik.type;\nend\n\nif isequal(liktype, 'Coxph') && isequal(target,'mu')\n target='f';\n warning('GP_CPRED: Target ''mu'' not applicable for a Cox-PH model. Switching to target ''f''')\nend\n\nif ~isempty(vars) && (~isvector(vars) || length(vars) ~= nin)\n error('Vector defining fixed variable values must be same length as number of covariates')\nend\n\nxto=xt; [n,tmp]=size(xto);\n\nif length(ind)==1\n \n if ind~=0\n [xtnn, iu] = unique(xt(:,ind));\n else\n xtnn = xt(1,:);\n iu = 1;\n end\n if ~isempty(z)\n options.zt = options.zt(iu);\n end\n if ~isempty(yt)\n options.yt = options.yt(iu);\n end\n xt = repmat(feval(method,xt), size(xtnn,1), 1);\n if ~isempty(vars)\n xt(:,~isnan(vars)) = repmat(vars(~isnan(vars)), length(xtnn), 1);\n end\n \n if ind>0\n xt(:,ind) = xtnn;\n end\n if ~strcmp(liktype, 'Coxph')\n switch target\n case 'f'\n [Ef, Varf] = gp_pred(gp, x, y, xt, options);\n case 'mu'\n prctmu = denormdata(gp_predprctmu(gp, x, y, xt, options),nd.ymean,nd.ystd);\n Ef = prctmu; Varf = [];\n case 'cdf'\n cdf = gp_predcdf(gp, x, y, xt, options);\n Ef = cdf; Varf = [];\n end\n else\n [Ef1,Ef2,Covf] = pred_coxph(gp,x,y,xt,'z',options.z,'zt',options.zt);\n nt=size(Ef1,1);\n if ind>0\n % conditional posterior given Ef1=E[Ef1]\n Ef = Ef2; \n Varf = diag(Covf(nt+1:end,nt+1:end)-Covf(nt+1:end,1:nt)*(Covf(1:nt,1:nt)\\Covf(1:nt,nt+1:end)));\n else\n % conditional posterior given Ef2=E[Ef2]\n Ef = Ef1; \n Varf = diag(Covf(1:nt, 1:nt)-Covf(1:nt,nt+1:end)*(Covf(nt+1:end,nt+1:end)\\Covf(nt+1:end,1:nt)));\n xtnn = gp.lik.xtime;\n end\n end\n if isequal(plot_results, 'on')\n if ind>0\n if ind>=1&numel(nd.xmean)>=ind\n xtnn=denormdata(xtnn,nd.xmean(ind),nd.xstd(ind));\n end\n deltadist=gp_finddeltadist(gp);\n if ~ismember(ind,deltadist)\n switch target\n case 'f'\n plot(xtnn, Ef, 'ob', xtnn, Ef, '-k', xtnn, Ef-1.64*sqrt(Varf), '--b', xtnn, Ef+1.64*sqrt(Varf), '--b')\n case 'mu'\n plot(xtnn, prctmu(:,2), 'ob', xtnn, prctmu(:,2), '-k', xtnn, prctmu(:,1), '--b', xtnn, prctmu(:,3), '--b')\n case 'cdf'\n plot(xtnn, Ef, 'o-b')\n end\n else\n switch target\n case 'f'\n plot(xtnn, Ef, 'ob', [xtnn xtnn]',[Ef-1.64*sqrt(Varf) Ef+1.64*sqrt(Varf)]', '-b')\n xlim([1.5*xtnn(1)-0.5*xtnn(2) 1.5*xtnn(end)-.5*xtnn(end-1)])\n set(gca,'xtick',xtnn)\n case 'mu'\n plot(xtnn, prctmu(:,2), 'ob', [xtnn xtnn]',[prctmu(:,1) prctmu(:,3)]', '-b')\n xlim([1.5*xtnn(1)-0.5*xtnn(2) 1.5*xtnn(end)-.5*xtnn(end-1)])\n set(gca,'xtick',xtnn)\n case 'cdf'\n plot(xtnn, Ef, 'ob')\n end\n end\n else\n % use stairs for piecewise constant baseline hazard\n xtnn = gp.lik.stime;\n [xx,yy]=stairs(xtnn, [Ef;Ef(end)]);\n [xx,yyl]=stairs(xtnn, [Ef-1.64*sqrt(Varf);Ef(end)-1.64*sqrt(Varf(end))]);\n [xx,yyu]=stairs(xtnn, [Ef+1.64*sqrt(Varf);Ef(end)+1.64*sqrt(Varf(end))]);\n plot(xx, yy, '-k', xx, yyl, '--b', xx, yyu, '--b')\n end\n end\n \nelseif length(ind)==2\n \n uu1=unique(xt(:,ind(1)));\n uu2=unique(xt(:,ind(2)));\n nu1=numel(uu1);\n nu2=numel(uu2);\n if nu1==2 || nu2==2\n % First or second covariate binary\n \n if nu1>2 && nu2==2\n % switch indeces, so that binary covariate is first\n tmp=ind(1);ind(1)=ind(2);ind(2)=tmp;\n tmp=uu1;uu1=uu2;uu2=tmp;\n end\n \n xt1=xt(xt(:,ind(1))==uu1(1),:);\n xt2=xt(xt(:,ind(1))==uu1(2),:);\n [xtnn1, iu1] = unique(xt1(:,ind(2)));\n [xtnn2, iu2] = unique(xt2(:,ind(2)));\n \n options1=options;\n options2=options;\n if ~isempty(z)\n options1.zt = options.zt(iu1);\n options2.zt = options.zt(iu2);\n end\n\n xt1 = repmat(feval(method,xt1), length(xtnn1), 1);\n xt2 = repmat(feval(method,xt2), length(xtnn2), 1);\n if ~isempty(vars)\n xt1(:,~isnan(vars)) = repmat(vars(~isnan(vars)), length(xtnn1), 1);\n xt2(:,~isnan(vars)) = repmat(vars(~isnan(vars)), length(xtnn2), 1);\n end\n xt1(:,ind(1)) = uu1(1); xt1(:,ind(2)) = xtnn1;\n xt2(:,ind(1)) = uu1(2); xt2(:,ind(2)) = xtnn2;\n \n if ~strcmp(liktype, 'Coxph')\n switch target\n case 'f'\n [Ef1, Varf1] = gp_pred(gp, x, y, xt1);\n [Ef2, Varf2] = gp_pred(gp, x, y, xt2);\n case 'mu'\n prctmu1 = denormdata(gp_predprctmu(gp, x, y, xt1, options1),nd.ymean,nd.ystd);\n prctmu2 = denormdata(gp_predprctmu(gp, x, y, xt2, options2),nd.ymean,nd.ystd);\n end\n else\n [Ef11,Ef12,Covf] = pred_coxph(gp,x,y,xt1, 'z', z);\n Ef1 = Ef12; Varf1 = diag(Covf(size(Ef11,1)+1:end,size(Ef11,1)+1:end));\n [Ef21,Ef22,Covf] = pred_coxph(gp,x,y,xt2, 'z', z);\n Ef2 = Ef22; Varf2 = diag(Covf(size(Ef21,1)+1:end,size(Ef21,1)+1:end));\n end\n \n if isequal(plot_results, 'on')\n xtnn1=denormdata(xtnn1,nd.xmean(ind(2)),nd.xstd(ind(2)));\n xtnn2=denormdata(xtnn2,nd.xmean(ind(2)),nd.xstd(ind(2)));\n if nu1>2 && nu2==2\n lstyle10='or';lstyle11='-r';lstyle12='--r';\n lstyle20='ob';lstyle21='-b';lstyle22='--b';\n else\n lstyle10='ob';lstyle11='-b';lstyle12='--b';\n lstyle20='or';lstyle21='-r';lstyle22='--r';\n end\n deltadist=gp_finddeltadist(gp);\n if ~ismember(ind(2),deltadist)\n switch target\n case 'f'\n plot(xtnn1, Ef1, lstyle10, xtnn1, Ef1, lstyle11, xtnn1, Ef1-1.64*sqrt(Varf1), lstyle12, xtnn1, Ef1+1.64*sqrt(Varf1), lstyle12); hold on;\n plot(xtnn2, Ef2, lstyle20, xtnn2, Ef2, lstyle21, xtnn2, Ef2-1.64*sqrt(Varf2), lstyle22, xtnn2, Ef2+1.64*sqrt(Varf2), lstyle22); hold off;\n case 'mu'\n plot(xtnn1, prctmu1(:,2), lstyle10, xtnn1, prctmu1(:,2), lstyle11, xtnn1, prctmu1(:,1), lstyle12, xtnn1, prctmu1(:,3), lstyle12); hold on;\n plot(xtnn2, prctmu2(:,2), lstyle20, xtnn2, prctmu2(:,2), lstyle21, xtnn2, prctmu2(:,1), lstyle22, xtnn2, prctmu2(:,3), lstyle22); hold off;\n end\n else\n delta=(diff(xtnn1(1:2))/10);\n switch target\n case 'f'\n plot(xtnn1-delta, Ef1, lstyle10, [xtnn1 xtnn1]'-delta, [Ef1-1.64*sqrt(Varf1) Ef1+1.64*sqrt(Varf1)]', lstyle11); hold on;\n plot(xtnn2+delta, Ef2, lstyle20, [xtnn2 xtnn2]'+delta, [Ef2-1.64*sqrt(Varf2) Ef2+1.64*sqrt(Varf2)]', lstyle21); hold off;\n xlim([1.5*xtnn1(1)-0.5*xtnn1(2) 1.5*xtnn1(end)-.5*xtnn1(end-1)])\n case 'mu'\n plot(xtnn1-delta, prctmu1(:,2), lstyle10, [xtnn1 xtnn1]'-delta, [prctmu1(:,1) prctmu1(:,3)]', lstyle11); hold on;\n plot(xtnn2+delta, prctmu2(:,2), lstyle20, [xtnn2 xtnn2]'+delta, [prctmu2(:,1) prctmu2(:,3)]', lstyle21); hold off;\n xlim([1.5*xtnn1(1)-0.5*xtnn1(2) 1.5*xtnn1(end)-.5*xtnn1(end-1)])\n end\n end\n end\n switch target\n case 'f'\n Ef = {Ef1 Ef2}; Varf = {Varf1 Varf2}; xtnn={xtnn1 xtnn2};\n case 'mu'\n Ef = {prctmu1 prctmu2}; Varf = {[] []}; xtnn={xtnn1 xtnn2};\n end\n \n else\n % both the first and the second covariate are non-binary\n deltadist=gp_finddeltadist(gp);\n if ~ismember(ind(1),deltadist)\n xtnn1 = linspace(min(xt(:,ind(1))), max(xt(:,ind(1))), 20);\n else\n xtnn1 = unique(xt(:,ind(1)));\n end\n if ~ismember(ind(2),deltadist)\n xtnn2 = linspace(min(xt(:,ind(2))), max(xt(:,ind(2))), 20);\n else\n xtnn2 = unique(xt(:,ind(2)));\n end\n [XT1, XT2] = meshgrid(xtnn1, xtnn2); XT1=XT1(:); XT2=XT2(:);\n xtnn1=denormdata(xtnn1,nd.xmean(ind(1)),nd.xstd(ind(1)));\n xtnn2=denormdata(xtnn2,nd.xmean(ind(2)),nd.xstd(ind(2)));\n if ~isempty(z)\n options.zt = repmat(options.zt(1), size(XT1));\n end\n xt = repmat(feval(method,xt), length(XT1), 1);\n if ~isempty(vars)\n xt(:,~isnan(vars)) = repmat(vars(~isnan(vars)), length(XT1), 1);\n end\n xt(:,ind) = [XT1 XT2];\n if ~strcmp(liktype, 'Coxph')\n switch target\n case 'f'\n [Ef, Varf] = gp_pred(gp, x, y, xt);\n case 'mu'\n prctmu = gp_predprctmu(gp, x, y, xt, options, 'prct', 50);\n Ef = prctmu; Varf = [];\n case 'cdf'\n cdf = gp_predcdf(gp, x, y, xt, options);\n Ef = cdf; Varf = [];\n end\n else\n [Ef1,Ef2,Covf] = pred_coxph(gp,x,y,xt, options);\n Ef = Ef2; Varf = diag(Covf(size(Ef1,1)+1:end,size(Ef1,1)+1:end));\n end\n \n indd = zeros(size(Ef));\n \n for i2=1:n\n for i3=1:numel(XT1)\n if sqrt(sum((xto(i2,ind)-xt(i3,ind)).^2)) < tr\n indd(i3) = 1;\n end\n end\n end\n \n XT1(indd==0) = NaN; XT2(indd==0) = NaN; Ef(indd==0) = NaN; Varf(indd==0) = NaN;\n \n if isequal(plot_results, 'on')\n xtnn1=denormdata(xtnn1,nd.xmean(ind(1)),nd.xstd(ind(1)));\n xtnn2=denormdata(xtnn2,nd.xmean(ind(2)),nd.xstd(ind(2)));\n surf(reshape(XT1,numel(xtnn2),numel(xtnn1)), reshape(XT2,numel(xtnn2),numel(xtnn1)), reshape(Ef,numel(xtnn2),numel(xtnn1)))\n view(2)\n axis tight\n shading flat\n colormap(mapcolor(Ef,repmat(nanmedian(Ef(:)),[1 2])))\n colorbar('EastOutside')\n end\n \n %xtnn = [XT1(indd==1), XT2(indd==1)]; Ef = Ef(indd==1); Varf = Varf(indd==1);\n xtnn = [XT1, XT2];\n end\n \nelse\n error('Only 1 or 2 covariates can be defined for predicting')\nend\n\n\nend\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gp_cpred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.38861043481155305}}
{"text": "function [f,J,Q] = spm_fx_cmm(x,u,P,M)\n% state equations for canonical neural-mass and mean-field models\n% FORMAT [f,J,Q] = spm_fx_cmm(x,u,P,M)\n%\n% x - states and covariances\n%\n% x(i,j,k) - k-th state of j-th population of i-th source\n% i.e., running over sources, pop. and states\n%\n% population: 1 - excitatory spiny stellate cells (input cells)\n% 2 - superficial pyramidal cells (forward output cells)\n% 3 - inhibitory interneurons (intrisic interneuons)\n% 4 - deep pyramidal cells (backward output cells)\n%\n% state: 1 V - voltage\n% 2 gE - conductance (excitatory)\n% 3 gI - conductance (inhibitory)\n%\n%--------------------------------------------------------------------------\n% refs:\n%\n% Marreiros et al (2008) Population dynamics under the Laplace assumption\n%\n% See also:\n%\n% Friston KJ.\n% The labile brain. I. Neuronal transients and nonlinear coupling. Philos\n% Trans R Soc Lond B Biol Sci. 2000 Feb 29;355(1394):215-36. \n% \n% McCormick DA, Connors BW, Lighthall JW, Prince DA.\n% Comparative electrophysiology of pyramidal and sparsely spiny stellate\n% neurons of the neocortex. J Neurophysiol. 1985 Oct;54(4):782-806.\n% \n% Brunel N, Wang XJ.\n% What determines the frequency of fast network oscillations with irregular\n% neural discharges? I. Synaptic dynamics and excitation-inhibition\n% balance. J Neurophysiol. 2003 Jul;90(1):415-30.\n% \n% Brunel N, Wang XJ.\n% Effects of neuromodulation in a cortical network model of object working\n% memory dominated by recurrent inhibition. J Comput Neurosci. 2001\n% Jul-Aug;11(1):63-85.\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_fx_cmm.m 5369 2013-03-28 20:09:27Z karl $\n \n% get dimensions and configure state variables\n%--------------------------------------------------------------------------\nns = size(M.x,1); % number of sources\nnp = size(M.x,2); % number of populations per source\nnk = size(M.x,3); % number of states per population\nx = reshape(x,ns,np,nk); % hidden states \n\n\n% extrinsic connection strengths\n%==========================================================================\n \n% exponential transform to ensure positivity constraints\n%--------------------------------------------------------------------------\nA{1} = exp(P.A{1}); % forward\nA{2} = exp(P.A{2}); % backward\nC = exp(P.C); % subcortical\n \n\n% detect and reduce the strength of reciprocal (lateral) connections\n%--------------------------------------------------------------------------\nfor i = 1:length(A)\n L = (A{i} > exp(-8)) & (A{i}' > exp(-8));\n A{i} = A{i}./(1 + 8*L);\nend\n\n \n% intrinsic connection strengths\n%==========================================================================\n\n% condition specific effects\n%--------------------------------------------------------------------------\nG = full(P.H);\nif any(P.G)\n G(2,2,:) = squeeze(G(2,2,:)) + P.G;\nend\nG(2,2,:) = 0;\nG = exp(G);\n\n\n\n% connectivity switches\n%==========================================================================\n% 1 - excitatory spiny stellate cells (granular input cells)\n% 2 - superficial pyramidal cells (forward output cells)\n% 3 - inhibitory interneurons (intrisic interneuons)\n% 4 - deep pyramidal cells (backward output cells)\n\n% extrinsic connections (F B) - from superficial and deep pyramidal cells\n%--------------------------------------------------------------------------\nSA = [1 0 ;\n 0 1 ;\n 0 2 ;\n 0 0]/8;\n \n% intrinsic connections (np x np) - excitatory\n%--------------------------------------------------------------------------\nGE = [ 0 0 0 0\n 4 0 0 0\n 4 0 0 2\n 0 4 0 0];\n \n% intrinsic connections (np x np) - inhibitory\n%--------------------------------------------------------------------------\nGI = [ 8 2 2 0\n 0 8 2 0\n 0 0 32 0\n 0 0 8 128];\n\n% rate constants (ns x np) (excitatory 4ms, inhibitory 16ms)\n%--------------------------------------------------------------------------\nKE = 1000/4; % excitatory rate constants\nKI = exp(-P.T)*[1/64 1/32 1/16 1/16]*1000; % inhibitory rate constants\n \n% Voltages\n%--------------------------------------------------------------------------\nVL = -70; % reversal potential leak (K)\nVE = 60; % reversal potential excite (Na)\nVI = -90; % reversal potential inhib (Cl)\nVR = -40; % threshold potential\n \nCV = exp(P.CV).*[16 16 32 16]/1000; % membrane capacitance\nGL = 1; % leak conductance\n \n% mean-field effects:\n%==========================================================================\n\n% neural-mass approximation to covariance of states\n%----------------------------------------------------------------------\nVx = exp(P.S)*32;\n\n% mean population firing and afferent extrinsic input\n%--------------------------------------------------------------------------\nm = spm_Ncdf_jdw(x(:,:,1),VR,Vx); % mean firing rate \na(:,1) = A{1}*m(:,2); % forward afference\na(:,2) = A{2}*m(:,4); % backward afference\n\n% Averge background activity and exogenous input\n%==========================================================================\nBE = exp(P.E)/2;\n\n% input\n%--------------------------------------------------------------------------\nif isfield(M,'u')\n \n % endogenous input\n %----------------------------------------------------------------------\n U = u(:)*8/1000;\n \nelse\n \n % exogenous input\n %----------------------------------------------------------------------\n U = C*u(:)/1000;\n \nend\n\n% flow over every (ns x np) subpopulation\n%==========================================================================\nf = x;\nfor i = 1:ns\n \n % intrinsic coupling\n %------------------------------------------------------------------\n E = (G(:,:,i).*GE)*m(i,:)';\n I = (G(:,:,i).*GI)*m(i,:)';\n \n % extrinsic coupling (excitatory only) and background activity\n %------------------------------------------------------------------\n E = E + BE + SA*a(i,:)';\n\n % and exogenous input(U)\n %------------------------------------------------------------------\n E(1) = E(1) + U(i);\n \n % Voltage\n %==================================================================\n f(i,:,1) = (GL*(VL - x(i,:,1)) + ...\n x(i,:,2).*(VE - x(i,:,1)) + ...\n x(i,:,3).*(VI - x(i,:,1)) )./CV;\n \n % Conductance\n %==================================================================\n f(i,:,2) = (E' - x(i,:,2)).*KE;\n f(i,:,3) = (I' - x(i,:,3)).*KI(i,:);\n \nend\n \n% vectorise equations of motion\n%==========================================================================\nf = spm_vec(f);\n \nif nargout < 2, return, end\n\n% Jacobian\n%==========================================================================\nJ = spm_cat(spm_diff(M.f,x,u,P,M,1));\n\nif nargout < 3, return, end\n\n% Delays\n%==========================================================================\n% Delay differential equations can be integrated efficiently (but \n% approximately) by absorbing the delay operator into the Jacobian\n%\n% dx(t)/dt = f(x(t - d))\n% = Q(d)f(x(t))\n%\n% J(d) = Q(d)df/dx\n%--------------------------------------------------------------------------\n% [specified] fixed parameters\n%--------------------------------------------------------------------------\nD = [2 16];\n\nd = -D.*exp(P.D)/1000;\nSp = kron(ones(nk,nk),kron( eye(np,np),eye(ns,ns))); % states: same pop.\nSs = kron(ones(nk,nk),kron(ones(np,np),eye(ns,ns))); % states: same source\n\nDp = ~Ss; % states: different sources\nDs = ~Sp & Ss; % states: same source different pop.\nD = d(2)*Dp + d(1)*Ds;\n\n\n% Implement: dx(t)/dt = f(x(t - d)) = inv(1 - D.*dfdx)*f(x(t))\n% = Q*f = Q*J*x(t)\n%--------------------------------------------------------------------------\nQ = spm_inv(speye(length(J)) - D.*J);\n\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/dcm_meeg/spm_fx_cmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3885066433253744}}
{"text": "%IKINE_SYM Symbolic inverse kinematics\n%\n% Q = R.IKINE_SYM(K, OPTIONS) is a cell array (Cx1) of inverse kinematic\n% solutions of the SerialLink object ROBOT. The cells of Q represent the\n% different possible configurations. Each cell of Q is a vector (Nx1), and\n% element J is the symbolic expressions for the J'th joint angle. The\n% solution is in terms of the desired end-point pose of the robot which is\n% represented by the symbolic matrix (3x4) with elements\n% nx ox ax tx\n% ny oy ay ty\n% nz oz az tz\n% where the first three columns specify orientation and the last column\n% specifies translation.\n%\n% K <= N can have only specific values:\n% - 2 solve for translation tx and ty\n% - 3 solve for translation tx, ty and tz\n% - 6 solve for translation and orientation\n%\n% Options::\n%\n% 'file',F Write the solution to an m-file named F\n%\n% Example::\n%\n% mdl_planar2\n% sol = p2.ikine_sym(2);\n% length(sol)\n% ans = \n% 2 % there are 2 solutions\n% s1 = sol{1} % is one solution\n% q1 = s1(1); % the expression for q1\n% q2 = s1(2); % the expression for q2\n%\n% Notes::\n% - Requires the Symbolic Toolbox for MATLAB.\n% - This code is experimental and has a lot of diagnostic prints.\n% - Based on the classical approach using Pieper's method.\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction out = ikine_sym(srobot, N, varargin)\n \n %\n % Given a robot model the following steps are performed:\n % 1. Convert model to symbolic form\n % 2. Find relevant trig equations and solve them for joint angles\n % 3. Write an M-file to implement the solution\n % xikine(T)\n % xikine(T, S) where S is a 3 vector with elements 1 or 2 to select\n % the first or second solution for the corresponding joint.\n %\n % TODO:\n % - handle the wrist joints, only first 3 joints so far\n % - handle base and tool transforms\n \n opt.file = [];\n opt = tb_optparse(opt, varargin);\n \n % make a symbolic representation of the passed robot\n srobot = sym(srobot);\n q = srobot.gencoords();\n\n % test N DOF has an allowable value\n switch N\n case 2\n case 3\n case 6\n otherwise\n error('RTB:ikine_sym:badarg', 'Can only solve for 2,3,6 DOF');\n end\n \n % define symbolic elements of the homogeneous transform\n syms nx ox ax tx\n syms ny oy ay ty\n syms nz oz az tz\n syms d3\n \n % inits\n Q = {};\n trigsubOld = [];\n trigsubNew = [];\n\n % loop over each joint variable\n for j=1:N\n fprintf('----- solving for joint %d\\n', j);\n \n % create some equations to sift through\n [left,right] = pieper(srobot, j, 'left');\n \n % decide which equations to look at\n if j <= 3\n % for first three joints only focus on translational part\n left = left(1:3, 4); left = left(:);\n right = right(1:3, 4); right = right(:);\n else\n % for last three joints only focus on rotational part\n left = left(1:3, 1:3); left = left(:);\n right = right(1:3, 1:3); right = right(:);\n end\n \n % substitute sin/cos for preceding joint as S/C, essentially removes\n % the joint variables from the equations and treats them as constants.\n if ~isempty(trigsubOld)\n left = subs(left, trigsubOld, trigsubNew);\n right = subs(right, trigsubOld, trigsubNew);\n end\n \n % then simplify the LHS\n % do it after the substitution to prevent sum of angle terms being introduced\n left = simplify(left);\n \n % search for a solveable equation:\n % function of current joint variable on the LHS\n % constant element on the RHS\n k = NaN;\n for i=1:length(left)\n if hasonly(left(i), j) && isconstant(right(i))\n k = i;\n break;\n end\n end\n \n eq = [];\n \n if ~isnan(k)\n % create the equation to solve: LHS-RHS == 0\n eq = left(k) - right(k);\n else\n % ok, we weren't lucky, try another strategy\n \n % find all equations:\n % function of current joint variable on the LHS\n \n k = [];\n for i=1:length(left)\n % has qj on the left and constant on the right\n if hasonly(left(i), j)\n k = [k i];\n end\n end\n \n % hopefully we found two of them\n if length(k) < 2\n continue;\n end\n \n % we did, lets see if the sum square RHS is constant\n rhs = simplify(right(k(1))^2 + right(k(2))^2); % was simple\n if isconstant( rhs )\n % it is, let's sum and square the LHS\n fprintf('lets square and add %d %d\\n', k);\n \n eq = simplify( expand( left(k(1))^2 + left(k(2))^2 ) ) - rhs; % was simple\n end\n end\n \n % expand the list of joint variable subsitutions\n fprintf('subs sin/cos q%d for S/C\\n', j);\n trigsubOld = [trigsubOld mvar('sin(q%d)', j) mvar('cos(q%d)', j)];\n trigsubNew = [trigsubNew mvar('S%d', j) mvar('C%d', j)];\n \n if isempty(eq)\n fprintf('cant solve this equation');\n k\n left(k)==right(k)\n error('cant solve');\n end\n % now solve the equation\n if srobot.links(j).isrevolute()\n % for revolute joint it will be a trig equation, do we know how to solve it?\n Q{j} = solve_joint(eq, j );\n if isempty(Q)\n warning('cant solve this kind of equation');\n end\n else\n fprintf('prismatic case\\n')\n q = sym( sprintf('q%d', j) );\n Q{j} = solve( eq == 0, q);\n end\n end\n \n % final simplification\n % get rid of C^2+S^2 and C^4, S^4 terms\n fprintf('**final simplification pass\\n')\n \n % create a list of simplifications\n % substitute S^2 = 1-C^2, S^4=(1-C^2)^2\n tsubOld = [];\n tsubNew = [];\n for j=1:N\n tsubOld = [tsubOld mvar('S%d', j)^2 mvar('S%d', j)^4];\n tsubNew = [tsubNew 1-mvar('C%d', j)^2 (1-mvar('C%d', j)^2)^2];\n end\n \n for j=1:N\n for k=1:5\n % seem to need to iterate this, not quite sure why\n Q{j} = simplify( expand( subs(Q{j}, tsubOld, tsubNew) ) );\n end\n end\n\n % Q is a cell array of equations for joint variables\n if nargout > 0\n out = Q;\n end\n \n if ~isempty(opt.file)\n fprintf('**generate MATLAB code\\n')\n gencode(Q);\n end\nend\n\n%PIEPER Return a set of equations using Pieper's method\n%\n% [L,R] = pieper(robot, n, which)\n%\n% If robot has link matrix A1 A2 A3 A4 then returns 12 equations from equating the coefficients of\n%\n% A1' T = A2 A3 A4 n=1, which='left'\n% A2' A1' T = A3 A4 n=2, which='left'\n% A3' A2' A1' T = A4 n=3, which='left'\n%\n% T A4' = A1 A2 A3 n=1, which='right'\n% T A4' A3' = A1 A2 n=2, which='right'\n% T A4' A3' A2' = A1 n=3, which='right'\n%\n% Judicious choice of the equations can lead to joint solutions\n\nfunction [L,R] = pieper(robot, n, which)\n \n if nargin < 3\n which = 'left';\n end\n \n syms nx ox ax tx real\n syms ny oy ay ty real\n syms nz oz az tz real\n \n T = [nx ox ax tx\n ny oy ay ty\n nx oz az tz\n 0 0 0 1 ];\n \n T = inv(robot.base) * T * inv(robot.tool);\n \n q = robot.gencoords();\n \n \n % Create the symbolic A matrices\n for j=1:robot.n\n A{j} = robot.links(j).A(q(j));\n end\n \n switch which\n case 'left'\n left = T;\n for j=1:n\n left = inv(A{j}) * left ;\n end\n \n right = eye(4,4);\n for j=n+1:robot.n\n right = right * A{j};\n end\n \n case 'right'\n left = T;\n for j=1:n\n left = left * inv(A{robot.n-j+1});\n end\n \n right = eye(4,4);\n for j=1:(robot.n-n)\n right = right * A{j};\n end\n end\n \n % left = simple(left);\n % right = simple(right);\n \n if nargout == 0\n left == right\n elseif nargout == 1\n L = left;\n elseif nargout == 2\n L = left;\n R = right;\n end\nend\n\n%SOLVE_JOINT Solve a trigonometric equation\n%\n% S = SOLVE_JOINT(EQ, J) solves the equation EQ=0 for the joint variable qJ.\n% The result is a cell array of solutions.\n%\n% The equations must be of the form:\n% A cos(qJ) + B sin(qJ) = 0\n% A cos(qJ) + B sin(qJ) = C\n%\n% where A, B, C are arbitrarily complex expressions. qJ can be the only\n% joint variable in the expression.\n\nfunction s = solve_joint(eq, j)\n \n sinj = mvar('sin(q%d)', j);\n cosj = mvar('cos(q%d)', j);\n \n A = getcoef(eq, cosj);\n B = getcoef(eq, sinj);\n \n if isempty(A) || isempty(B)\n warning('don''t know how to solve this kind of equation');\n end\n \n C = -simplify(eq - A*cosj - B*sinj); % was simple\n \n if C == 0\n % A cos(q) + B sin(q) = 0\n s(2) = atan2(A, -B);\n s(1) = atan2(-A, B);\n else\n % A cos(q) + B sin(q) = C\n r = sqrt(A^2 + B^2 - C^2);\n phi = atan2(A, B);\n \n s(2) = atan2(C, r) - phi;\n s(1) = atan2(C, -r) - phi;\n end\n if nargout == 0\n try\n eval(s)\n catch\n s\n end\n end\nend\n\n%MVAR Create a symbolic variable\n%\n% V = MVAR(FMT, ARGS) is a symbolic variable created using SPRINTF\n%\n% eg. mvar('q%d', j)\n%\n% The symbolic is explicitly declared to be real.\n\nfunction v = mvar(fmt, varargin)\n\n if isempty(strfind(fmt, '('))\n % not a function\n v = sym( sprintf(fmt, varargin{:}), 'real' );\n else\n v = sym( sprintf(fmt, varargin{:}) );\n \n end\nend\n\n%HASONLY Determine if an expression contains only certain joint variables\n%\n% S = HASONLY(E L) is true if the joint variables (q1, q2 etc.) in the expression E\n% are listed in the vector L.\n%\n% Eg. hasonly('sin(q1)*cos(q2)*cos(q4)', [1 2 3]) -> true\n% Eg. hasonly('sin(q1)*cos(q2)*cos(q4)', [1]) -> false\n\nfunction s = hasonly(eq, j)\n \n q = findq(eq);\n if isempty(q)\n s = false;\n else\n s = all(ismember(j, findq(eq)));\n end\nend\n\n%ISCONSTANT Determine if an expression is free of joint variables\n%\n% S = ISCONSTANT(E) is true if the expression E contains no joint variables such\n% q1, q2 etc.\n\nfunction s = isconstant(eq)\n s = isempty(findq(eq));\nend\n\n%FINDQ Find the joint variables in expression\n%\n% Q = FINDQ(E) returns a list of integers indicating the joint variables found\n% in the expression E. For instance an instance of 'q1' would cause a 1 to be\n% returned and so on.\n%\n% Eg. findq('sin(q1)*cos(q2)+S3') -> [1 2]\n\nfunction q = findq(s)\n \n q = [];\n \n for var=symvar(s)\n if isempty(var)\n break\n end\n varname = char(var);\n if varname(1) == 'q'\n q = [q str2num(varname(2:end))];\n end\n end\nend\n\nfunction coef = getcoef(eq, trig)\n z = children( collect(eq, trig) );\n z = children( z(1) );\n coef = z(1);\nend\n\n% Output a joint expression to a file\n\nfunction s = gencode(Q, filename)\n \n function s = G(s, fmt, varargin)\n s = strvcat(s, sprintf(fmt, varargin{:}));\n end\n\n s = 'function q = xikine(T, sol)';\n s = G(s, ' if nargin < 2; sol = ones(1, %d); end', length(Q));\n s = G(s, ' px = T(1,4); py = T(2,4); pz = T(3,4);');\n \n for j=1:3\n Qj = Q{j}; % cast it to subclass\n if length(Qj) == 1\n s = G(s, ' q(%d) = %s', j, matgen2(Qj));\n elseif length(Qj) == 2\n s = G(s, ' if sol(%d) == 1', j);\n s = G(s, ' q(%d) = %s', j, matgen2(Qj(1)));\n s = G(s, ' else');\n s = G(s, ' q(%d) = %s', j, matgen2(Qj(2)));\n s = G(s, ' end');\n \n \n end\n \n \n s = G(s, ' S%d = sin(q(%d));', j, j);\n s = G(s, ' C%d = cos(q(%d));', j, j);\n s = G(s, ' ');\n \n \n end\n s = G(s, 'end');\n \n fp = fopen(filename, 'w');\n for i=1:numrows(s)\n fprintf(fp, '%s\\n', deblank(s(i,:)));\n end\n fclose(fp);\n \nend\n\n% Generate MATLAB code from an expression\n%\n% Requires a bit of a hack, a subclass of sym (sym2) to do this\n\nfunction s = matgen2(e)\n \n s = matgen(sym2(e));\n \n k = strfind(s, '=');\n s = deblank( s(k+2:end) );\nend\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/@SerialLink/ikine_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.38837741921140884}}
{"text": "function [PSNR, yRGB_est] = CBM3D(yRGB, zRGB, sigma, profile, print_to_screen, colorspace)\n%\n% CBM3D is algorithm for attenuation of additive white Gaussian noise from \n% color RGB images. This algorithm reproduces the results from the article:\n%\n% [1] K. Dabov, A. Foi, V. Katkovnik, and K. Egiazarian, \"Color image\n% denoising via sparse 3D collaborative filtering with grouping constraint in \n% luminance-chrominance space,\" submitted to IEEE Int. Conf. Image Process., \n% January 2007, in review, preprint at http://www.cs.tut.fi/~foi/GCF-BM3D.\n%\n% FUNCTION INTERFACE:\n%\n% [PSNR, yRGB_est] = CBM3D(yRGB, zRGB, sigma, profile, print_to_screen, colorspace)\n%\n% ! The function can work without any of the input arguments, \n% in which case, the internal default ones are used !\n% \n% BASIC USAGE EXAMPLES:\n%\n% Case 1) Using the default parameters (i.e., image name, sigma, etc.)\n% \n% [PSNR, yRGB_est] = CBM3D;\n% \n% Case 2) Using an external noisy image:\n%\n% % Read an RGB image and scale its intensities in range [0,1]\n% yRGB = im2double(imread('image_House256rgb.png')); \n% % Generate the same seed used in the experimental results of [1]\n% randn('seed', 0);\n% % Standard deviation of the noise --- corresponding to intensity \n% % range [0,255], despite that the input was scaled in [0,1]\n% sigma = 25;\n% % Add the AWGN with zero mean and standard deviation 'sigma'\n% zRGB = yRGB + (sigma/255)*randn(size(yRGB));\n% % Denoise 'zRGB'. The denoised image is 'yRGB_est', and 'NA = 1' \n% % because the true image was not provided\n% [NA, yRGB_est] = CBM3D(1, zRGB, sigma); \n% % Compute the putput PSNR\n% PSNR = 10*log10(1/mean((yRGB(:)-yRGB_est(:)).^2))\n% % show the noisy image 'zRGB' and the denoised 'yRGB_est'\n% figure; imshow(min(max(zRGB,0),1)); \n% figure; imshow(min(max(yRGB_est,0),1));\n% \n% Case 3) If the original image yRGB is provided as the first input \n% argument, then some additional information is printed (PSNRs, \n% figures, etc.). That is, \"[NA, yRGB_est] = BM3D(1, zRGB, sigma);\" in the\n% above code should be replaced with:\n% \n% [PSNR, yRGB_est] = CBM3D(yRGB, zRGB, sigma);\n% \n% \n% INPUT ARGUMENTS (OPTIONAL):\n% 1) yRGB (M x N x 3): Noise-free RGB image (needed for computing PSNR),\n% replace with the scalar 1 if not available.\n% 2) zRGB (M x N x 3): Noisy RGBimage (intensities in range [0,1] or [0,255])\n% 3) sigma (double) : Std. dev. of the noise (corresponding to intensities\n% in range [0,255] even if the range of zRGB is [0,1])\n% 4) profile (char) : 'np' --> Normal Profile \n% 'lc' --> Fast Profile\n% 5) print_to_screen : 0 --> do not print output information (and do \n% not plot figures)\n% 1 --> print information and plot figures\n% 6) colorspace (char): 'opp' --> use opponent colorspace\n% 'yCbCr' --> use yCbCr colorspace\n%\n% OUTPUTS:\n% 1) PSNR (double) : Output PSNR (dB), only if the original \n% image is available, otherwise PSNR = 0 \n% 2) yRGB_est (M x N x 3): Final RGB estimate (in the range [0,1])\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright (c) 2007-2011 Tampere University of Technology.\n% All rights reserved.\n% This work should only be used for nonprofit purposes.\n%\n% AUTHORS:\n% Kostadin Dabov, email: dabov _at_ cs.tut.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% In case, there is no input image (zRGB or yRGB), then use the filename \n%%%% below to read an original image (might contain path also). Later, \n%%%% artificial AWGN noise is added and this noisy image is processed \n%%%% by the CBM3D.\n%%%%\nimage_name = [\n% 'kodim12.png'\n 'image_Lena512rgb.png'\n% 'image_House256rgb.png'\n% 'image_Peppers512rgb.png'\n% 'image_Baboon512rgb.png'\n% 'image_F16_512rgb.png'\n ];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Quality/complexity trade-off \n%%%%\n%%%% 'np' --> Normal Profile (balanced quality)\n%%%% 'lc' --> Low Complexity Profile (fast, lower quality)\n%%%%\n%%%% 'high' --> High Profile (high quality, not documented in [1])\n%%%%\n%%%% 'vn' --> This profile is automatically enabled for high noise \n%%%% when sigma > 40\n%%%%\n%%%% 'vn_old' --> This is the old 'vn' profile that was used in [1].\n%%%% It gives inferior results than 'vn' in most cases. \n%%%%\nif (exist('profile') ~= 1)\n profile = 'np'; %% default profile\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Specify the std. dev. of the corrupting noise\n%%%%\nif (exist('sigma') ~= 1),\n sigma = 50; %% default standard deviation of the AWGN\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Colorspace in which we perform denoising. BM is applied to the first\n%%%% component and the matching information is re-used for the other two.\n%%%%\nif (exist('colorspace') ~= 1),\n colorspace = 'opp'; %%% (valid colorspaces are: 'yCbCr' and 'opp')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Following are the parameters for the Normal Profile.\n%%%%\n\n%%%% Select transforms ('dct', 'dst', 'hadamard', or anything that is listed by 'help wfilters'):\ntransform_2D_HT_name = 'bior1.5'; %% transform used for the HT filt. of size N1 x N1\ntransform_2D_Wiener_name = 'dct'; %% transform used for the Wiener filt. of size N1_wiener x N1_wiener\ntransform_3rd_dim_name = 'haar'; %% transform used in the 3-rd dim, the same for HT and Wiener filt.\n\n%%%% Hard-thresholding (HT) parameters:\nN1 = 8; %% N1 x N1 is the block size used for the hard-thresholding (HT) filtering\nNstep = 3; %% sliding step to process every next reference block\nN2 = 16; %% maximum number of similar blocks (maximum size of the 3rd dimension of a 3D array)\nNs = 39; %% length of the side of the search neighborhood for full-search block-matching (BM), must be odd\ntau_match = 3000;%% threshold for the block-distance (d-distance)\nlambda_thr2D = 0; %% threshold parameter for the coarse initial denoising used in the d-distance measure\nlambda_thr3D = 2.7; %% threshold parameter for the hard-thresholding in 3D transform domain\nbeta = 2.0; %% parameter of the 2D Kaiser window used in the reconstruction\n\n%%%% Wiener filtering parameters:\nN1_wiener = 8;\nNstep_wiener = 3;\nN2_wiener = 32;\nNs_wiener = 39;\ntau_match_wiener = 400;\nbeta_wiener = 2.0;\n\n%%%% Block-matching parameters:\nstepFS = 1; %% step that forces to switch to full-search BM, \"1\" implies always full-search\nsmallLN = 'not used in np'; %% if stepFS > 1, then this specifies the size of the small local search neighb.\nstepFSW = 1;\nsmallLNW = 'not used in np';\nthrToIncStep = 8; %% used in the HT filtering to increase the sliding step in uniform regions\n\nif strcmp(profile, 'lc') == 1,\n\n Nstep = 6;\n Ns = 25;\n Nstep_wiener = 5;\n N2_wiener = 16;\n Ns_wiener = 25;\n\n thrToIncStep = 3;\n smallLN = 3;\n stepFS = 6*Nstep;\n smallLNW = 2;\n stepFSW = 5*Nstep_wiener;\n\nend\n\n% Profile 'vn' was proposed in \n% Y. Hou, C. Zhao, D. Yang, and Y. Cheng, 'Comment on \"Image Denoising by Sparse 3D Transform-Domain\n% Collaborative Filtering\"', accepted for publication, IEEE Trans. on Image Processing, July, 2010.\n% as a better alternative to that initially proposed in [1] (which is currently in profile 'vn_old')\nif (strcmp(profile, 'vn') == 1) | (sigma > 40),\n\n N2 = 32;\n Nstep = 4;\n \n N1_wiener = 11;\n Nstep_wiener = 6;\n\n lambda_thr3D = 2.8;\n thrToIncStep = 3;\n tau_match_wiener = 3500;\n tau_match = 25000;\n \n Ns_wiener = 39;\n \nend\n\n% The 'vn_old' profile corresponds to the original parameters for strong noise proposed in [1].\nif (strcmp(profile, 'vn_old') == 1) & (sigma > 40),\n\n transform_2D_HT_name = 'dct'; \n \n N1 = 12;\n Nstep = 4;\n \n N1_wiener = 11;\n Nstep_wiener = 6;\n\n lambda_thr3D = 2.8;\n lambda_thr2D = 2.0;\n thrToIncStep = 3;\n tau_match_wiener = 3500;\n tau_match = 5000;\n \n Ns_wiener = 39;\n \nend\n\n\ndecLevel = 0; %% dec. levels of the dyadic wavelet 2D transform for blocks (0 means full decomposition, higher values decrease the dec. number)\nthr_mask = ones(N1); %% N1xN1 mask of threshold scaling coeff. --- by default there is no scaling, however the use of different thresholds for different wavelet decompoistion subbands can be done with this matrix\n\nif strcmp(profile, 'high') == 1,\n \n decLevel = 1; \n Nstep = 2;\n Nstep_wiener = 2;\n lambda_thr3D = 2.5;\n vMask = ones(N1,1); vMask((end/4+1):end/2)= 1.01; vMask((end/2+1):end) = 1.07; %% this allows to have different threhsolds for the finest and next-to-the-finest subbands\n thr_mask = vMask * vMask'; \n beta = 2.5;\n beta_wiener = 1.5;\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Note: touch below this point only if you know what you are doing!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% Check whether to dump information to the screen or reamin silent\ndump_output_information = 1;\nif (exist('print_to_screen') == 1) & (print_to_screen == 0),\n dump_output_information = 0;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Create transform matrices, etc.\n%%%%\n[Tfor, Tinv] = getTransfMatrix(N1, transform_2D_HT_name, decLevel); %% get (normalized) forward and inverse transform matrices\n[TforW, TinvW] = getTransfMatrix(N1_wiener, transform_2D_Wiener_name); %% get (normalized) forward and inverse transform matrices\n\nif (strcmp(transform_3rd_dim_name, 'haar') == 1) | (strcmp(transform_3rd_dim_name(end-2:end), '1.1') == 1),\n %%% If Haar is used in the 3-rd dimension, then a fast internal transform is used, thus no need to generate transform\n %%% matrices.\n hadper_trans_single_den = {};\n inverse_hadper_trans_single_den = {};\nelse\n %%% Create transform matrices. The transforms are later applied by\n %%% matrix-vector multiplication for the 1D case.\n for hpow = 0:ceil(log2(max(N2,N2_wiener))),\n h = 2^hpow;\n [Tfor3rd, Tinv3rd] = getTransfMatrix(h, transform_3rd_dim_name, 0);\n hadper_trans_single_den{h} = single(Tfor3rd);\n inverse_hadper_trans_single_den{h} = single(Tinv3rd');\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% 2D Kaiser windows used in the aggregation of block-wise estimates\n%%%%\nif beta_wiener==2 & beta==2 & N1_wiener==8 & N1==8 % hardcode the window function so that the signal processing toolbox is not needed by default\n Wwin2D = [ 0.1924 0.2989 0.3846 0.4325 0.4325 0.3846 0.2989 0.1924;\n 0.2989 0.4642 0.5974 0.6717 0.6717 0.5974 0.4642 0.2989;\n 0.3846 0.5974 0.7688 0.8644 0.8644 0.7688 0.5974 0.3846;\n 0.4325 0.6717 0.8644 0.9718 0.9718 0.8644 0.6717 0.4325;\n 0.4325 0.6717 0.8644 0.9718 0.9718 0.8644 0.6717 0.4325;\n 0.3846 0.5974 0.7688 0.8644 0.8644 0.7688 0.5974 0.3846;\n 0.2989 0.4642 0.5974 0.6717 0.6717 0.5974 0.4642 0.2989;\n 0.1924 0.2989 0.3846 0.4325 0.4325 0.3846 0.2989 0.1924];\n Wwin2D_wiener = Wwin2D;\nelse\n Wwin2D = kaiser(N1, beta) * kaiser(N1, beta)'; % Kaiser window used in the aggregation of the HT part\n Wwin2D_wiener = kaiser(N1_wiener, beta_wiener) * kaiser(N1_wiener, beta_wiener)'; % Kaiser window used in the aggregation of the Wiener filt. part\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% If needed, read images, generate noise, or scale the images to the \n%%%% [0,1] interval\n%%%%\nif (exist('yRGB') ~= 1) | (exist('zRGB') ~= 1)\n yRGB = im2double(imread(image_name)); %% read a noise-free image\n randn('seed', 0); %% generate seed\n zRGB = yRGB + (sigma/255)*randn(size(yRGB)); %% create a noisy image\nelse % external images\n image_name = 'External image';\n \n % convert zRGB to double precision\n zRGB = double(zRGB);\n\n % convert yRGB to double precision\n yRGB = double(yRGB);\n \n % if zRGB's range is [0, 255], then convert to [0, 1]\n if (max(zRGB(:)) > 10), % a naive check for intensity range\n zRGB = zRGB / 255;\n end\n \n % if yRGB's range is [0, 255], then convert to [0, 1]\n if (max(yRGB(:)) > 10), % a naive check for intensity range\n yRGB = yRGB / 255;\n end \nend\n\n\nif (size(zRGB,3) ~= 3) | (size(zRGB,4) ~= 1),\n error('CBM3D accepts only input RGB images (i.e. matrices of size M x N x 3).');\nend\n\n% Check if the true image yRGB is a valid one; if not, then we cannot compute PSNR, etc.\nyRGB_is_invalid_image = (length(size(zRGB)) ~= length(size(yRGB))) | (size(zRGB,1) ~= size(yRGB,1)) | (size(zRGB,2) ~= size(yRGB,2)) | (size(zRGB,3) ~= size(yRGB,3));\nif (yRGB_is_invalid_image),\n dump_output_information = 0;\nend\n\n\n[Xv, Xh, numSlices] = size(zRGB); %%% obtain image sizes\n\nif numSlices ~= 3\n fprintf('Error, an RGB color image is required!\\n');\n return;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Change colorspace, compute the l2-norms of the new color channels\n%%%%\n[zColSpace l2normLumChrom] = function_rgb2LumChrom(zRGB, colorspace);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Print image information to the screen\n%%%%\nif dump_output_information == 1,\n fprintf(sprintf('Image: %s (%dx%dx%d), sigma: %.1f\\n', image_name, Xv, Xh, numSlices, sigma));\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Step 1. Basic estimate by collaborative hard-thresholding and using\n%%%% the grouping constraint on the chrominances.\n%%%%\ntic;\ny_hat = bm3d_thr_color(zColSpace, hadper_trans_single_den, Nstep, N1, N2, lambda_thr2D,...\n lambda_thr3D, tau_match*N1*N1/(255*255), (Ns-1)/2, sigma/255, thrToIncStep, single(Tfor), single(Tinv)', inverse_hadper_trans_single_den, single(thr_mask), 'unused arg', 'unused arg', l2normLumChrom, Wwin2D, smallLN, stepFS );\nestimate_elapsed_time = toc;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Step 2. Final estimate by collaborative Wiener filtering and using\n%%%% the grouping constraint on the chrominances.\n%%%%\ntic;\nyRGB_est = bm3d_wiener_color(zColSpace, y_hat, hadper_trans_single_den, Nstep_wiener, N1_wiener, N2_wiener, ...\n 'unused_arg', tau_match_wiener*N1_wiener*N1_wiener/(255*255), (Ns_wiener-1)/2, sigma/255, 'unused arg', single(TforW), single(TinvW)', inverse_hadper_trans_single_den, 'unused arg', 'unused arg', l2normLumChrom, Wwin2D_wiener, smallLNW, stepFSW );\nwiener_elapsed_time = toc;\n\nyRGB_est = double(yRGB_est);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Convert back to RGB colorspace\n%%%%\nyRGB_est = function_LumChrom2rgb(yRGB_est, colorspace);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% Calculate final estimate's PSNR and ISNR, print them, and show the\n%%%% denoised image\n%%%%\nPSNR = 0; %% Remains 0 if the true image yRGB is not available\nif (~yRGB_is_invalid_image), % then we assume yRGB is a valid image\n PSNR = 10*log10(1/mean((yRGB(:)-yRGB_est(:)).^2));\nend\n\nif dump_output_information == 1,\n fprintf(sprintf('FINAL ESTIMATE (total time: %.1f sec), PSNR: %.2f dB\\n', ...\n wiener_elapsed_time + estimate_elapsed_time, PSNR));\n\n figure, imshow(min(max(zRGB,0),1)); title(sprintf('Noisy %s, PSNR: %.3f dB (sigma: %d)', ...\n image_name(1:end-4), 10*log10(1/mean((yRGB(:)-zRGB(:)).^2)), sigma));\n\n figure, imshow(min(max(yRGB_est,0),1)); title(sprintf('Denoised %s, PSNR: %.3f dB', ...\n image_name(1:end-4), PSNR));\nend\n\nreturn;\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Some auxiliary functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\nfunction [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)\n%\n% Create forward and inverse transform matrices, which allow for perfect\n% reconstruction. The forward transform matrix is normalized so that the \n% l2-norm of each basis element is 1.\n%\n% [Tforward, Tinverse] = getTransfMatrix (N, transform_type, dec_levels)\n%\n% INPUTS:\n%\n% N --> Size of the transform (for wavelets, must be 2^K)\n%\n% transform_type --> 'dct', 'dst', 'hadamard', or anything that is \n% listed by 'help wfilters' (bi-orthogonal wavelets)\n% 'DCrand' -- an orthonormal transform with a DC and all\n% the other basis elements of random nature\n%\n% dec_levels --> If a wavelet transform is generated, this is the\n% desired decomposition level. Must be in the\n% range [0, log2(N)-1], where \"0\" implies\n% full decomposition.\n%\n% OUTPUTS:\n%\n% Tforward --> (N x N) Forward transform matrix\n%\n% Tinverse --> (N x N) Inverse transform matrix\n%\n\nif exist('dec_levels') ~= 1,\n dec_levels = 0;\nend\n\nif N == 1,\n Tforward = 1;\nelseif strcmp(transform_type, 'hadamard') == 1,\n Tforward = hadamard(N);\nelseif (N == 8) & strcmp(transform_type, 'bior1.5')==1 % hardcoded transform so that the wavelet toolbox is not needed to generate it\n Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;\n 0.219417649252501 0.449283757993216 0.449283757993216 0.219417649252501 -0.219417649252501 -0.449283757993216 -0.449283757993216 -0.219417649252501;\n 0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846 -0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284;\n -0.083506045090284 0.083506045090284 -0.083506045090284 0.083506045090284 0.569359398342846 0.402347308162278 -0.402347308162278 -0.569359398342846;\n 0.707106781186547 -0.707106781186547 0 0 0 0 0 0;\n 0 0 0.707106781186547 -0.707106781186547 0 0 0 0;\n 0 0 0 0 0.707106781186547 -0.707106781186547 0 0;\n 0 0 0 0 0 0 0.707106781186547 -0.707106781186547]; \nelseif (N == 8) & strcmp(transform_type, 'dct')==1 % hardcoded transform so that the signal processing toolbox is not needed to generate it\n Tforward = [ 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274 0.353553390593274;\n 0.490392640201615 0.415734806151273 0.277785116509801 0.097545161008064 -0.097545161008064 -0.277785116509801 -0.415734806151273 -0.490392640201615;\n 0.461939766255643 0.191341716182545 -0.191341716182545 -0.461939766255643 -0.461939766255643 -0.191341716182545 0.191341716182545 0.461939766255643;\n 0.415734806151273 -0.097545161008064 -0.490392640201615 -0.277785116509801 0.277785116509801 0.490392640201615 0.097545161008064 -0.415734806151273;\n 0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274 0.353553390593274 -0.353553390593274 -0.353553390593274 0.353553390593274;\n 0.277785116509801 -0.490392640201615 0.097545161008064 0.415734806151273 -0.415734806151273 -0.097545161008064 0.490392640201615 -0.277785116509801;\n 0.191341716182545 -0.461939766255643 0.461939766255643 -0.191341716182545 -0.191341716182545 0.461939766255643 -0.461939766255643 0.191341716182545;\n 0.097545161008064 -0.277785116509801 0.415734806151273 -0.490392640201615 0.490392640201615 -0.415734806151273 0.277785116509801 -0.097545161008064];\nelseif (N == 8) & strcmp(transform_type, 'dst')==1 % hardcoded transform so that the PDE toolbox is not needed to generate it\n Tforward = [ 0.161229841765317 0.303012985114696 0.408248290463863 0.464242826880013 0.464242826880013 0.408248290463863 0.303012985114696 0.161229841765317;\n 0.303012985114696 0.464242826880013 0.408248290463863 0.161229841765317 -0.161229841765317 -0.408248290463863 -0.464242826880013 -0.303012985114696;\n 0.408248290463863 0.408248290463863 0 -0.408248290463863 -0.408248290463863 0 0.408248290463863 0.408248290463863;\n 0.464242826880013 0.161229841765317 -0.408248290463863 -0.303012985114696 0.303012985114696 0.408248290463863 -0.161229841765317 -0.464242826880013;\n 0.464242826880013 -0.161229841765317 -0.408248290463863 0.303012985114696 0.303012985114696 -0.408248290463863 -0.161229841765317 0.464242826880013;\n 0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863 0 0.408248290463863 -0.408248290463863;\n 0.303012985114696 -0.464242826880013 0.408248290463863 -0.161229841765317 -0.161229841765317 0.408248290463863 -0.464242826880013 0.303012985114696;\n 0.161229841765317 -0.303012985114696 0.408248290463863 -0.464242826880013 0.464242826880013 -0.408248290463863 0.303012985114696 -0.161229841765317];\nelseif strcmp(transform_type, 'dct') == 1,\n Tforward = dct(eye(N));\nelseif strcmp(transform_type, 'dst') == 1,\n Tforward = dst(eye(N));\nelseif strcmp(transform_type, 'DCrand') == 1,\n x = randn(N); x(1:end,1) = 1; [Q,R] = qr(x); \n if (Q(1) < 0), \n Q = -Q; \n end;\n Tforward = Q';\nelse %% a wavelet decomposition supported by 'wavedec'\n %%% Set periodic boundary conditions, to preserve bi-orthogonality\n dwtmode('per','nodisp'); \n \n Tforward = zeros(N,N);\n for i = 1:N\n Tforward(:,i)=wavedec(circshift([1 zeros(1,N-1)],[dec_levels i-1]), log2(N), transform_type); %% construct transform matrix\n end\nend\n\n%%% Normalize the basis elements\nTforward = (Tforward' * diag(sqrt(1./sum(Tforward.^2,2))))'; \n\n%%% Compute the inverse transform matrix\nTinverse = inv(Tforward);\n\nreturn;\n\nfunction [y, A, l2normLumChrom]=function_rgb2LumChrom(xRGB, colormode)\n% Forward color-space transformation ( inverse transformation is function_LumChrom2rgb.m )\n%\n% Alessandro Foi - Tampere University of Technology - 2005 - 2006 Public release v1.03 (March 2006)\n% -----------------------------------------------------------------------------------------------------------------------------------------------\n%\n% SYNTAX:\n%\n% [y A l2normLumChrom] = function_rgb2LumChrom(xRGB, colormode);\n%\n% INPUTS:\n% xRGB is RGB image with range [0 1]^3\n%\n% colormode = 'opp', 'yCbCr', 'pca', or a custom 3x3 matrix\n%\n% 'opp' Opponent color space ('opp' is equirange version)\n% 'yCbCr' The standard yCbCr (e.g. for JPEG images)\n% 'pca' Principal components (note that this transformation is renormalized to be equirange) \n%\n% OUTPUTS:\n% y is color-transformed image (with range typically included in or equal to [0 1]^3, depending on the transformation matrix)\n%\n% l2normLumChrom (optional) l2-norm of the transformation (useful for noise std calculation)\n% A transformation matrix (used necessarily if colormode='pca')\n%\n% NOTES: - If only two outputs are used, then the second output is l2normLumChrom, unless colormode='pca';\n% - 'opp' is used by default if no colormode is specified.\n%\n%\n% USAGE EXAMPLE FOR PCA TRANSFORMATION:\n% %%%% -- forward color transformation --\n% if colormode=='pca'\n% [zLumChrom colormode] = function_rgb2LumChrom(zRGB,colormode); % 'colormode' is assigned a 3x3 transform matrix\n% else\n% zLumChrom = function_rgb2LumChrom(zRGB,colormode);\n% end\n%\n% %%%% [ ... ] Some processing [ ... ]\n%\n% %%%% -- inverse color transformation --\n% zRGB=function_LumChrom2rgb(zLumChrom,colormode);\n%\n\nif nargin==1\n colormode='opp';\nend\nchange_output=0;\nif size(colormode)==[3 3]\n A=colormode;\n l2normLumChrom=sqrt(sum(A.^2,2));\nelse\n if strcmp(colormode,'opp')\n A=[1/3 1/3 1/3; 0.5 0 -0.5; 0.25 -0.5 0.25];\n end\n if strcmp(colormode,'yCbCr')\n A=[0.299 0.587 0.114; -0.16873660714285 -0.33126339285715 0.5; 0.5 -0.4186875 -0.0813125];\n end\n if strcmp(colormode,'pca')\n A=princomp(reshape(xRGB,[size(xRGB,1)*size(xRGB,2) 3]))';\n A=A./repmat(sum(A.*(A>0),2)-sum(A.*(A<0),2),[1 3]); %% ranges are normalized to unitary length;\n else\n if nargout==2\n change_output=1;\n end\n end\nend\n\n%%%% Make sure that each channel's intensity range is [0,1]\nmaxV = sum(A.*(A>0),2);\nminV = sum(A.*(A<0),2);\nyNormal = (reshape(xRGB,[size(xRGB,1)*size(xRGB,2) 3]) * A' - repmat(minV, [1 size(xRGB,1)*size(xRGB,2)])') * diag(1./(maxV-minV)); % put in range [0,1]\ny = reshape(yNormal, [size(xRGB,1) size(xRGB,2) 3]);\n\n%%%% The l2-norm of each of the 3 transform basis elements \nl2normLumChrom = diag(1./(maxV-minV))*sqrt(sum(A.^2,2));\n\nif change_output\n A=l2normLumChrom;\nend\n\nreturn;\n\n\n\n\nfunction yRGB=function_LumChrom2rgb(x,colormode)\n% Inverse color-space transformation ( forward transformation is function_rgb2LumChrom.m )\n%\n% Alessandro Foi - Tampere University of Technology - 2005 - 2006 Public release v1.03 (March 2006)\n% -----------------------------------------------------------------------------------------------------------------------------------------------\n%\n% SYNTAX:\n%\n% yRGB = function_LumChrom2rgb(x,colormode);\n%\n% INPUTS:\n% x is color-transformed image (with range typically included in or equal to [0 1]^3, depending on the transformation matrix)\n%\n% colormode = 'opp', 'yCbCr', or a custom 3x3 matrix (e.g. provided by the forward transform when 'pca' is selected)\n%\n% 'opp' opponent color space ('opp' is equirange version)\n% 'yCbCr' standard yCbCr (e.g. for JPEG images)\n%\n% OUTPUTS:\n% x is RGB image (with range [0 1]^3)\n%\n%\n% NOTE: 'opp' is used by default if no colormode is specified\n%\n\nif nargin==1\n colormode='opp';\nend\nif size(colormode)==[3 3]\n A=colormode;\n B=inv(A);\nelse\n if strcmp(colormode,'opp')\n A =[1/3 1/3 1/3; 0.5 0 -0.5; 0.25 -0.5 0.25];\n B =[1 1 2/3;1 0 -4/3;1 -1 2/3];\n end\n if strcmp(colormode,'yCbCr')\n A=[0.299 0.587 0.114; -0.16873660714285 -0.33126339285715 0.5; 0.5 -0.4186875 -0.0813125];\n B=inv(A);\n end\nend\n\n%%%% Make sure that each channel's intensity range is [0,1]\nmaxV = sum(A.*(A>0),2);\nminV = sum(A.*(A<0),2);\nxNormal = reshape(x,[size(x,1)*size(x,2) 3]) * diag(maxV-minV) + repmat(minV, [1 size(x,1)*size(x,2)])'; % put in range [0,1]\nyRGB = reshape(xNormal * B', [ size(x,1) size(x,2) 3]);\n\nreturn;\n\n", "meta": {"author": "xialeiliu", "repo": "RankIQA", "sha": "22ca65cd0156b5b428cecd55ed939366fb64d2e5", "save_path": "github-repos/MATLAB/xialeiliu-RankIQA", "path": "github-repos/MATLAB/xialeiliu-RankIQA/RankIQA-22ca65cd0156b5b428cecd55ed939366fb64d2e5/data/rank_tid2013/BM3D/CBM3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3882601057423013}}
{"text": "function [dStates, contactForces] = dynamics_singleStanceOne(States, Actuators, Parameters)\n% function [dStates, Actuators] = dynamics_singleStanceOne(States, Actuators, Parameters)\n%\n% Computer Generated File -- DO NOT EDIT \n%\n% This function was created by the function Write_ContinuousDynamics()\n% 10-Dec-2013 19:40:47\n%\n% Dymanics Model: retractable double pendulum biped\n% Motion Phase: Single Stance One\n%\n% Matthew Kelly \n% Cornell University \n% \n\nx = States(1,:); % (m) Foot One horizontal position\ny = States(2,:); % (m) Foot One vertical position\nth1 = States(3,:); % (rad) Leg One absolute angle\nth2 = States(4,:); % (rad) Leg Two absolute angle\nL1 = States(5,:); % (m) Leg One length\nL2 = States(6,:); % (m) Leg Two length\ndx = States(7,:); % (m/s) Foot One horizontal velocity\ndy = States(8,:); % (m/s) Foot One vertical velocity\ndth1 = States(9,:); % (rad/s) Leg One absolute angular rate\ndth2 = States(10,:); % (rad/s) Leg Two absolute angular rate\ndL1 = States(11,:); % (m/s) Leg One extension rate\ndL2 = States(12,:); % (m/s) Leg Two extensioin rate\n\nF1 = Actuators(1,:); % (N) Compresive axial force in Leg One\nF2 = Actuators(2,:); % (N) Compresive axial force in Leg Two\nT1 = Actuators(3,:); % (Nm) External torque applied to Leg One\nT2 = 0; %Foot Two not in contact with ground!\nThip = Actuators(5,:); % (Nm) Torque acting on Leg Two from Leg One\n\nm1 = Parameters.m1; % (kg) Foot One mass\nm2 = Parameters.m2; % (kg) Foot Two mass\nM = Parameters.M; % (kg) Hip mass\ng = Parameters.g; % (m/s^2) Gravity\n\n% Constraints for this phase: \nddx = 0; %(m) Foot One horizontal position\nddy = 0; %(m) Foot One vertical position\nH2 = 0; %(N) Foot Two, horizontal contact force\nV2 = 0; %(N) Foot Two, vertical contact force\n\ndStates = zeros(size(States));\ndStates(1:6,:) = States((1+6):(6+6),:);\ndStates(7,:) = zeros(1,size(States,2));\ndStates(8,:) = zeros(1,size(States,2));\ndStates(9,:) = -(L2.*Thip - L2.*T1 + L1.*T2.*cos(th1 - th2) + L1.*Thip.*cos(th1 - th2) - F2.*L1.*L2.*sin(th1 - th2) + 2.*L1.*L2.*M.*dL1.*dth1 + L1.*L2.*M.*ddy.*cos(th1) + L1.*L2.*M.*g.*cos(th1) - L1.*L2.*M.*ddx.*sin(th1))./(L1.^2.*L2.*M);\ndStates(10,:) = (L1.*M.*T2 + L1.*M.*Thip - L2.*T1.*m2.*cos(th1 - th2) + L2.*Thip.*m2.*cos(th1 - th2) + L1.*T2.*m2.*cos(th1 - th2).^2 + L1.*Thip.*m2.*cos(th1 - th2).^2 + L1.*T2.*m2.*sin(th1 - th2).^2 + L1.*Thip.*m2.*sin(th1 - th2).^2 + L1.*L2.*M.*V2.*cos(th2) - H2.*L1.*L2.*M.*sin(th2) - F1.*L1.*L2.*m2.*sin(th1 - th2) - 2.*L1.*L2.*M.*dL2.*dth2.*m2 - L1.*L2.*M.*ddy.*m2.*cos(th2) - L1.*L2.*M.*g.*m2.*cos(th2) + L1.*L2.*M.*ddx.*m2.*sin(th2) - L1.*L2.*M.*ddx.*m2.*cos(th1 - th2).*sin(th1) + L1.*L2.*M.*ddx.*m2.*sin(th1 - th2).*cos(th1) + L1.*L2.*M.*ddy.*m2.*sin(th1 - th2).*sin(th1) + L1.*L2.*M.*g.*m2.*sin(th1 - th2).*sin(th1) + L1.*L2.*M.*ddy.*m2.*cos(th1 - th2).*cos(th1) + L1.*L2.*M.*g.*m2.*cos(th1 - th2).*cos(th1))./(L1.*L2.^2.*M.*m2);\ndStates(11,:) = -(T2.*sin(th1 - th2) + Thip.*sin(th1 - th2) - F1.*L2 + F2.*L2.*cos(th1 - th2) - L1.*L2.*M.*dth1.^2 + L2.*M.*ddx.*cos(th1) + L2.*M.*ddy.*sin(th1) + L2.*M.*g.*sin(th1))./(L2.*M);\ndStates(12,:) = (T1.*m2.*sin(th1 - th2) - Thip.*m2.*sin(th1 - th2) + F2.*L1.*M + H2.*L1.*M.*cos(th2) + L1.*M.*V2.*sin(th2) - F1.*L1.*m2.*cos(th1 - th2) + F2.*L1.*m2.*cos(th1 - th2).^2 + F2.*L1.*m2.*sin(th1 - th2).^2 + L1.*L2.*M.*dth2.^2.*m2 - L1.*M.*ddx.*m2.*cos(th2) - L1.*M.*ddy.*m2.*sin(th2) - L1.*M.*g.*m2.*sin(th2) + L1.*M.*ddx.*m2.*cos(th1 - th2).*cos(th1) + L1.*M.*ddy.*m2.*cos(th1 - th2).*sin(th1) - L1.*M.*ddy.*m2.*sin(th1 - th2).*cos(th1) + L1.*M.*g.*m2.*cos(th1 - th2).*sin(th1) - L1.*M.*g.*m2.*sin(th1 - th2).*cos(th1) + L1.*M.*ddx.*m2.*sin(th1 - th2).*sin(th1))./(L1.*M.*m2);\n\n% contactForces(1,:) == H1 == (N) Foot One, horizontal contact force\n% contactForces(2,:) == V1 == (N) Foot One, vertical contact force\n% contactForces(3,:) == H2 == (N) Foot Two, horizontal contact force\n% contactForces(4,:) == V2 == (N) Foot Two, vertical contact force\ncontactForces = zeros(4,size(States,2));\ncontactForces(1,:) = (Thip.*sin(th1) - T1.*sin(th1) + L1.*ddx.*m1 + F1.*L1.*cos(th1))./L1;\ncontactForces(2,:) = (T1.*cos(th1) - Thip.*cos(th1) + L1.*ddy.*m1 + L1.*g.*m1 + F1.*L1.*sin(th1))./L1;\ncontactForces(3,:) = zeros(1,size(States,2));\ncontactForces(4,:) = zeros(1,size(States,2));\n\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/FancyDoublePendulum/Polar/computerGeneratedCode/dynamics_singleStanceOne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.4804786780479071, "lm_q1q2_score": 0.3882590665416875}}
{"text": "function [fig_name_tca]=ps_mean_v(ifg_list,n_boot,subtract_switches,use_small_baselines,aps_flag)\n%PS_MEAN_V Calculate mean velocities and their standard deviations\n% PS_MEAN_V(IFG_LIST,N_BOOT,SUBTRACT_SWITCHES) where IFG_LIST gives indices \n% of interferograms to be included in the calculation,N_BOOT specifies number \n% of bootstrap iterations and RAMP_FLAG is 1 to subtract orbital ramps\n%\n% Andy Hooper, Jan 2008\n%\n% ======================================================================\n% 06/2009 AH: Subtract orbital ramp if present\n% 06/2009 AH: Process smaller chunks to reduce memory needs\n% 02/2010 AH: Revert to v3.1 version\n% 02/2010 AH: Replace unwrap_ifg_index with drop_ifg_index\n% 03/2010 AH: 3rd input changed to 'subtract_switches'\n% 03/2010 AH: Use small baselines option added\n% 03/2010 AH: var/cov added to inversion\n% 05/2010 AH: Include master if there are not ifgs before and after\n% 06/2010 AH: small change to ps_mean_v.m\n% 03/2014 AH: -a etc added\n% 04/2014 DB: fix fig_name_tca output in case no aps correction\n% 05/2014 DB: Fix v-doa to v-dao \n% 05/2014 DB: For APS related corrections include deramping on the fly\n% 05/2014 DB: big fix in case of a nan \n% 07/2014 EH: Fix for nanmean in case of single element compared to vector\n% 03/2015 DB: Do all deramping on the fly, make consistent for TRAIN release\n% 05/2017 DB: use stamps save to save larger variables than 2GB.\n% 06/2017 DB: Include the option to choose between chol decompostion for\n% bootstrapping (not to invert covariance often), or conventional\n% bootstrapping requiring to invert covariance matrix for each iteration.\n% ======================================================================\n\n\nfprintf('Calculating standard deviation of mean velocity...\\n')\n\n\nchol_flag = 'n';\n\nif nargin<1\n ifg_list=[];\nend\nif nargin<2\n n_boot=100;\nend\n\nif nargin<3 | isempty(subtract_switches)\n subtract_switches='';\nend\n\nif nargin<4\n use_small_baselines=0;\nend\n\nif nargin<5\n aps_flag=1;\nend\n\nload psver\npsname=['./ps',num2str(psver)];\nphuwname=['./phuw',num2str(psver)];\nphuwsbresname=['./phuw_sb_res',num2str(psver)];\nifgstdname=['./ifgstd',num2str(psver)];\nsclaname=['./scla',num2str(psver)];\napsname=['./tca',num2str(psver)];\ntidename=['./tide',num2str(psver)];\n\nmvname=['mv',num2str(psver)];\n\nps=load(psname);\n\ndrop_ifg_index=getparm('drop_ifg_index');\nfig_name_tca = '';\nif strcmpi(getparm('small_baseline_flag'),'y')\n if use_small_baselines==0\n phuw=load(phuwname,'unwrap_ifg_index_sm');\n if isfield(phuw,'unwrap_ifg_index_sm');\n unwrap_ifg_index=phuw.unwrap_ifg_index_sm;\n else\n unwrap_ifg_index=[1:ps.n_image];\n end\n phuwres=load(phuwsbresname,'sm_cov');\n if isfield(phuwres,'sm_cov');\n ifg_cov=phuwres.sm_cov;\n else\n ifg_cov=eye(ps.n_image);\n end\n else\n unwrap_ifg_index=setdiff([1:ps.n_ifg],drop_ifg_index);\n phuwname=['./phuw_sb',num2str(psver)];\n sclaname=['./scla_sb',num2str(psver)];\n apsname=['./tca_sb',num2str(psver)];\n tidename=['./tide_sb',num2str(psver)];\n\n phuwres=load(phuwsbresname,'sb_cov');\n if isfield(phuwres,'sb_cov');\n ifg_cov=phuwres.sb_cov;\n else\n ifg_cov=eye(ps.n_ifg);\n end\n end\nelse\n use_small_baselines=0;\n unwrap_ifg_index=setdiff([1:ps.n_ifg],drop_ifg_index);\n if ~exist([ifgstdname,'.mat'],'file')\n ifg_cov=eye(ps.n_ifg);\n else ifgstd=load(ifgstdname);\n if isfield(ifgstd,'ifg_std');\n ifgvar=(ifgstd.ifg_std*pi/181).^2;\n ifg_cov=diag(ifgvar);\n else\n ifg_cov=eye(ps.n_ifg);\n end\n end\nend\n\n\n\nuw=load(phuwname);\nph_uw=uw.ph_uw;\nclear uw\n\n\nswitch(subtract_switches)\ncase('')\ncase('d')\n scla=load(sclaname);\n ph_uw=ph_uw - scla.ph_scla;\n clear scla\ncase('o')\n [ph_uw] = ps_deramp(ps,ph_uw);\ncase('a')\n aps=load(apsname);\n [aps_corr,fig_name_tca] = ps_plot_tca(aps,aps_flag);\n ph_uw=ph_uw - aps_corr;\n clear aps aps_corr\ncase('ao')\n aps=load(apsname);\n [aps_corr,fig_name_tca] = ps_plot_tca(aps,aps_flag);\n ph_uw=ph_uw - aps_corr;\n [ph_uw] = ps_deramp(ps,ph_uw);\n clear aps aps_corr\ncase('do')\n scla=load(sclaname);\n ph_uw=ph_uw - scla.ph_scla;\n [ph_uw] = ps_deramp(ps,ph_uw);\ncase('da')\n scla=load(sclaname);\n ph_uw=ph_uw - scla.ph_scla;\n clear scla\n aps=load(apsname);\n [aps_corr,fig_name_tca] = ps_plot_tca(aps,aps_flag);\n ph_uw=ph_uw - aps_corr;\n clear aps aps_corr\ncase('dat')\n tide=load(tidename);\n scla=load(sclaname);\n ph_uw=ph_uw - scla.ph_scla;\n clear scla\n aps=load(apsname);\n [aps_corr,fig_name_tca] = ps_plot_tca(aps,aps_flag);\n ph_uw=ph_uw - aps_corr-tide.ph_tide;\n clear aps aps_corr\ncase('dao')\n scla=load(sclaname);\n ph_uw=ph_uw - scla.ph_scla ;\n [ph_uw] = ps_deramp(ps,ph_uw);\n aps=load(apsname);\n [aps_corr,fig_name_tca] = ps_plot_tca(aps,aps_flag);\n ph_uw=ph_uw - aps_corr;\n clear aps aps_corr\notherwise\n error('unknown subtract flags')\nend\n\nif use_small_baselines==0 \n %AH2CHECK %%%%%%% & unwrap_ifg_index(1)~=ps.master_ix & unwrap_ifg_index(end)~=ps.master_ix\n unwrap_ifg_index=setdiff(unwrap_ifg_index,ps.master_ix);\nend\n\nph_all=zeros(ps.n_ps,1);\nref_ps=ps_setref;\nif ~isempty(ifg_list)\n unwrap_ifg_index=intersect(unwrap_ifg_index,ifg_list);\n ifg_list=[];\nend\nph_uw=ph_uw(:,unwrap_ifg_index);\nifg_cov=ifg_cov(unwrap_ifg_index,unwrap_ifg_index);\nif rank(ifg_cov)0\n if sum(ix_non_nan)== length(ix_non_nan)\n [mean_v_dist,boot_ix] = bootstrp(n_boot, @(x) single(lscov(G(x,:),ph_bit(x,:))), [1:N]);\n temp = std(mean_v_dist(:,2:2:end))';\n else\n [mean_v_dist_temp,boot_ix] = bootstrp(n_boot, @(x) single(lscov(G(x,:),ph_bit(x,ix_non_nan))), [1:N]);\n temp = NaN([size(ph_bit,2) 1]); \n temp(ix_non_nan) = std(mean_v_dist_temp(:,2:2:end))';\n clear mean_v_dist_temp\n end\n mean_v_std(i:i_end) =temp; \n end\n i=i+n;\n fprintf('%d PS processed\\n',i-1)\n end\n \n \nelse\n % conventional bootstrapping where the coveriance matrix is inverted on\n % each set PS segments.\n while i0\n if sum(ix_non_nan)== length(ix_non_nan)\n [mean_v_dist,boot_ix] = bootstrp(n_boot, @(x) single(lscov(G(x,:),ph_bit(x,:),ifg_cov)), [1:N]);\n temp = std(mean_v_dist(:,2:2:end))';\n else\n fprintf('test\\n')\n [mean_v_dist_temp,boot_ix] = bootstrp(n_boot, @(x) single(lscov(G(x,:),ph_bit(x,ix_non_nan),ifg_cov(ix_non_nan,ix_non_nan))), [1:N]);\n temp = NaN([size(ph_bit,2) 1]); \n temp(ix_non_nan) = std(mean_v_dist_temp(:,2:2:end))';\n clear mean_v_dist_temp\n end\n mean_v_std(i:i_end) =temp; \n end\n i=i+n;\n fprintf('%d PS processed\\n',i-1)\n end\nend\n\nstamps_save(mvname,n_boot,subtract_switches,mean_v,mean_v_std)\n\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/ps_mean_v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3878769457403568}}
{"text": "function Y = TT_weingarten(V, Z, ind)\n% Weingarten map computation for the fixed TT-rank manifold.\n%\n% NOTE: this manifold requires the use of a modified version of TTeMPS_1.1,\n% which is packaced with Manopt and can be found in \n% manopt/manopt/manifolds/ttfixedrank/TTeMPS_1.1\n% \n% Y = TT_weingarten(V, Z, ind)\n% \n% This function implements the efficient way of computing the Weingarten\n% map for the Riemannian submanifold of fixed TT-rank tensors embedded in\n% its natural embedding Euclidean space, as described in the paper:\n%\n% Psenka and Boumal,\n% Second-order optimization for tensors with fixed tensor-train rank,\n% Optimization workshop at NeurIPS 2020.\n% \n% Y is the output tangent vector, V is a tangent vector (which contains\n% needed information of base point X), Z is a tensor (embedding space).\n% \n% TT_weingarten supports the following formats for Z:\n% 1) Full\n% 2) TT-format (any rank)\n% 3) sparse, with non-zero indices indexed by ind (see fixedTTrankfactory).\n%\n% See also: fixedTTrankfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Michael Psenka, Nov. 24, 2020.\n% Contributors: Nicolas Boumal\n% Change log:\n\n % Preliminary tangent vector set-up for Y\n d = V.order;\n r = V.rank;\n n = V.size;\n \n\n Y = V; % all properties except for dU cores inherited from V\n normV = norm(V);\n V = (1 / normV) * V;\n Y.dU = cell(1, d);\n\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Begin calculating variational components\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % Pre-calculate all R-components as needed for tangent space conversion\n R = cell(1, d-1);\n % Intermediary used to calculate R-terms for re-orthogonalization\n Xr = V.U;\n\n for k = d:-1:2\n\n sz = size(Xr{k});\n\n if length(sz) == 2\n sz = [sz, 1]; %#ok\n end\n\n [Q, R{k - 1}] = qr_unique(unfold(Xr{k}, 'right')');\n Xr{k} = reshape(Q', [size(Q, 2), sz(2), sz(3)]);\n\n Xr{k - 1} = tensorprod_ttemps(Xr{k - 1}, R{k - 1}, 3);\n end\n\n % Calculate V.dU under the original parametrization of tangent space\n\n dUR = cell(1, d);\n\n for k = 1:(d - 1)\n dUR{k} = unfold(V.dU{k}, 'left') / R{k}';\n dUR{k} = reshape(dUR{k}, [r(k), n(k), r(k + 1)]);\n end\n\n dUR{d} = V.dU{d};\n\n % Calculate ~X^tV_{\\ge k} efficiently\n XtVg = cell(1, d);\n\n XtVg{d} = conj(unfold(V.V{d}, 'right')) * unfold(V.dU{d}, 'right').';\n XtVgTmp = conj(unfold(V.V{d}, 'right')) * unfold(V.U{d}, 'right').';\n\n for k = (d - 1):-1:2\n tmp = tensorprod_ttemps(V.V{k}, XtVg{k + 1}', 3);\n XtVg{k} = conj(unfold(tmp, 'right')) * unfold(V.U{k}, 'right').';\n\n tmp2 = tensorprod_ttemps(V.V{k}, XtVgTmp', 3);\n XtVg{k} = XtVg{k} + conj(unfold(tmp2, 'right')) * unfold(dUR{k}, 'right').';\n XtVgTmp = conj(unfold(tmp2, 'right')) * unfold(V.U{k}, 'right').';\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CASES FOR TYPE OF EUCLIDEAN GRADIENT Z %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if isa(Z, 'TTeMPS') || isa(Z, 'TTeMPS_tangent_orth')% Z either TT-tensor or tangent vec\n\n if isa(Z, 'TTeMPS_tangent_orth')\n Z = tangent_to_TTeMPS(Z); % efficient to treat both as TTeMPS case\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%% DIAGONAL TERMS %%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n ZVr = cell(1, d); % stores values of V_<^T(Z)\n Zr = cell(1, d); % stores values of X_<^T(Z)\n ZVl = cell(1, d); % stores values of (Z)^T(V_>)\n Zl = cell(1, d); % stores values of (Z)^T(X_>)\n\n\n ZVr{d} = conj(unfold(Z.U{d}, 'right')) * unfold(V.dU{d}, 'right').';\n XtVgTmp = conj(unfold(Z.U{d}, 'right')) * unfold(V.U{d}, 'right').';\n\n for k = (d - 1):-1:2\n tmp = tensorprod_ttemps(Z.U{k}, ZVr{k + 1}', 3);\n ZVr{k} = conj(unfold(tmp, 'right')) * unfold(V.U{k}, 'right').';\n\n tmp2 = tensorprod_ttemps(Z.U{k}, XtVgTmp', 3);\n ZVr{k} = ZVr{k} + conj(unfold(tmp2, 'right')) * unfold(dUR{k}, 'right').';\n XtVgTmp = conj(unfold(tmp2, 'right')) * unfold(V.U{k}, 'right').';\n end\n\n for k=1:d\n ZVr{k} = ZVr{k}';\n end\n \n\n Zr{d} = conj(unfold(V.V{d}, 'right')) * unfold(Z.U{d}, 'right').';\n\n for k = (d - 1):-1:2\n tmp = tensorprod_ttemps(V.V{k}, Zr{k + 1}', 3);\n Zr{k} = conj(unfold(tmp, 'right')) * unfold(Z.U{k}, 'right').';\n end\n\n % Computation of ZVl and Zl\n\n ZVl{1} = unfold(dUR{1}, 'left')' * unfold(Z.U{1}, 'left');\n Zl{1} = unfold(V.U{1}, 'left')' * unfold(Z.U{1}, 'left');\n\n for k = 2:(d - 1)\n % (V_k-1)(U_k)\n tmp = tensorprod_ttemps(V.U{k}, ZVl{k - 1}', 1);\n ZVl{k} = unfold(tmp, 'left')' * unfold(Z.U{k}, 'left');\n % + (X_k-1)(dU_k)\n tmp = tensorprod_ttemps(dUR{k}, Zl{k - 1}', 1);\n ZVl{k} = ZVl{k} + unfold(tmp, 'left')' * unfold(Z.U{k}, 'left');\n % update Zr to keep up w/ recursive definition\n tmp = tensorprod_ttemps(V.U{k}, Zl{k - 1}', 1);\n Zl{k} = unfold(tmp, 'left')' * unfold(Z.U{k}, 'left');\n end\n\n ZZ = cell(1, d); % final cores for normal (I \\otimes X)Z(X^T)\n Zv = cell(1, d); % final cores for (I \\otimes X)Z(V^T)\n vZ = cell(1, d); % final cores for (I \\otimes V)Z(X^T)\n\n\n % contract to first core\n ZZ{1} = tensorprod_ttemps(Z.U{1}, Zr{2}, 3);\n % contract to inner cores\n for k = 2:(d - 1)\n res = tensorprod_ttemps(Z.U{k}, Zl{k - 1}, 1);\n ZZ{k} = tensorprod_ttemps(res, Zr{k + 1}, 3);\n end\n\n % contract to last core\n ZZ{d} = tensorprod_ttemps(Z.U{d}, Zl{d - 1}, 1);\n\n Zv{1} = tensorprod_ttemps(Z.U{1}, ZVr{2}, 3);\n\n for k = 2:(d - 1)\n res = tensorprod_ttemps(Z.U{k}, Zl{k - 1}, 1);\n Zv{k} = tensorprod_ttemps(res, ZVr{k + 1}, 3);\n end\n\n Zv{d} = tensorprod_ttemps(Z.U{d}, Zl{d - 1}, 1);\n\n\n vZ{1} = tensorprod_ttemps(Z.U{1}, Zr{2}, 3);\n\n for k = 2:(d - 1)\n res = tensorprod_ttemps(Z.U{k}, ZVl{k - 1}, 1);\n vZ{k} = tensorprod_ttemps(res, Zr{k + 1}, 3);\n end\n\n vZ{d} = tensorprod_ttemps(Z.U{d}, ZVl{d - 1}, 1);\n\n % Left unfold everything to apply additional operations\n for k = 1:d\n ZZ{k} = unfold(ZZ{k}, 'left');\n Zv{k} = unfold(Zv{k}, 'left');\n vZ{k} = unfold(vZ{k}, 'left');\n end\n % %%%%%%%%%%%%%%%%%%%%%%%%% TESTING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n % 1st and last cases special, so they're computed outside the loop\n UL = unfold(V.U{1}, 'left');\n dUL = unfold(dUR{1}, 'left');\n\n % right variational term without (I - UU^T) projection\n rightV = (Zv{1} - ZZ{1} * XtVg{2}) / R{1};\n\n Y.dU{1} = -dUL * UL' * ZZ{1} + rightV - UL * (UL' * rightV);\n\n for k = 2:(d - 1)\n UL = unfold(V.U{k}, 'left');\n dUL = unfold(dUR{k}, 'left');\n\n % right variational term without (I - UU^T) projection\n rightV = (Zv{k} - ZZ{k} * XtVg{k + 1}) / R{k};\n\n Y.dU{k} = vZ{k} - UL * (UL' * vZ{k}) - dUL * UL' * ZZ{k} ...\n + rightV - UL * (UL' * rightV);\n end\n\n Y.dU{d} = vZ{d};\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%% CROSS TERMS %%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n for k = 1:(d - 1)\n U = unfold(V.U{k}, 'left');\n ZZ{k} = ZZ{k} - U * (U' * ZZ{k});\n ZZ{k} = reshape(ZZ{k}, [r(k), n(k), r(k + 1)]);\n end\n\n ZZ{d} = reshape(ZZ{d}, [r(d), n(d), 1]);\n\n % Double loop to represent P_k DP_m, 1 <= k < d\n for k = 1:(d - 1)\n\n UL = unfold(V.U{k}, 'left');\n dUL = unfold(dUR{k}, 'left');\n\n for m = 1:(k - 1)\n VtZ = crossTermVariational(k, m, ZZ, dUR{m}, V);\n projUVtZ = VtZ - UL * (UL' * VtZ);\n\n Y.dU{k} = Y.dU{k} - projUVtZ;\n end\n\n for m = (k + 1):d\n ZtX = crossTermMatrixRight(k + 1, m, ZZ, V);\n Y.dU{k} = Y.dU{k} + dUL * ZtX;\n end\n\n end\n\n % Final terms for k = d\n for m = 1:(d - 1)\n VtZ = crossTermVariational(d, m, ZZ, dUR{m}, V);\n Y.dU{d} = Y.dU{d} - VtZ;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%FINAL RESHAPE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n for k = 1:d\n Y.dU{k} = reshape(Y.dU{k}, [r(k), n(k), r(k + 1)]);\n end\n\n elseif ~exist('ind', 'var')% Z is a full array\n\n %{\n Note that you can split up the full expression for the Weingarten map in\n the following way:\n\n 1) Diagonal terms(P_i DP_i terms, or non - cross terms)\n a) This can be split into(left variational) + (right variational),\n which correspond to two terms in product rule expansion\n 2) Cross terms(P_i DP_j, we show mathematically equivalent expression\n in companion paper.)\n a) This likewise can be split into(i < j) + (i > j)\n %}\n\n % Cell that represents the LEFT VARIATIONAL SIDE\n Zv = cell(1, d);\n % Cell that represents the RIGHT VARIATIONAL SIDE\n vZ = cell(1, d);\n\n % Initialization step\n Zv{d} = Z(:);\n vZ{d} = Z(:);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%% DIAGONAL TERMS %%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%% LEFT VARIATIONAL %%%%%%%%%%%%%%%%%%\n\n % First, calculate where the right side is the variational matrix\n % Note that the calculation here is split between VR^-1 and XX^tVR^-1\n % in (I - XX^t)VR^{-1} through xx and xx2 terms respectively\n\n % (d-1) term done separately to initialize the temp variable handoff\n zz = reshape(Z, [prod(n(1:(d - 1))), n(d)]);\n xx = transpose(unfold(V.dU{d}, 'right'));\n xxTmp = transpose(unfold(V.U{d}, 'right')); % temp var to help calc xx terms\n xx2 = transpose(unfold(V.V{d}, 'right'));\n\n % Z-matrix-k-variational, represents the xx calculation for Zv{k}\n Zmkv = zz * xx;\n vZ{d - 1} = zz * xx2;\n Zv{d - 1} = (Zmkv - vZ{d - 1} * XtVg{d}) / R{d - 1};\n\n % auxillery term for computing anything with variational matrix\n ZZtmp = zz * xxTmp;\n\n % Main calcualtion for right size of Zv\n for k = (d - 2):-1:1\n zz = reshape(Zmkv, [prod(n(1:k)), n(k + 1) * r(k + 2)]);\n xx = transpose(unfold(V.U{k + 1}, 'right'));\n Zmkv = zz * xx;\n\n zzTmp = reshape(ZZtmp, [prod(n(1:k)), n(k + 1) * r(k + 2)]);\n xxTmp = transpose(unfold(dUR{k + 1}, 'right'));\n Zmkv = Zmkv + zzTmp * xxTmp;\n ZZtmp = zzTmp * xx;\n\n % NOTE: vZ is only used here to store these values for later use\n % It stores the standard right side calc for the orthogonal projector\n zz2 = reshape(vZ{k + 1}, [prod(n(1:k)), n(k + 1) * r(k + 2)]);\n xx2 = transpose(unfold(V.V{k + 1}, 'right'));\n vZ{k} = zz2 * xx2;\n\n Zv{k} = (Zmkv - vZ{k} * XtVg{k + 1}) / R{k};\n end\n\n % Standard left side calculations for Zv\n for k = 2:d\n\n for i = 1:(k - 1)\n Z_i = reshape(Zv{k}, [r(i) * n(i), prod(n(i + 1:k)) * r(k + 1)]);\n X_i = unfold(V.U{i}, 'left');\n Zm = X_i' * Z_i;\n Zv{k} = Zm;\n end\n\n Zv{k} = reshape(Zv{k}, [r(k) * n(k), r(k + 1)]);\n end\n\n % Final U core projector mult for Zv\n for k = 1:(d - 1)\n U = unfold(V.U{k}, 'left');\n Zv{k} = Zv{k} - U * (U' * Zv{k});\n end\n\n %%%%%%%%%%%%%%% RIGHT VARIATIONAL %%%%%%%%%%%%%%%%%%\n\n % represents standard projection, also needed as intermediary for this section\n ZZ = vZ;\n % Start left side calculation for vZ\n for k = 2:d\n\n % Do first in loop separately to initialize intermediary variable\n Z_i = reshape(vZ{k}, [n(1), prod(n(2:k)) * r(k + 1)]);\n dU_i = unfold(dUR{1}, 'left');\n Zm = dU_i' * Z_i;\n vZ{k} = Zm;\n\n X_i = unfold(V.U{1}, 'left');\n ZZ{k} = X_i' * Z_i;\n\n for m = 2:(k - 1)\n Z_i = reshape(vZ{k}, [r(m) * n(m), prod(n(m + 1:k)) * r(k + 1)]);\n X_i = unfold(V.U{m}, 'left');\n Zm = X_i' * Z_i;\n\n Z_tmp = reshape(ZZ{k}, [r(m) * prod(n(m)), prod(n(m + 1:k)) * r(k + 1)]);\n dU_i = unfold(dUR{m}, 'left');\n\n vZ{k} = Zm + dU_i' * Z_tmp;\n\n ZZ{k} = X_i' * Z_tmp;\n end\n\n vZ{k} = reshape(vZ{k}, [r(k) * n(k), r(k + 1)]);\n ZZ{k} = reshape(ZZ{k}, [r(k) * n(k), r(k + 1)]);\n end\n\n % Final U core projector mult for vZ\n\n % 1st core separate since vZ{1} = 0 up until now. Purely for efficiency\n U = unfold(V.U{1}, 'left');\n dU = unfold(V.dU{1}, 'left');\n vZ{1} = -dU * U' * ZZ{1};\n\n for k = 2:(d - 1)\n U = unfold(V.U{k}, 'left');\n dU = unfold(V.dU{k}, 'left');\n vZ{k} = vZ{k} - U * (U' * vZ{k});\n\n vZ{k} = vZ{k} - dU * U' * ZZ{k};\n\n end\n\n for k = 1:d - 1\n Y.dU{k} = Zv{k} + vZ{k};\n end\n\n Y.dU{d} = vZ{d};\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%% CROSS TERMS %%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n for k = 1:(d - 1)\n % now only need ZZ as dU cores of normal projection of V\n U = unfold(V.U{k}, 'left');\n ZZ{k} = ZZ{k} - U * (U' * ZZ{k});\n ZZ{k} = reshape(ZZ{k}, [r(k), n(k), r(k + 1)]);\n end\n\n ZZ{d} = reshape(ZZ{d}, [r(d), n(d), 1]);\n\n % Double loop to represent P_k DP_m, 1 <= k < d\n for k = 1:(d - 1)\n\n UL = unfold(V.U{k}, 'left');\n dUL = unfold(V.dU{k}, 'left');\n\n for m = 1:(k - 1)\n VtZ = crossTermVariational(k, m, ZZ, dUR{m}, V);\n\n projUVtZ = VtZ - UL * (UL' * VtZ);\n\n Y.dU{k} = Y.dU{k} - projUVtZ; \n end\n\n for m = (k + 1):d\n ZtX = crossTermMatrixRight(k + 1, m, ZZ, V);\n Y.dU{k} = Y.dU{k} + dUL * ZtX;\n end\n\n end\n\n % Final terms for k = d\n for m = 1:(d - 1)\n VtZ = crossTermVariational(d, m, ZZ, dUR{m}, V);\n\n Y.dU{d} = Y.dU{d} - VtZ;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FINAL RESHAPE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n for k = 1:d\n Y.dU{k} = reshape(Y.dU{k}, [r(k), n(k), r(k + 1)]);\n end\n\n else\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SPARSE CASE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % permuted U, V, and dU cells for the efficient computation in C\n CU = cell(1, d);\n CV = cell(1, d);\n CdUR = cell(1, d);\n\n for k = 1:d\n CU{k} = permute(V.U{k}, [1 3 2]);\n CV{k} = permute(V.V{k}, [1 3 2]);\n CdUR{k} = permute(dUR{k}, [1 3 2]);\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%% DIAGONAL TERMS %%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n [ZZ, vZ, Zv] = weingarten_omega(n, r, CU, CV, CdUR, ind.', Z);\n\n for k = 1:d\n\n ZZ{k} = reshape(ZZ{k}, [r(k), r(k + 1), n(k)]);\n ZZ{k} = unfold(permute(ZZ{k}, [1 3 2]), 'left');\n\n vZ{k} = reshape(vZ{k}, [r(k), r(k + 1), n(k)]);\n vZ{k} = unfold(permute(vZ{k}, [1 3 2]), 'left');\n\n Zv{k} = reshape(Zv{k}, [r(k), r(k + 1), n(k)]);\n Zv{k} = unfold(permute(Zv{k}, [1 3 2]), 'left');\n end\n\n\n \n\n % 1st and last cases special, so they're computed outside the loop\n UL = unfold(V.U{1}, 'left');\n dUL = unfold(dUR{1}, 'left');\n\n % right variational term without (I - UU^T) projection\n rightV = (Zv{1} - ZZ{1} * XtVg{2}) / R{1};\n Y.dU{1} = -dUL * UL' * ZZ{1} + rightV - UL * (UL' * rightV);\n\n for k = 2:(d - 1)\n UL = unfold(V.U{k}, 'left');\n dUL = unfold(dUR{k}, 'left');\n\n % right variational term without (I - UU^T) projection\n rightV = (Zv{k} - ZZ{k} * XtVg{k + 1}) / R{k};\n Y.dU{k} = vZ{k} - UL * (UL' * vZ{k}) - dUL * UL' * ZZ{k} + rightV - UL * (UL' * rightV);\n % norm(vZ{k} - UL * (UL' * vZ{k}) + (Zv{k} - UL * (UL' * Zv{k})) / R{k}) / norm(V)\n % norm(V)\n end\n\n\n Y.dU{d} = vZ{d};\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%% CROSS TERMS %%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n for k = 1:(d - 1)\n U = unfold(V.U{k}, 'left');\n ZZ{k} = ZZ{k} - U * (U' * ZZ{k});\n ZZ{k} = reshape(ZZ{k}, [r(k), n(k), r(k + 1)]);\n end\n\n ZZ{d} = reshape(ZZ{d}, [r(d), n(d), 1]);\n\n % Double loop to represent P_k DP_m, 1 <= k < d\n for k = 1:(d - 1)\n\n UL = unfold(V.U{k}, 'left');\n dUL = unfold(dUR{k}, 'left');\n\n for m = 1:(k - 1)\n % XtZ = crossTermMatrixLeft(k, m, ZZ, V);\n VtZ = crossTermVariational(k, m, ZZ, dUR{m}, V);\n projUVtZ = VtZ - UL * (UL' * VtZ);\n\n Y.dU{k} = Y.dU{k} - projUVtZ; %+ dUL * XtZ;\n\n % Y.dU{k} = Y.dU{k} - (projUk * kron(eye(n(k)), Vllk') - dUkL * Xlek') * Zkm;\n end\n\n for m = (k + 1):d\n ZtX = crossTermMatrixRight(k + 1, m, ZZ, V);\n Y.dU{k} = Y.dU{k} + dUL * ZtX;\n\n % Y.dU{k} = Y.dU{k} + dUkL * Zkm' * Xg{k+1};\n end\n\n end\n\n % Final terms for k = d\n for m = 1:(d - 1)\n VtZ = crossTermVariational(d, m, ZZ, dUR{m}, V);\n\n Y.dU{d} = Y.dU{d} - VtZ;\n\n % Y.dU{d} = Y.dU{d} - kron(eye(n(d)), Vlld') * Zkm;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%FINAL RESHAPE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n for k = 1:d\n Y.dU{k} = reshape(Y.dU{k}, [r(k), n(k), r(k + 1)]);\n end\n\n Y = (normV) * Y;\n end\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper methods\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Efficient ZtX term for P_k DP_m, m > k\n% Zp here is the projection of Z (just dU cores)\n% V is only passed for access to U and V cores\nfunction ZtX = crossTermMatrixRight(k, m, Zp, V)\n ZtX = conj(unfold(Zp{m}, 'right')) * unfold(V.V{m}, 'right').';\n\n for p = (m - 1):-1:k\n tmp = tensorprod_ttemps(V.U{p}, (ZtX)', 3);\n ZtX = conj(unfold(tmp, 'right')) * unfold(V.V{p}, 'right').';\n end\n\nend\n\n% Efficient XtZ term for P_k DP_m, m < k\n% Zp here is the projection of Z\n% V is only passed for access to U and V cores\nfunction XtZ = crossTermMatrixLeft(k, m, Zp, V) %#ok\n\n XtZ = unfold(V.U{m}, 'left')' * unfold(Zp{m}, 'left');\n\n for p = (m + 1):k\n XtZ = tensorprod_ttemps(V.U{p}, (XtZ)', 1);\n XtZ = unfold(XtZ, 'left')' * unfold(V.V{p}, 'left');\n end\n\nend\n\n% Efficient VtZ (more accurately kron(eye(n(k)), V') * Z) term for P_k DP_m, m < k\n% Zp here is the projection of Z, dURm is normally parametrized dU{m}\n% V is only passed for access to U and V cores\nfunction VtZ = crossTermVariational(k, m, Zp, dURm, V)\n\n VtZ = unfold(dURm, 'left')' * unfold(Zp{m}, 'left');\n\n for p = (m + 1):(k - 1)\n VtZ = tensorprod_ttemps(V.U{p}, (VtZ)', 1);\n VtZ = unfold(VtZ, 'left')' * unfold(V.V{p}, 'left');\n end\n\n VtZ = tensorprod_ttemps(V.V{k}, VtZ, 1);\n VtZ = unfold(VtZ, 'left');\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TT_weingarten.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.38770611331740856}}
{"text": "function [err_N, sG] = ptv_local_nuclear_metric(volfix, voldef, pix_resolution, mask, singular_coefs, P_SZ, norm_type)\n%% todo:\n% * volfix\n% * zero mean, choose std???\n% * making zero mean changes gradient!\n\n% norm_type = 3;\n abs_type = 0;\n deps = 1e-3;\n \n volsz = [size(voldef, 1), size(voldef, 2), size(voldef, 3)];\n Nd = 3;\n if volsz(3) == 1\n Nd = 2;\n end\n \n P_SZ = round(P_SZ);\n Nimgs = size(voldef, 5);\n if Nd == 2\n P_SZ = [P_SZ, 1];\n end\n \n err_N = 0;\n sG = zeros([volsz, Nimgs], 'like', voldef);\n if Nd == 2\n for i1 = 1 : P_SZ(1) : volsz(1)\n for i2 = 1 : P_SZ(2) : volsz(2)\n i11 = min(i1 + P_SZ(1) - 1, volsz(1));\n i22 = min(i2 + P_SZ(2) - 1, volsz(2));\n if i11-i1 < 2 || i22 - i2 < 2\n continue;\n end\n patch = voldef(i1:i11, i2:i22, 1, :, :);\n if norm_type == 1\n patch = patch - sum(sum(sum(patch,1),2),3) / (size(patch,1)*size(patch,2)*size(patch,3));\n elseif norm_type == 2\n patch = patch - mean(patch(:));\n elseif norm_type == 3\n patch = patch - sum(sum( patch, 4), 5) / (size(patch,4)*size(patch,5));\n elseif norm_type == 4\n patch = patch - sum(sum(sum(patch,1),2),3) / (size(patch,1)*size(patch,2)*size(patch,3));\n patch = patch - sum(sum( patch, 4), 5) / (size(patch,4)*size(patch,5));\n end\n \n patch0 = reshape(patch, [size(patch, 1), size(patch, 2), size(patch, 3), Nimgs]);\n if abs_type == 1\n patch = abs(patch);\n elseif abs_type == 2\n patch = sqrt(patch.^2 + deps);\n end\n \n if ~isempty(mask)\n mask_cur = logical(mask(i1:i11, i2:i22));\n else\n mask_cur = [];\n end\n if isempty(mask_cur) || any(mask_cur(:))\n [terr, tgrad] = ptv_nuclear_metric([], patch, pix_resolution, mask_cur, singular_coefs);\n err_N = err_N + terr;\n \n if abs_type == 1\n tgrad = tgrad.*sign(patch0);\n elseif abs_type == 2\n tgrad = tgrad .* patch0 ./ sqrt(patch0.^2 + deps);\n end\n \n if norm_type == 1\n tgrad = tgrad - sum(sum(sum(tgrad, 1), 2), 3) / (size(patch,1)*size(patch,2)*size(patch,3));\n elseif norm_type == 2\n tgrad = tgrad - mean(tgrad(:));\n elseif norm_type == 3\n tgrad = tgrad - sum(sum( tgrad, 4), 5) / (size(patch,4)*size(patch,5));\n elseif norm_type == 4\n tgrad = tgrad - sum(sum( tgrad, 4), 5) / (size(patch,4)*size(patch,5));\n tgrad = tgrad - sum(sum(sum(tgrad, 1), 2), 3) / (size(patch,1)*size(patch,2)*size(patch,3));\n end\n \n sG(i1:i11, i2:i22, 1, :) = tgrad;\n end\n end\n end\n else %3d\n for i1 = 1 : P_SZ(1) : volsz(1)\n for i2 = 1 : P_SZ(2) : volsz(2)\n for i3 = 1 : P_SZ(3) : volsz(3)\n i11 = min(i1 + P_SZ(1) - 1, volsz(1));\n i22 = min(i2 + P_SZ(2) - 1, volsz(2));\n i33 = min(i3 + P_SZ(3) - 1, volsz(3));\n if i11-i1 < 2 || i22 - i2 < 2 || i33 - i3 < 2\n continue;\n end\n patch = voldef(i1:i11, i2:i22, i3:i33, :, :);\n if norm_type == 1\n patch = patch - sum(sum(sum(patch,1),2),3) / (size(patch,1)*size(patch,2)*size(patch,3));\n elseif norm_type == 2\n patch = patch - mean(patch(:));\n elseif norm_type == 3\n patch = patch - sum(sum( patch, 4), 5) / (size(patch,4)*size(patch,5));\n elseif norm_type == 4\n patch = patch - sum(sum(sum(patch,1),2),3) / (size(patch,1)*size(patch,2)*size(patch,3));\n patch = patch - sum(sum( patch, 4), 5) / (size(patch,4)*size(patch,5));\n end\n \n patch0 = reshape(patch, [size(patch, 1), size(patch, 2), size(patch, 3), Nimgs]);\n if abs_type == 1\n patch = abs(patch);\n elseif abs_type == 2\n patch = sqrt(patch.^2 + deps);\n end\n \n if ~isempty(mask)\n mask_cur = logical(mask(i1:i11, i2:i22, i3:i33));\n else\n mask_cur = [];\n end\n if isempty(mask_cur) || any(mask_cur(:))\n [terr, tgrad] = ptv_nuclear_metric([], patch, pix_resolution, mask_cur, singular_coefs);\n err_N = err_N + terr;\n if abs_type == 1\n tgrad = tgrad.*sign(patch0);\n elseif abs_type == 2\n tgrad = tgrad .* patch0 ./ sqrt(patch0.^2 + deps);\n end\n if norm_type == 1\n tgrad = tgrad - sum(sum(sum(tgrad, 1), 2), 3) / (size(patch,1)*size(patch,2)*size(patch,3));\n elseif norm_type == 2\n tgrad = tgrad - mean(tgrad(:));\n elseif norm_type == 3\n tgrad = tgrad - sum(sum( tgrad, 4), 5) / (size(patch,4)*size(patch,5));\n elseif norm_type == 4\n tgrad = tgrad - sum(sum( tgrad, 4), 5) / (size(patch,4)*size(patch,5));\n tgrad = tgrad - sum(sum(sum(tgrad, 1), 2), 3) / (size(patch,1)*size(patch,2)*size(patch,3));\n end\n sG(i1:i11, i2:i22, i3:i33, :) = tgrad;\n end\n end\n end\n end\n end\n err_N = err_N * prod(pix_resolution);\n sG = sG(1:volsz(1), 1:volsz(2), 1:volsz(3), :, :) * prod(pix_resolution);\nend\n\n% function [err_N, sG] = ptv_local_nuclear_metric(volfix, voldef, pix_resolution, mask, singular_coefs, P_SZ)\n% %% todo:\n% % * volfix\n% % * zero mean, choose std???\n% % * making zero mean changes gradient!\n% \n% % P_SZ = [15,15,15];\n% volsz = [size(voldef, 1), size(voldef, 2), size(voldef, 3)];\n% Nd = 3;\n% if volsz(3) == 1\n% Nd = 2;\n% end\n% \n% P_SZ = round(P_SZ);\n% Nimgs = size(voldef, 5);\n% if Nd == 2\n% P_SZ = [P_SZ, 1];\n% end\n% \n% volsz_p = ceil(volsz./P_SZ) .* P_SZ;\n% \n% if Nd == 2\n% volsz_p(3) = 1;\n% end\n% \n% voldef_p = zeros([volsz_p, 1, Nimgs]);\n% voldef_p(1:volsz(1), 1:volsz(2), 1:volsz(3), :, :) = voldef;\n% \n% if ~isempty(mask)\n% if Nd == 3\n% mask_p = zeros([volsz_p]);\n% mask_p(1:volsz(1), 1:volsz(2), 1:volsz(3)) = mask;\n% else\n% mask_p = zeros([volsz_p]);\n% mask_p(1:volsz(1), 1:volsz(2), 1) = mask;\n% end\n% end\n% \n% err_N = 0;\n% sG = zeros([volsz, Nimgs], 'like', voldef);\n% if Nd == 2\n% for i1 = 1 : P_SZ(1) : volsz(1)\n% for i2 = 1 : P_SZ(2) : volsz(2)\n% patch = voldef_p(i1:i1+P_SZ(1)-1, i2:i2+P_SZ(2)-1, 1, :, :);\n% patch = patch - sum(sum(sum(patch,1),2),3) / numel(patch);\n% % patch = patch ./ std(std(std(patch,[],1),[],2),[],3);\n% if ~isempty(mask)\n% mask_cur = logical(mask_p(i1:i1+P_SZ(1)-1, i2:i2+P_SZ(2)-1));\n% else\n% mask_cur = [];\n% end\n% if isempty(mask_cur) || any(mask_cur(:))\n% [terr, tgrad] = ptv_nuclear_metric([], patch, pix_resolution, mask_cur, singular_coefs);\n% err_N = err_N + terr;\n% tgrad = tgrad - sum(sum(sum(tgrad, 1), 2), 3) / numel(patch);\n% sG(i1:i1+P_SZ(1)-1, i2:i2+P_SZ(2)-1, 1, :) = tgrad;\n% end\n% end\n% end\n% else %3d\n% for i1 = 1 : P_SZ(1) : volsz(1)\n% for i2 = 1 : P_SZ(2) : volsz(2)\n% for i3 = 1 : P_SZ(3) : volsz(3)\n% patch = voldef_p(i1:i1+P_SZ(1)-1, i2:i2+P_SZ(2)-1, i3:i3+P_SZ(3)-1, :, :);\n% patch = patch - sum(sum(sum(patch,1),2),3) / numel(patch);\n% if ~isempty(mask)\n% mask_cur = logical(mask_p(i1:i1+P_SZ(1)-1, i2:i2+P_SZ(2)-1, i3:i3+P_SZ(3)-1));\n% else\n% mask_cur = [];\n% end\n% if isempty(mask_cur) || any(mask_cur(:))\n% [terr, tgrad] = ptv_nuclear_metric([], patch, pix_resolution, mask_cur, singular_coefs);\n% err_N = err_N + terr;\n% sG(i1:i1+P_SZ(1)-1, i2:i2+P_SZ(2)-1, i3:i3+P_SZ(3)-1, :) = tgrad;\n% end\n% end\n% end\n% end\n% end\n% err_N = err_N * prod(pix_resolution);\n% sG = sG(1:volsz(1), 1:volsz(2), 1:volsz(3), :, :) * prod(pix_resolution);\n% end", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/ptv/ptv_local_nuclear_metric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3877061133174085}}
{"text": "function significant = spectsignificance(tests,alpha)\n%\n% From a estiamtion of p-values through the specttest function,\n% It returns 0 or 1 for each power of coherence value, if the p-value is\n% below the level of significance 'alpha'. \n%\n% INPUTS: \n%\n% tests The output of specttest, i.e. a cell \n% where each element corresponds to one subject\n% alpha Significance level\n%\n% OUTPUT:\n% \n% significant Struct with 4 fields: lower, higher, lower_corr, higher_corr. \n% ('_corr' reflects to multiple comparisons correction)\n% Each field has a field 'states', just like each\n% element of tests, with fields state(k).psd and \n% state(k).coh containing 1 if the value is\n% significant and 0 otherwise\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford (2017)\n\nif nargin < 2, alpha = 0.01; end\n\nsignificant = struct();\nsignificant.higher = struct();\nsignificant.higher.state = struct();\nsignificant.higher_corr = struct();\nsignificant.higher_corr.state = struct();\nsignificant.lower = struct();\nsignificant.lower.state = struct();\nsignificant.lower_corr = struct();\nsignificant.lower_corr.state = struct();\n\nK = length(tests.higher.state); \nfor k = 1:K\n significant.higher.state(k).psd = tests.higher.state(k).psd < alpha;\n significant.higher_corr.state(k).psd = tests.higher_corr.state(k).psd < alpha;\n significant.lower.state(k).psd = tests.lower.state(k).psd < alpha;\n significant.lower_corr.state(k).psd = tests.lower_corr.state(k).psd < alpha;\n significant.higher.state(k).coh = tests.higher.state(k).coh < alpha;\n significant.higher_corr.state(k).coh = tests.higher_corr.state(k).coh < alpha;\n significant.lower.state(k).coh = tests.lower.state(k).coh < alpha;\n significant.lower_corr.state(k).coh = tests.lower_corr.state(k).coh < alpha;\nend\n\nend", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/utils/testing/spectsignificance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.38764781765068385}}
{"text": "function [a_vec, a_vec_flt] = KiserTMOv(hdrv, filenameOutput, tmo_alpha, tmo_dn_clamping, tmo_white, tmo_gamma, tmo_quality, tmo_video_profile)\n%\n%\n% KiserTMOv(hdrv, filenameOutput, tmo_alpha, tmo_dn_clamping, tmo_white, tmo_gamma, tmo_quality, tmo_video_profile)\n%\n%\n% Input:\n% -hdrv: a HDR video structure; use hdrvread to create a hdrv\n% structure\n% -filenameOutput: output filename (if it has an image extension,\n% single files will be generated)\n% -tmo_alpha: \\alpha_A, \\alpha_B, \\alpha_C coefficients\n% costants in the paper (Equation 3a, 3b, and 3c)\n% -tmo_dn_clamping: a boolean value (0 or 1) for setting black\n% and white levels clamping\n% -tmo_white: white point;\n% -tmo_gamma: gamma for encoding the frame\n% -tmo_quality: the output quality in [1,100]. 100 is the best quality\n% 1 is the lowest quality.%\n% -tmo_video_profile: the compression profile (encoder) for compressing the stream.\n% Please have a look to the profile of VideoWriter from the MATLAB\n% help. Depending on the version of MATLAB some profiles may be not\n% be present.\n%\n% Copyright (C) 2013-17 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% The paper describing this technique is:\n% \"Real-time Automated Tone Mapping System for HDR Video\"\n% \t by Chris Kiser, Erik Reinhard, Mike Tocci and Nora Tocci\n% in IEEE International Conference on Image Processing, 2012 \n%\n%\n\nif(~exist('tmo_alpha', 'var'))\n tmo_alpha = 0.98;\nend\n\nif(~exist('tmo_dn_clamping', 'var'))\n tmo_dn_clamping = 0;\nend\n\nif(~exist('tmo_white', 'var'))\n tmo_white = 1e6;\nend\n\nif(tmo_white <= 0.0)\n tmo_white = 1e6;\nend\n\nif(~exist('tmo_gamma', 'var'))\n tmo_gamma = -2.2;\nend\n\nif(tmo_gamma < 0)\n bsRGB = 1;\nelse\n bsRGB = 0;\nend\n\nif(~exist('tmo_quality', 'var'))\n tmo_quality = 95;\nend\n\nif(~exist('tmo_video_profile', 'var'))\n tmo_video_profile = 'MPEG-4';\nend\n\nname = RemoveExt(filenameOutput);\next = fileExtension(filenameOutput);\n\nbVideo = 0;\nwriterObj = 0;\n\nif(strcmp(ext, 'avi') == 1 | strcmp(ext, 'mp4') == 1)\n bVideo = 1;\n writerObj = VideoWriter(filenameOutput, tmo_video_profile);\n writerObj.FrameRate = hdrv.FrameRate;\n writerObj.Quality = tmo_quality;\n open(writerObj);\nend\n\nhdrv = hdrvopen(hdrv);\n\ndisp('Tone Mapping...');\n\nbeta_clamping = 0.999;\nbeta_clamping_c = (1.0 - beta_clamping);\n\na_vec = [];\na_vec_flt = [];\n\nmaxLprev = 0;\n\nmkdir(name);\n\nfor i=1:hdrv.totalFrames\n disp(['Processing frame ', num2str(i)]);\n [frame, hdrv] = hdrvGetFrame(hdrv, i);\n \n %only physical values\n frame = RemoveSpecials(frame);\n frame(frame < 0) = 0;\n \n if(tmo_dn_clamping)\n %clamp black and white levels\n L = RemoveSpecials(lum(frame));\n %compute CDF's histogram \n [histo, bound, ~] = HistogramHDR(L, 256, 'log10', [], 1); \n histo_cdf = cumsum(histo);\n histo_cdf = histo_cdf/max(histo_cdf(:));\n [~, ind] = min(abs(histo_cdf - beta_clamping));\n maxL = 10^(ind * (bound(2) - bound(1)) / 256 + bound(1));\n\n [~, ind] = min(abs(histo_cdf-beta_clamping_c));\n minL = 10^(ind * (bound(2) - bound(1)) / 256 + bound(1));\n\n frame(frame > maxL) = maxL;\n frame(frame < minL) = minL;\n frame = frame - minL;\n end\n \n %compute statistics for the current frame\n L = lum(frame);\n Lav = logMean(L);\n maxL = max(L(:));\n A = maxL - Lav;\n B = Lav - min(L(:));\n \n if(i == 1)\n maxLprev = maxL;\n Aprev = A;\n Bprev = B;\n aprev = 0.18 * 2^(2 * (B - A) / (A + B));\n end\n \n %leaky integration\n tmo_alpha_c = 1.0 - tmo_alpha;\n An = tmo_alpha_c * Aprev + tmo_alpha * A;\n Aprev = An;\n \n Bn = tmo_alpha_c * Bprev + tmo_alpha * B;\n Bprev = Bn;\n \n a = SceneKey(An, Bn);\n an = tmo_alpha_c * aprev + tmo_alpha * a;\n aprev = an;\n \n %tone mapping\n [frameOut, ~, ~] = ReinhardTMO(frame, an, tmo_white, 'global');\n\n %example\n a_vec = [a_vec, maxL]; \n maxLn = 0.5 * maxLprev + 0.5 *maxL;\n maxLprev = maxLn; \n a_vec_flt = [a_vec_flt, maxLn ]; \n \n %gamma/sRGB encoding\n if(bsRGB)\n frameOut = ClampImg(ConvertRGBtosRGB(frameOut, 0), 0, 1);\n else\n frameOut = ClampImg(GammaTMO(frameOut, tmo_gamma, 0, 0), 0, 1);\n end\n \n if(bVideo)\n writeVideo(writerObj, frameOut);\n else\n imwrite(frameOut, [name, '/frame_', sprintf('%.10d',i), '.', ext]);\n end\n \n %update statistics for the next frame\n Aprev = A;\n Bprev = B;\n aprev = a; \nend\ndisp('OK');\n\nif(bVideo)\n close(writerObj);\nend\n\nhdrvclose(hdrv);\n\nend\n\nfunction a = SceneKey(An, Bn)\n a = 0.18 * 2^(2 * (Bn - An) / (An + Bn));\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo_video/KiserTMOv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.38764781092739353}}
{"text": "function value = r8_mop ( i )\n\n%*****************************************************************************80\n%\n%% R8_MOP returns the I-th power of -1 as an R8 value.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the power of -1.\n%\n% Output, real R8_MOP, the I-th power of -1.\n%\n if ( mod ( i, 2 ) == 0 )\n value = + 1.0;\n else\n value = - 1.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sandia_sparse/r8_mop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.38742231985221404}}
{"text": "function M = callback_blurring( M, dir, options )\n\n% callback_blurring - callback for the deconvolution with wavelets\n%\n% M = callback_blurring( M, dir, options );\n%\n% Copyright (c) 2007 Gabriel Peyre\n\nif isfield(options, 'eta')\n eta = options.eta;\nelse\n eta = 5;\nend\nif isfield(options, 'eta')\n Jmin = options.Jmin;\nelse\n Jmin = 4;\nend\n\nn = sqrt(size(M,1));\nM = reshape(M,n,n);\n\nif dir==1\n % wavelet synthesis and then blurring\n M = perform_wavelet_transform(M, Jmin, -1, options );\n M = perform_blurring( M, eta );\nelse\n % transpose\n M = perform_blurring( M, eta );\n M = perform_wavelet_transform(M, Jmin, 1, options );\nend\n\nM = M(:);", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_sparsity/callback_blurring.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3874223168522451}}
{"text": "classdef chebtech2 < chebtech\n%CHEBTECH2 Approximate smooth functions on [-1,1] with Chebyshev interpolants.\n%\n% Class for approximating smooth functions on the interval [-1,1] using\n% function values at 2nd-kind Chebyshev points and coefficients of the\n% corresponding 1st-kind Chebyshev series expansion.\n%\n% Constructor inputs:\n% CHEBTECH2(OP) constructs a CHEBTECH2 object from the function handle OP. OP\n% should be vectorised (i.e., accept a vector input) and ouput a vector of\n% the same length. CHEBTECH2 objects allow for array-valued construction\n% (i.e., of an array-valued function), in which case OP should accept a column\n% vector of length N and return a matrix of size NxM.\n%\n% CHEBTECH2(OP, DATA) constructs a CHEBTECH2 using the additional data\n% supplied in the DATA structure. Fields currently recognized are:\n% DATA.VSCALE (Default: 0)\n% DATA.HSCALE (Default: 1)\n% The constructor builds a CHEBTECH2 with 'happiness' (see\n% HAPPINESSCHECK.m) relative to the maximum of the given vertical scale\n% DATA.VSCALE and the (column-wise) infinity norm of the sampled\n% function values of OP, and the fixed horizontal scale DATA.HSCALE. If\n% not given (or given as empty), the VSCALE defaults to 0 initially,\n% and HSCALE defaults to 1.\n% If any fields in DATA are empty or not supplied, or if DATA itself is empty\n% or not supplied, appropriate default values are set.\n%\n% CHEBTECH2(OP, DATA, PREF) overrides the default behavior with that given by\n% the preference structure PREF. See CHEBTECH.TECHPREF for details.\n%\n% CHEBTECH2(VALUES, ...) returns a CHEBTECH2 object which interpolates the\n% values in the columns of VALUES at 2nd-kind Chebyshev points and\n% CHEBTECH2({VALUES, COEFFS}, ... ) uses the Chebyshev coefficients passed in\n% COEFFS rather than computing them from VALUES. If VALUES, is empty then the\n% CHEBTECH2 is constructed directly from the COEFFS. If COEFFS are passed,\n% the resulting CHEBTECH2 is always deemed 'happy'.\n%\n% Examples: % Basic construction: f = chebtech2(@(x) sin(x))\n%\n% % Construction with preferences:\n% p.sampleTest = 0; % See CHEBTECH.TECHPREF for details\n% f = chebtech2(@(x) sin(x), [], [], p)\n%\n% % Array-valued construction:\n% f = chebtech2(@(x) [sin(x), cos(x), exp(x)])\n%\n% See also CHEBTECH, CHEBTECH.TECHPREF, CHEBPTS, HAPPINESSCHECK, REFINE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CHEBTECH2 Class Description:\n%\n% The CHEBTECH2 class represents smooth functions on the interval [-1,1] using\n% function values at 2nd-kind Chebyshev points and coefficients of the\n% corresponding 1st-kind Chebyshev series expansion.\n%\n% The constructor is supplied with a handle that evaluates a given function on\n% an increasingly fine Chebyshev 2nd-kind grid (see REFINE.m) until the\n% representation is deemed 'happy' (see HAPPINESSCHECK.m). The resulting object\n% can be used to evaluate and operate on the input function.\n%\n% More information can be found in the CHEBTECH class definition.\n%\n% Class diagram: [<>] <-- [CHEBTECH2]\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS CONSTRUCTOR:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n function obj = chebtech2(op, data, pref)\n % Parse inputs.\n if ( (nargin == 0) || isempty(op) )\n % Return an empty CHEBTECH2 on null input:\n return\n end\n\n if ( (nargin < 2) || isempty(data) )\n data = struct();\n end\n\n if ( (nargin < 3) || isempty(pref) )\n pref = chebtech.techPref();\n else\n pref = chebtech.techPref(pref);\n end\n\n data = chebtech.parseDataInputs(data, pref);\n\n % Force nonadaptive construction if PREF.FIXEDLENGTH is numeric and\n % we're not using contour integrals.\n if ( ~(isnumeric(op) || iscell(op)) && ...\n ~isnan(pref.fixedLength) && ~pref.useTurbo )\n % Evaluate op on the Chebyshev grid of given size:\n op = feval(op, chebtech2.chebpts(pref.fixedLength));\n end\n\n % Actual construction takes place here:\n [obj, values] = populate(obj, op, data, pref);\n\n if ( isnumeric(op) || iscell(op) )\n % Set length of obj to PREF.FIXEDLENGTH (if it is non-trivial).\n if ( ~isnan(pref.fixedLength ) )\n obj = prolong(obj, pref.fixedLength);\n end\n\n % No need to error check when constructing from discrete data.\n return\n elseif ( obj.ishappy )\n % Use contour integrals if requested.\n if ( pref.useTurbo )\n obj = constructorTurbo(obj, op, pref);\n end\n\n % No need to error check if we are happy:\n return\n end\n\n % Check for NaNs (if not happy):\n if ( pref.extrapolate )\n % Check for NaNs in interior only (because extrapolate was on):\n if ( any(any(isnan(obj.coeffs(2:end-1,:)))) )\n error('CHEBFUN:CHEBTECH2:chebtech2:nanEval', ...\n 'Function returned NaN when evaluated.')\n end\n % We make sure not to return NaNs at +1 and -1.\n valuesTemp = extrapolate(obj, values);\n valuesTemp([1 end], :) = valuesTemp([1,end],:);\n obj.coeffs = obj.vals2coeffs(valuesTemp);\n elseif ( any(isnan(obj.coeffs(:))) )\n % Here we throw an error if NaNs were encountered anywhere.\n error('CHEBFUN:CHEBTECH2:chebtech2:nanEval2', ...\n 'Function returned NaN when evaluated.')\n end\n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% STATIC METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = true )\n \n % Aliasing:\n coeffs = alias(coeffs, m)\n \n % Angles of Chebyshev points. (i.e., acos(chebpts(n))\n t = angles(n)\n \n % Evaluate a Chebyshev interpolant using the barycentric formula:\n out = bary(x, values)\n \n % Compute Chebyshev barycentric weights:\n w = barywts(n)\n \n % Compute Chebyshev points (x) and optionally quadrature (w)\n % and barycentric (v) weights:\n [x, w, v, t] = chebpts(n);\n \n % Tensor product grid of Chebyshev points in 1D, 2D or 3D:\n out = tensorGrid(N, dom)\n \n % Convert coefficients to values:\n values = coeffs2vals(coeffs);\n \n % Make a CHEBTECH2 (constructor shortcut):\n f = make(varargin);\n \n % Compute Chebyshev quadrature weights:\n w = quadwts(n)\n \n % Refinement function for CHEBTECH2 construction (evaluates OP on grid):\n [values, points, giveUp] = refine(op, values, pref)\n \n % Return the value-based discretization class which uses CHEBTECH2: \n function disc = returnValsDisc()\n disc = @chebcolloc2;\n end\n \n % Convert values to coefficients:\n coeffs = vals2coeffs(values)\n \n end\n \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebtech2/chebtech2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.38736672127493377}}
{"text": "% CORRIMAGE - compute correlation image between an event and amplitude\n% and phase in the time-frequency domain.\n%\n% Usage: \n% corrimage(data, sortvar, times);\n% [times, freqs, alpha, sigout, limits ] = corrimage(data, sortvar, ...\n% times, 'key1', val1, 'key2', val2, ...)\n%\n% Inputs:\n% data - [float array] data of size (times,trials)\n% sortvar - [float array] sorting variable of size (trials)\n% times - [float array] time indices for every data point. Size of\n% (times). Note: same input as the times vector for erpimage.\n%\n% Optional input:\n% 'mode' - ['phase'|'amp'] compute correlation of event values with \n% phase ('phase') or amplitude ('amp') of signal at the \n% given time-frequency points. Default is 'amp'.\n% 'freqs' - [min nfreqs max] build a frequency vector of size nfreqs \n% with frequency spaced in a log scale. Then compute \n% correlation at these frequency value.\n% Default is 50 points in a log scale between 2.5Hz to 50Hz.\n% 'times' - [float vector] compute correlation at these time value (ms).\n% (uses closest times points in 'times' input and return\n% them in the times output).\n% Default is 100 steps between min time+5% of time range and\n% max time-5%. Enter only 2 values [N X] to generate N \n% time points and trim by X %. If N is negative, uses it as\n% a subsampling factor [-3 5] trims times by 5% and subsample\n% by 3 (by subsampling one obtains a regularly spaced times).\n% 'trim' - [low high] low and high percentile of sorted sortvar values\n% to retain. i.e. [5 95] remove the 5 lowest and highest \n% percentile of sortvar values (and associated data) before\n% computing statistics. Default is [0 100].\n% 'align' - [float] same as 'align' parameter of ERPIMAGE. This \n% parameter is used to constrain the 'times' parameter so\n% correlation with data trials containing 0-values (as a\n% result of data alignment) are avoided: computing these\n% correlations would produce spurious significant results.\n% Default is no alignment.\n% 'method' - ['erpimage'|timefreq'] use either the ERPIMAGE function\n% of the TIMEFREQ function to compute spectral decomposition.\n% Default is 'timefreq' for speed reasons (note that both \n% methods should return the same results).\n% 'erpout' - [min max] regress out ERP using the selected time-window [min\n% max] in ms (the ERP is subtracted from the whole time period \n% but only regressed out in the selected time window).\n% 'triallimit' - [integer array] specify trial boundaries for subjects. For \n% instance [1 200 400] indicates 2 subjects, trials 1 to 199\n% for subject 1 and trials 200 to 399 for subject 2. This is \n% currently only used for regressing erp out.\n%\n% Processing options:\n% 'erpimopt' - [cell array] erpimage additional options (number of cycle ...).\n% 'tfopt' - [cell array] timefreq additional options (number of cycle ...).\n% \n% Plotting options:\n% 'plotvals' - [cell array of output values] enter output values here\n% { times freqs alpha sigout} to replot them.\n% 'nofig' - ['on'|'off'] do not create figure.\n% 'cbar' - ['on'|'off'] plot color bar. Default: 'on'.\n% 'smooth' - ['on'|'off'] smooth significance array. Default: 'on'.\n% 'plot' - ['no'|'alpha'|'sigout'|'sigoutm'|'sigoutm2'] plot -10*log(alpha)\n% values ('alpha'); output signal (slope or ITC) ('sigout'), \n% output signal masked by significance ('sigoutm') or the last\n% 2 option combined ('sigoutm2'). 'no' prevent the function\n% from plotting. In addition, see pmask. Default is 'sigoutmasked'.\n% 'pmask' - [real] maximum p value to show in plot. Default is 0.00001\n% (0.001 taking into account multiple comparisons (100)). Enter \n% 0.9XXX to get the higher tail or a negative value (e.e., -0.001\n% to get both tails).\n% 'vert' - [real array] time vector for vertivcal lines.\n% 'limits' - [min max] plotting limits. \n%\n% Outputs:\n% times - [float vector] vector of times (ms)\n% freqs - [float vector] vector of frequencies (Hz)\n% alpha - [float array] array (freqs,times) of p-values.\n% sigout - [float array] array (freqs,times) of signal out (coherence\n% for phase and slope for amplitude).\n%\n% Important note: the 'timefreq' method may truncate the time window to\n% compute the spectral decomposition at the lowest freq.\n%\n% Author: Arnaud Delorme & Scott Makeig, SCCN UCSD, \n% and CNL Salk Institute, 18 April 2003\n%\n% See also: ERPIMAGE\n\n%123456789012345678901234567890123456789012345678901234567890123456789012\n\n% Copyright (C) 2002 Arnaud Delorme\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [time, freq, alpha, sigout, limits, tf, sortvar] = corrimage(data, sortvar, timevect, varargin)\n\nif nargin < 3\n help corrimage;\n return;\nend\n \nif isempty(timevect), timevect = [1 2]; end\n\n% check inputs\n% ------------\ng = finputcheck(varargin, { 'freqs' 'real' [0 Inf] [2.5 50 50];\n 'times' 'real' [] [100 5]; % see function at the end\n 'mode' 'string' { 'phase','amp' } 'amp'; \n 'vert' 'real' [] [];\n 'align' { 'real','cell' } [] []; \n 'plotvals' 'cell' [] {}; \n 'pmask' 'real' [] 0.00001; \n 'triallimit' 'integer' [] []; \n 'trim' 'real' [0 100] [0 100]; \n 'limits' 'real' [] [];\n 'method' 'string' { 'erpimage','timefreq' } 'timefreq';\n 'plot' 'string' { 'no','alpha','sigout','sigoutm','sigoutp','sigoutm2' } 'sigoutm'; \n 'nofig' 'string' { 'on','off' } 'off';\n 'cbar' 'string' { 'on','off' } 'on';\n 'smooth' 'string' { 'on','off' } 'off';\n 'erpout' 'real' [] [];\n 'tfopt' 'cell' [] {};\n 'erpimopt' 'cell' [] {} });\nif ischar(g), error(g); end\n\nfprintf('Generating %d frequencies in log scale (ignore message on linear scale)\\n', g.freqs(2));\ng.freqs = logscale(g.freqs(1), g.freqs(3), g.freqs(2));\n \nframes = length(timevect);\nif size(data,1) == 1\n data = reshape(data, frames, size(data,2)*size(data,3)/frames);\nend\n\n% trim sortvar values\n% -------------------\n[sortvar sortorder] = sort(sortvar);\ndata = data(:, sortorder);\nlen = length(sortvar);\nlowindex = round(len*g.trim(1)/100)+1;\nhighindex = round(len*g.trim(2)/100);\nsortvar = sortvar(lowindex:highindex);\ndata = data(:, lowindex:highindex);\nif lowindex ~=1 || highindex ~= length(sortorder)\n fprintf('Actual percentiles %1.2f-%1.2f (indices 1-%d -> %d-%d): event vals min %3.2f; max %3.2f\\n', ...\n 100*(lowindex-1)/len, 100*highindex/len, len, lowindex, highindex, min(sortvar), max(sortvar));\nend\n\n% assign subject number for each trial\n% ------------------------------------\nif ~isempty(g.triallimit)\n alltrials = zeros(1,len);\n for index = 1:length(g.triallimit)-1\n alltrials([g.triallimit(index):g.triallimit(index+1)-1]) = index; \n end\n alltrials = alltrials(sortorder);\n alltrials = alltrials(lowindex:highindex);\nend\n\n%figure; hist(sortvar)\n\n% constraining time values depending on data alignment\n% ----------------------------------------------------\nsrate = 1000*(length(timevect)-1)/(timevect(end)-timevect(1));\nif ~isempty(g.align)\n\n if iscell(g.align)\n fprintf('Realigned sortvar plotted at %g ms.\\n',g.align{1});\n shifts = round((g.align{1}-g.align{2})*srate/1000); % shifts can be positive or negative\n g.align = g.align{1};\n else\n if isinf(g.align)\n g.align = median(sortvar);\n end\n fprintf('Realigned sortvar plotted at %g ms.\\n',g.align);\n \n % compute shifts\n % --------------\n shifts = round((g.align-sortvar)*srate/1000); % shifts can be positive or negative\n end\n \n %figure; hist(shifts)\n minshift = min(shifts); % negative\n maxshift = max(shifts); % positive\n if minshift > 0, error('minshift has to be negative'); end\n if maxshift < 0, error('maxshift has to be positive'); end\n \n % realign data for all trials\n % ---------------------------\n aligndata=zeros(size(data))+NaN; % begin with matrix of zeros()\n for t=1:size(data,2), %%%%%%%%% foreach trial %%%%%%%%%\n shft = shifts(t);\n if shft>0, % shift right\n aligndata(shft+1:frames,t)=data(1:frames-shft,t);\n elseif shft < 0 % shift left\n aligndata(1:frames+shft,t)=data(1-shft:frames,t);\n else % shft == 0\n aligndata(:,t) = data(:,t);\n end \n end % end trial \n data = aligndata(maxshift+1:frames+minshift,:);\n if any(any(isnan(data))), error('NaNs remaining after data alignment'); end\n timevect = timevect(maxshift+1:frames+minshift);\n \n % take the time vector subset\n % ---------------------------\n if isempty(timevect), error('Shift too big, empty time vector'); \n else fprintf('Time vector truncated for data alignment between %1.0f and %1.0f\\n', ...\n min(timevect), max(timevect)); \n end; \nend\n\n% regress out the ERP from the data (4 times to have residual ERP close to 0)\n% ---------------------------------------------------------------------------\nif ~isempty(g.erpout) \n %data = erpregout(data);\n %data = erpregout(data);\n %data = erpregout(data);\n disp('Regressing out ERP');\n erpbeg = mean(data,2);\n if ~isempty(g.triallimit)\n for index = 1:length(g.triallimit)-1\n trials = find(alltrials == index); \n %[data(:,trials) erp factors]= erpregout(data(:,trials), [timevect(1) timevect(end)], [300 400]);\n erpstart = mean(data(:,trials),2);\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n erpend = mean(data(:,trials),2);\n fprintf([ '***********************************************\\n' ...\n 'Ratio in ERP after regression (compare to before) is %3.2f\\n' ...\n '***********************************************\\n' ], mean(erpend./erpstart));\n end\n end\n erpend = mean(data,2);\n fprintf([ '***********************************************\\n' ...\n 'Ratio in grand ERP after regression (compare to before) is %3.2f\\n' ...\n '***********************************************\\n' ], mean(erpend./erpbeg));\n \n if 0\n %trials = find(alltrials == 1); \n data2 = data;\n dasf\n\n [data(:,trials) erp factors]= erpregout(data(:,trials), [timevect(1) timevect(end)], [300 400]);\n\n figure; subplot(1,2,1); erpimage(data, sortvar, timevect, '', 300, 500, 'erp');\n \n figure; \n subplot(1,2,1); erpimage(data2, sortvar, timevect, '', 300, 500, 'erp');\n subplot(1,2,2); erpimage(data , sortvar, timevect, '', 300, 500, 'erp');\n \n figure; \n subplot(1,2,1); erpimage(data2(:,trials), sortvar(trials), timevect, '', 0, 0, 'erp');\n subplot(1,2,2); erpimage(data (:,trials), sortvar(trials), timevect, '', 0, 0, 'erp');\n\n \n figure; \n for index = 1:length(g.triallimit)-1\n subplot(3,5,index);\n trials = find(alltrials == index); \n erpimage(data(:,trials), sortvar(trials), timevect, '', 50, 100, 'erp');\n end\n \n disp('Regressing out ERP');\n if ~isempty(g.triallimit)\n for index = 1:length(g.triallimit)-1\n trials = find(alltrials == index); \n [data(:,trials) erp factors]= erpregout(data(:,trials), [timevect(1) timevect(end)], [300 400]);\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n data(:,trials) = erpregout(data(:,trials));\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout);\n end\n else\n %data = erpregout(data, [timevect(1) timevect(end)], g.erpout);\n end\n end\nend\n\n% generate time points\n% --------------------\ng.times = gettimes(timevect, g.times);\ndata = reshape(data, 1, size(data,2)*size(data,1));\n\n% time frequency decomposition\n% ----------------------------\nif strcmpi(g.method, 'timefreq') && isempty(g.plotvals)\n data = reshape(data, length(data)/length(sortvar), length(sortvar));\n [tf, g.freqs, g.times] = timefreq(data, srate, 'freqs', g.freqs, 'timesout', g.times, ...\n 'tlimits', [min(timevect) max(timevect)], 'wavelet', 3);\n outvar = sortvar;\nend\n\n% compute correlation\n% -------------------\nif strcmpi(g.mode, 'phase') && isempty(g.plotvals) \n for freq = 1:length(g.freqs)\n fprintf('Computing correlation with phase %3.2f Hz ----------------------\\n', g.freqs(freq));\n for time = 1:length(g.times)\n if strcmpi(g.method, 'erpimage')\n [outdata,outvar,outtrials,limits,axhndls,erp, ...\n amps,cohers,cohsig,ampsig,outamps,phsangls,phsamp,sortidx] =erpimage(data,sortvar,timevect, ...\n '', 0,0,g.erpimopt{:}, 'phasesort', [g.times(time) 0 g.freqs(freq)], 'noshow', 'yes');\n else\n phsangls = angle( squeeze(tf(freq, time, :))' );\n end\n \n % computing ITCs\n [ ITC(freq, time) alpha(freq, time) ] = ...\n bootcircle(outvar/mean(outvar), exp(j*phsangls), 'naccu', 250);\n\n % accumulate 200 values, fitted with a normal distribution\n % --------------------------------------------------------\n %cmplx = outvar .* exp(j*phsangls)/mean(outvar);\n %ITC(freq, time) = mean(cmplx);\n %alpha(freq,time) = bootstat(outvar/mean(outvar), exp(j*phsangls), 'res = mean(arg1 .* arg2)', ...\n % 'naccu', 100, 'vals', abs(ITC(freq, time)), 'distfit', 'norm');\n end\n end\n sigout = ITC;\nelseif isempty(g.plotvals)\n for freq = 1:length(g.freqs)\n fprintf('Computing correlation with amplitude %3.2f Hz ----------------------\\n', g.freqs(freq));\n for time = 1:length(g.times)\n if strcmpi(g.method, 'erpimage')\n [outdata,outvar,outtrials,limits,axhndls,erp, ...\n amps,cohers,cohsig,ampsig,outamps,phsangls,phsamp,sortidx] =erpimage(data,sortvar,timevect, ...\n '', 0,0,g.erpimopt{:}, 'ampsort', [g.times(time) 0 g.freqs(freq)], 'noshow', 'yes');\n else\n phsamp = abs(squeeze(tf(freq, time, :)))';\n end\n \n % computing ITCs\n [ypred alpha(freq, time) Rsq slope(freq, time)] = myregress(outvar, 20*log10(phsamp));\n end\n end; \n sigout = slope;\nelse \n g.times = g.plotvals{1};\n g.freqs = g.plotvals{2};\n alpha = g.plotvals{3};\n sigout = g.plotvals{4};\nend\n\n% plot correlation\n% ----------------\nif ~strcmp('plot', 'no')\n if ~isreal(sigout), \n if strcmpi(g.plot, 'sigoutp')\n sigoutplot = angle(sigout);\n else\n sigoutplot = abs(sigout);\n end\n else sigoutplot = sigout; \n end\n sigouttmp = sigoutplot;\n if strcmpi(g.smooth, 'on')\n tmpfilt = gauss2d(3,3,.3,.3);\n tmpfilt = tmpfilt/sum(sum(tmpfilt));\n alpha = conv2(alpha, tmpfilt, 'same');\n end\n \n % mask signal out\n if g.pmask > 0.5\n indices = find( alpha(:) < g.pmask);\n sigouttmp = sigoutplot;\n sigouttmp(indices) = 0;\n elseif g.pmask < 0 % both sides, i.e. 0.01\n sigouttmp = sigoutplot;\n indices = intersect_bc(find( alpha(:) > -g.pmask), find( alpha(:) < 1+g.pmask));\n sigouttmp(indices) = 0;\n else\n sigouttmp = sigoutplot;\n indices = find( alpha(:) > g.pmask);\n sigouttmp(indices) = 0;\n end\n \n if strcmpi(g.nofig, 'off'), figure; end\n switch g.plot\n case 'alpha', limits = plotfig(g.times, g.freqs, -log10(alpha), g);\n case 'sigout', limits = plotfigsim(g.times, g.freqs, sigoutplot, g);\n case { 'sigoutm' 'sigoutp' }, limits = plotfigsim(g.times, g.freqs, sigouttmp, g);\n case 'sigoutm2', limits = subplot(1,2,1); plotfigsim(g.times, g.freqs, sigoutplot, g);\n limits = subplot(1,2,2); plotfigsim(g.times, g.freqs, sigouttmp, g);\n end\nend\n\ntime = g.times;\nfreq = g.freqs;\n\nreturn;\n\n% formula for the normal distribution\n% -----------------------------------\nfunction y = norm(mu, sigma, x);\n\ny = 1/sqrt(2) * exp( -(x-mu).^2/(sigma*sigma*2) ) / (sqrt(pi)*sigma);\n\n% get time points\n% ---------------\nfunction val = gettimes(timevect, timevar);\n if length(timevar) == 2\n\n if timevar(1) > 0\n % generate linearly space vector\n % ------------------------------\n npoints = timevar(1);\n trim = timevar(2);\n if length(timevect)-2*round(trim/100*length(timevect)) < npoints\n npoints = length(timevect)-round(trim/100*length(timevect));\n end\n fprintf('Generating %d times points trimmed by %1.1f percent\\n', npoints, trim);\n timer = max(timevect) - min(timevect);\n maxt = max(timevect)-timer*trim/100;\n mint = min(timevect)+timer*trim/100;\n val = linspace(mint,maxt, npoints);\n else \n % subsample data\n % --------------\n nsub = -timevar(1);\n trim = timevar(2);\n len = length(timevect);\n trimtimevect = timevect(round(trim/100*len)+1:len-round(trim/100*len));\n fprintf('Subsampling by %d and trimming data by %1.1f percent (%d points)\\n', nsub, trim, round(trim/100*len));\n val = trimtimevect(1:nsub:end);\n end\n else\n val = timevar;\n end; \n \n % find closet points in data\n oldval = val;\n for index = 1:length(val)\n [dum ind] = min(abs(timevect-val(index)));\n val(index) = timevect(ind);\n end\n if length(val) < length(unique(val))\n disp('Warning: duplicate times, reduce the number of output times');\n end\n if all(oldval == val)\n disp('Debug msg: Time value unchanged by finding closest in data');\n end; \n \n% get log scale (for frequency)\n% ------------- \nfunction val = logscale(a,b,n);\n %val = [5 7 9]; return;\n val = linspace(log(a), log(b), n);\n val = exp(val);\n \n% plot figure\n% -----------\nfunction limits = plotfig(times, freqs, vals, g)\n icadefs;\n imagesc(times, [1:size(vals,1)], vals);\n \n colormap(DEFAULT_COLORMAP);\n ticks = linspace(1, size(vals,1), length(freqs));\n ticks = ticks(1:4:end);\n set(gca, 'ytick', ticks);\n set(gca, 'yticklabel', num2str(freqs(1:4:end)', 3))\n\n xlabel('Time (ms)'); ylabel('Freq (Hz)');\n if ~isempty(g.limits), caxis(g.limits); end\n limits = caxis;\n if ~isempty(g.vert)\n for vert = g.vert(:)'\n hold on; plot([vert vert], [0.001 500], 'k', 'linewidth', 2);\n end\n end\n if strcmpi(g.cbar,'on')\n cbar;\n end\n\n% plot figure with symmetrical phase\n% ---------------------------------\nfunction limits = plotfigsim(times, freqs, vals, g)\n icadefs;\n imagesc(times, [1:size(vals,1)], vals);\n\n colormap(DEFAULT_COLORMAP);\n ticks = linspace(1, size(vals,1), length(freqs));\n ticks = ticks(1:4:end);\n set(gca, 'ytick', ticks);\n set(gca, 'yticklabel', num2str(freqs(1:4:end)', 3))\n\n if ~isempty(g.limits) \n caxis(g.limits);\n limits = g.limits;\n else \n clim = max(abs(caxis));\n limits = [-clim clim];\n caxis(limits);\n end\n xlabel('Time (ms)'); ylabel('Freq (Hz)');\n if ~isempty(g.vert)\n for vert = g.vert(:)'\n hold on; plot([vert vert], [0.01 500], 'k', 'linewidth', 2);\n end\n end\n if strcmpi(g.cbar,'on')\n cbar;\n end\n return;\n\n\n% -----------------------------------------\n% plot time-freq point (when clicking on it\n% -----------------------------------------\nfunction plotpoint(data, sortvar, timevect, freq, timepnts);\n\nfigure; \nsubplot(2,2,1);\nerpimage(act_all(:,:),sortvar_all,timepnts, ...\n '', 300,10,'erp', 'erpstd', 'caxis',[-1.0 1.0], 'srate',256,'align',352, 'yerplabel', '', erpimopt{:}, ...\n 'phasesort', [500 0 5]); % aligned to median rt\n\n% plot in polar coordinates phase versus RT\n% -----------------------------------------\nphaseang2 = [phsangls phsangls-2*pi]; phaseang2 = movav(phaseang2,[], 100); \noutvar2 = [outvar outvar]; outvar2 = movav(outvar2,[], 100);\nphaseang2 = phaseang2(length(phsangls)/2-50:length(phsangls)+length(phsangls)/2-50);\noutvar2 = outvar2 (length(phsangls)/2-50:length(phsangls)+length(phsangls)/2-50);\nsubplot(2,2,3);\npolar(phsangls, outvar, '.');\nhold on; polar(phaseang2, outvar2, 'r');\n\n% computing ITC\n% -------------\ncmplx = outvar .* exp(j*phsangls);\nITCval = mean(cmplx);\nangle(ITCval)/pi*180;\nabs(ITCval)/mean(outvar);\ntext(-1300,-1400,sprintf('ITC value: amplitude %3.4f, angle %3.1f\\n', abs(ITCval)/mean(outvar), angle(ITCval)/pi*180));\n\n% accumulate 200 values\n% ---------------------\nalpha = 0.05;\nif exist('accarray') ~= 1, accarray = NaN; end\n[sigval accarray] = bootstat(outvar/mean(outvar), phsangls, 'res = mean(arg1 .* exp(arg2*complex(0,1)))', ...\n 'accarray', accarray, 'bootside', 'upper', 'alpha', alpha);\ntext(-1300,-1600,sprintf('Threshold for significance at %d percent(naccu=200): %3.4f\\n', alpha*100, sigval));\ntitle(sprintf('Clust %d corr. theta phase at 500 ms and RT', clust));\n\n% amplitude sorting\n% -----------------\nfigure;\n[outdata,outvar,outtrials,limits,axhndls,erp, ...\n amps,cohers,cohsig,ampsig,outamps,phsangls,phsamp,sortidx]=erpimage(act_all(:,:),sortvar_all,timepnts, ...\n '', 0,0,'erp', 'erpstd', 'caxis', 0.5, 'cbar', ...\n 'srate',256,'align',352, 'yerplabel', '', erpimopt{:}, 'ampsort', [500 0 5]); % aligned to median rt\nclose;\nsubplot(2,2,2);\nerpimage(act_all(:,:),sortvar_all,timevect, ...\n '', 300,10,'erp', 'erpstd', 'caxis', 0.5, 'cbar', ...\n 'srate',256,'align',352, 'yerplabel', '', erpimopt{:}, 'ampsort', [500 0 5]); % aligned to median rt\n\n% compute correlation\n% -------------------\n[ypred alpha Rsq] = myregress(outvar, phsamp);\nsubplot(2,2,4);\nplot(outvar, phsamp, '.');\nhold on;\nplot(outvar, ypred, 'r');\nxlabel('Reaction time');\nylabel('Amplitude');\ntitle(sprintf('Theta amp. at 500 ms vs RT (p=%1.8f, R^2=%3.4f)', alpha, Rsq));\nset(gcf, 'position', [336 485 730 540], 'paperpositionmode', 'auto');\n\nsetfont(gcf, 'fontsize', 10);\neval(['print -djpeg clust' int2str(clust) 'corrthetart.jpg']);\n \n \n% set up for command line call\n% copy text from plotcorrthetaart\n%timevect = times;\nsortvar = sortvar_all;\ndata = act_all;\ntime = 1\nfreq = 1\ng.times = 0;\ng.freqs = 5;\ng.erpimopt = {};\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/corrimage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3872916868788579}}
{"text": "function [Eft, Varft, lpyt, Eyt, Varyt] = gpia_loopred(gp_array, x, y, varargin)\n%GPIA_LOOPRED Leave-one-out predictions with Gaussian Process IA approximation\n%\n% Description\n% [EFT, VARFT, LPYT, EYT, VARYT] = GPIA_LOOPRED(RECGP, X, Y)\n% takes a cell array of GP structures together with matrix X of\n% input vectors, matrix X of training inputs and vector Y of\n% training targets, and evaluates the leave-one-out predictive\n% distribution at inputs X and returns means EFT and variances\n% VARFT of latent variables, the logarithm of the predictive\n% densities PYT, and the predictive means EYT and variances\n% VARYT of observations at input locations X.\n%\n% OPTIONS is optional parameter-value pair\n% z - optional observed quantity in triplet (x_i,y_i,z_i)\n% Some likelihoods may use this. For example, in case of \n% Poisson likelihood we have z_i=E_i, that is, expected value \n% for ith case. \n% is - defines if importance sampling weighting is used 'on'\n% (default). If set to 'off', integration points and\n% weights for the full posterior are used.\n% \n% Given Gaussian likelihood or non-Gaussian likelihood and\n% latent method Laplace or EP, LOO-posterior given\n% hyperparameters is computed analytically or with analytic\n% approximation and LOO-posterior of the hyperparameters is\n% approximated using importance sampling reweighted integration\n% points from gp_ia. Optionally integration weights for full data\n% posterior of hyperparameters can be used (by setting option\n% 'is' to 'off').\n%\n% References:\n% Aki Vehtari and Jouko Lampinen (2002). Bayesian model\n% assessment and comparison using cross-validation predictive\n% densities. Neural Computation, 14(10):2439-2468.\n%\n% See also\n% GP_LOOPRED, GP_IA, GP_PRED\n%\n% Copyright (c) 2009 Ville Pietil�inen\n% Copyright (c) 2009-2010 Jarno Vanhatalo\n% Copyright (c) 2010,2012 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'GPIA_LOOPRED';\n ip.addRequired('gp_array',@iscell);\n ip.addRequired('x', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addRequired('y', @(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('z', [], @(x) isreal(x) && all(isfinite(x(:))))\n ip.addParamValue('is', 'on', @(x) ismember(x,{'on' 'off'}))\n ip.parse(gp_array, x, y, varargin{:});\n z=ip.Results.z;\n is=ip.Results.is;\n\n nGP = numel(gp_array);\n n=size(x,1);\n \n P_TH = zeros(1,nGP);\n Efts = zeros(n,nGP);\n Varfts = zeros(n,nGP);\n lpyts = zeros(n,nGP);\n if nargout > 3\n Eyts = zeros(n,nGP);\n Varyts = zeros(n,nGP);\n end\n \n for i1=1:nGP\n Gp=gp_array{i1};\n P_TH(1,i1) = Gp.ia_weight;\n % compute leave-one-out predictions for each hyperparameter sample\n % if latent method is MCMC, then these samples are for latent values, too\n if nargout <= 3\n [Efts(:,i1), Varfts(:,i1), lpyts(:,i1)] = gp_loopred(Gp, x, y, 'z', z);\n else\n [Efts(:,i1), Varfts(:,i1), lpyts(:,i1), Eyts_temp, Varyts_temp] = gp_loopred(Gp, x, y, 'z', z);\n if ~isempty(Eyts_temp)\n Eyts(:,i1) = Eyts_temp;\n end\n if ~isempty(Varyts_temp)\n Varyts(:,i1) = Varyts_temp;\n end\n end\n end\n\n if isequal(is,'off')\n P_TH=repmat(P_TH,n,1);\n else\n % log importance sampling weights\n lw=-lpyts;\n % normalize weights\n for i2=1:n\n % this works even when lw have large magnitudes\n lw(i2,:)=lw(i2,:)-sumlogs(lw(i2,:));\n end\n % importance sampling weights\n w=exp(lw);\n % reweight ia weights\n P_TH=bsxfun(@times,P_TH,w);\n P_TH=bsxfun(@rdivide,P_TH,sum(P_TH,2));\n % check the effective sample size\n m_eff=1./sum(P_TH.^2,2);\n if min(m_eff)=200\n % (new) default sample size for is_normal and is_t is 200\n % CCD with nParam>=12 has at least 281 points\n [lw,pk] = psislw(log(P_TH'),10);\n P_TH=exp(lw');\n % check whether the variance and mean of the raw importance ratios is finite\n % PSIS weights have always finite variance and mean, but if raw importance\n % ratios have infinite variance the convergence to true value is\n % slower and if raw importance ratios have non-existing mean the the\n % estimate can't converge to true value\n vkn1=sum(pk>=0.5&pk<0.7);\n vkn2=sum(pk>=0.7&pk<1);\n vkn3=sum(pk>=1);\n n=numel(pk);\n if vkn1>0\n warning('%d (%.0f%%) PSIS Pareto k estimates between 0.5 and .7',vkn1,vkn1/n*100)\n end\n if vkn2>0\n warning('%d (%.0f%%) PSIS Pareto k estimates between 0.7 and 1',vkn2,vkn2/n*100)\n end\n if vkn3>0\n warning('%d (%.0f%%) PSIS Pareto k estimates greater than 1',vkn3,vkn3/n*100)\n end\n end\n end\n\n % compute combined predictions\n Eft = sum(Efts.*P_TH, 2);\n Varft = sum(Varfts.*P_TH,2) + sum(bsxfun(@minus,Efts,Eft).^2.*P_TH,2);\n if nargout > 2\n lpyt = log(sum(exp(lpyts+log(P_TH)),2));\n if nargout > 3\n Eyt = sum(Eyts.*P_TH,2);\n Varyt = sum(Varyts.*P_TH,2) + sum(bsxfun(@minus,Eyts,Eyt).^2.*P_TH, 2);\n end\n end\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpia_loopred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.38703178250911585}}
{"text": "function [y]=rake_fft(x, tol)\n% Discrete Fourier Transform in the QTT-Tucker format\n% function [y]=rake_fft(x, tol)\n% Computes the multidimensional DFT of the vector x in the QTT-Tucker format with\n% the approximation tolerance tol.\n% Returns the quantized dimensions in the correct order.\n%\n% !!WARNING!! employs a (probably) costly rank reverse procedure.\n\nD = size(x.tuck);\ntuck = x.tuck;\ncrx = core2cell(x.core);\nfor i=1:D\n [tuck{i}, rv]=qr(tuck{i}, 'lr');\n r1 = size(crx{i}, 1); r2 = size(crx{i}, 3); rt = size(crx{i},2);\n crx{i} = permute(crx{i}, [2, 1, 3]);\n crx{i} = reshape(crx{i}, rt, r1*r2);\n crx{i} = rv*crx{i};\n rt = size(rv,1);\n crx{i} = reshape(crx{i}, rt, r1, r2);\n crx{i} = permute(crx{i}, [2, 1, 3]); \nend;\n% [crx,rv]=qr(crx, 'rl');\n% crx = rv.'*crx;\nfor i=D:-1:2\n r1 = size(crx{i}, 1); rt = size(crx{i}, 2); r2 = size(crx{i}, 3);\n crx{i} = reshape(crx{i}, r1, rt*r2);\n [crx{i}, rv]=qr(crx{i}.', 0);\n r0 = size(crx{i-1}, 1); rt0 = size(crx{i-1}, 2);\n crx{i-1} = reshape(crx{i-1}, r0*rt0, r1);\n crx{i-1}=crx{i-1}*rv.';\n r1 = size(rv,1);\n crx{i-1} = reshape(crx{i-1}, r0, rt0, r1);\n crx{i} = reshape(crx{i}.', r1, rt, r2);\nend;\nfor i=1:D\n r1 = size(crx{i}, 1); r2 = size(crx{i}, 3); rt = size(crx{i},2);\n crx{i} = permute(crx{i}, [1, 3, 2]);\n crx{i} = reshape(crx{i}, r1*r2, rt);\n [crx{i}, rv]=qr(crx{i}, 0);\n tuck{i} = tuck{i}*rv.';\n tuck{i} = qtt_fft1(tuck{i}, tol);\n % rank is reversed\n r = tuck{i}.r;\n rq1 = r(1);\n for k=1:rq1\n ek = [zeros(1,k-1), 1, zeros(1,rq1-k)];\n yk = ek*tuck{i}; % first rank is 1\n if (k==1)\n ynew = yk;\n else\n ynew = [ynew, yk];\n ynew = round(ynew, tol);\n end;\n end;\n [tuck{i}, rv]=qr(ynew, 'lr');\n% % reversing 2\n% % nonorth block is the last, but we need to SVD from the first\n% tuck{i} = core2cell(tuck{i});\n% for j=numel(tuck{i}):-1:2\n% tuck{i}{j} = reshape(tuck{i}{j}, r(j), 2*r(j+1));\n% [tuck{i}{j}, rv]=qr(tuck{i}{j}.', 0);\n% tuck{i}{j-1} = reshape(tuck{i}{j-1}, r(j-1)*2, r(j));\n% tuck{i}{j-1} = tuck{i}{j-1}*rv.';\n% r(j) = size(rv, 1);\n% tuck{i}{j} = reshape(tuck{i}{j}.', r(j), 2, r(j+1));\n% tuck{i}{j-1} = reshape(tuck{i}{j-1}, r(j-1), 2, r(j));\n% end;\n% tuck{i}{1} = permute(tuck{i}{1}, [2, 1, 3]);\n% tuck{i}{1} = reshape(tuck{i}{1}, 2, rq1*r(2));\n% [u,s,v]=svd(tuck{i}{1}, 'econ');\n% s = diag(s);\n% rnew = my_chop2(s, norm(s)*tol/sqrt(numel(tuck{i})-1));\n% u=u(:,1:rnew);\n% v=v(:,1:rnew)*diag(s(1:rnew));\n% tuck{i}{1} = reshape(u, 1, 2, rnew);\n% r(1) = 1;\n% rv = reshape(v', rnew*rq1, r(2));\n% for j=2:numel(tuck{i})\n% tuck{i}{j} = reshape(tuck{i}{j}, r(j), 2*r(j+1));\n% tuck{i}{j} = rv*tuck{i}{j};\n% r(j) = rnew;\n% tuck{i}{j} = reshape(tuck{i}{j}, r(j), rq1, 2, r(j+1));\n% tuck{i}{j} = permute(tuck{i}{j}, [1, 3, 2, 4]);\n% tuck{i}{j} = reshape(tuck{i}{j}, r(j)*2, rq1*r(j+1));\n% [u,s,v]=svd(tuck{i}{j}, 'econ');\n% s = diag(s);\n% rnew = my_chop2(s, norm(s)*tol/sqrt(numel(tuck{i})-1));\n% u=u(:,1:rnew);\n% v=v(:,1:rnew)*diag(s(1:rnew));\n% tuck{i}{j} = reshape(u, r(j), 2, rnew);\n% rv = reshape(v', rnew*rq1, r(j+1)); \n% end;\n% rv = reshape(rv, rnew, rq1);\n% tuck{i} = cell2core(tt_tensor, tuck{i});\n \n crx{i} = crx{i}*rv.';\n rt = size(rv,1);\n crx{i} = reshape(crx{i}, r1, r2, rt);\n crx{i} = permute(crx{i}, [1, 3, 2]); \n if (i ',num2str(sx(1)),'x',num2str(sx(2))]);\n disp(['size of matrix 2 => ',num2str(sy(1)),'x',num2str(sy(2))]);\n error('array size mismatch for mtimes')\n else\n out=mp(zeros(sx(1),sy(2)),precision);\n for ii=1:sx(1)\n for jj=1:sy(2)\n out(ii,jj)=sum(x(ii,1:end).*y(1:end,jj).');\n end\n end\n end\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/mptoolbox/@mp/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.38672072367882043}}
{"text": "function P=compute_constraint_distance_3param_6eq_6unk(m1,m2,m3)\n\n% Copyright (C) <2007> \n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the version 3 of the GNU General Public License\n% as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n% General Public License for more details. \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Francesc Moreno-Noguer, CVLab-EPFL, September 2007.\n% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/ \n\n%redefine variables name, for compatibility with maple\nm1_1=m1(1); \nm1_2=m1(2); \nm1_3=m1(3); \nm1_4=m1(4); \nm1_5=m1(5); \nm1_6=m1(6);\nm1_7=m1(7); \nm1_8=m1(8); \nm1_9=m1(9); \nm1_10=m1(10); \nm1_11=m1(11); \nm1_12=m1(12);\n\nm2_1=m2(1); \nm2_2=m2(2); \nm2_3=m2(3); \nm2_4=m2(4); \nm2_5=m2(5); \nm2_6=m2(6);\nm2_7=m2(7); \nm2_8=m2(8); \nm2_9=m2(9); \nm2_10=m2(10); \nm2_11=m2(11); \nm2_12=m2(12);\n\nm3_1=m3(1); \nm3_2=m3(2); \nm3_3=m3(3); \nm3_4=m3(4); \nm3_5=m3(5); \nm3_6=m3(6);\nm3_7=m3(7); \nm3_8=m3(8); \nm3_9=m3(9); \nm3_10=m3(10); \nm3_11=m3(11); \nm3_12=m3(12);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nt1 = (m1_2 ^ 2);\nt4 = (m1_6 ^ 2);\nt5 = (m1_3 ^ 2);\nt6 = (m1_5 ^ 2);\nt11 = (m1_4 ^ 2);\nt12 = (m1_1 ^ 2);\nt20 = m1_4 * m2_4;\nt21 = m1_3 * m2_3;\nt22 = m1_5 * m2_5;\nt23 = m1_2 * m2_2;\nt24 = m1_6 * m2_6;\nt25 = m1_1 * m2_1;\nt26 = (-m2_4 * m1_1 - m2_5 * m1_2 - m2_6 * m1_3 - m1_6 * m2_3 - m1_4 * m2_1 - m1_5 * m2_2 + t20 + t21 + t22 + t23 + t24 + t25);\nt27 = m1_6 * m3_6;\nt29 = m1_5 * m3_5;\nt30 = m1_4 * m3_4;\nt33 = m1_3 * m3_3;\nt35 = m1_1 * m3_1;\nt38 = m1_2 * m3_2;\nt39 = (t27 - m1_6 * m3_3 + t29 + t30 - m1_4 * m3_1 - m3_6 * m1_3 + t33 - m3_5 * m1_2 + t35 - m3_4 * m1_1 - m1_5 * m3_2 + t38);\nt40 = (m2_4 ^ 2);\nt41 = (m2_2 ^ 2);\nt42 = (m2_5 ^ 2);\nt43 = (m2_1 ^ 2);\nt44 = (m2_6 ^ 2);\nt45 = (m2_3 ^ 2);\nt53 = m2_4 * m3_4;\nt56 = m2_5 * m3_5;\nt57 = m2_2 * m3_2;\nt60 = m2_1 * m3_1;\nt62 = m2_6 * m3_6;\nt63 = m2_3 * m3_3;\nt65 = (t53 - m2_4 * m3_1 - m3_4 * m2_1 + t56 + t57 - m2_5 * m3_2 - m2_6 * m3_3 + t60 - m3_6 * m2_3 + t62 + t63 - m3_5 * m2_2);\nt66 = (m3_5 ^ 2);\nt69 = (m3_4 ^ 2);\nt70 = (m3_3 ^ 2);\nt71 = (m3_2 ^ 2);\nt72 = (m3_6 ^ 2);\nt75 = (m3_1 ^ 2);\nt81 = (m1_9 ^ 2);\nt82 = (m1_8 ^ 2);\nt83 = (m1_7 ^ 2);\nt90 = m1_8 * m2_8;\nt91 = m1_7 * m2_7;\nt93 = m1_9 * m2_9;\nt98 = (-m1_9 * m2_3 + t21 + t90 + t23 + t91 + t25 - m2_7 * m1_1 + t93 - m2_9 * m1_3 - m1_8 * m2_2 - m1_7 * m2_1 - m2_8 * m1_2);\nt101 = m1_9 * m3_9;\nt102 = m1_7 * m3_7;\nt106 = m1_8 * m3_8;\nt108 = (-m3_8 * m1_2 + t38 + t33 - m3_9 * m1_3 + t101 + t102 - m1_7 * m3_1 - m1_9 * m3_3 + t35 - m3_7 * m1_1 + t106 - m1_8 * m3_2);\nt113 = (m2_8 ^ 2);\nt116 = (m2_9 ^ 2);\nt117 = (m2_7 ^ 2);\nt119 = m2_8 * m3_8;\nt122 = m2_9 * m3_9;\nt125 = m2_7 * m3_7;\nt128 = (t119 - m2_7 * m3_1 - m3_8 * m2_2 + t57 + t63 + t60 + t122 - m2_8 * m3_2 - m3_7 * m2_1 + t125 - m3_9 * m2_3 - m2_9 * m3_3);\nt129 = (m3_7 ^ 2);\nt130 = (m3_8 ^ 2);\nt133 = (m3_9 ^ 2);\nt141 = (m1_10 ^ 2);\nt142 = (m1_11 ^ 2);\nt143 = (m1_12 ^ 2);\nt151 = m1_10 * m2_10;\nt152 = m1_12 * m2_12;\nt154 = m1_11 * m2_11;\nt158 = (-m2_10 * m1_1 - m2_12 * m1_3 + t151 + t23 + t25 + t152 + t21 - m1_10 * m2_1 + t154 - m1_11 * m2_2 - m2_11 * m1_2 - m1_12 * m2_3);\nt160 = m1_12 * m3_12;\nt164 = m1_10 * m3_10;\nt165 = m1_11 * m3_11;\nt168 = (-m3_10 * m1_1 + t160 - m3_11 * m1_2 + t38 + t33 - m1_12 * m3_3 - m3_12 * m1_3 + t164 + t35 + t165 - m1_11 * m3_2 - m1_10 * m3_1);\nt169 = (m2_12 ^ 2);\nt170 = (m2_10 ^ 2);\nt171 = (m2_11 ^ 2);\nt179 = m2_10 * m3_10;\nt181 = m2_12 * m3_12;\nt185 = m2_11 * m3_11;\nt188 = (t57 + t60 + t179 - m2_10 * m3_1 + t181 - m2_12 * m3_3 - m3_12 * m2_3 - m3_10 * m2_1 + t63 + t185 - m2_11 * m3_2 - m3_11 * m2_2);\nt191 = (m3_12 ^ 2);\nt192 = (m3_10 ^ 2);\nt193 = (m3_11 ^ 2);\nt212 = (t22 + t91 + t93 - m1_7 * m2_4 + t20 - m2_7 * m1_4 + t90 - m2_8 * m1_5 - m1_8 * m2_5 - m1_9 * m2_6 + t24 - m2_9 * m1_6);\nt219 = (t101 + t30 - m3_9 * m1_6 - m3_8 * m1_5 - m1_8 * m3_5 - m3_7 * m1_4 + t27 - m1_9 * m3_6 - m1_7 * m3_4 + t102 + t106 + t29);\nt233 = (t53 - m2_8 * m3_5 - m2_9 * m3_6 - m2_7 * m3_4 + t125 + t122 - m3_8 * m2_5 + t62 + t119 + t56 - m3_7 * m2_4 - m3_9 * m2_6);\nt254 = (-m2_11 * m1_5 + t154 + t151 - m1_12 * m2_6 + t20 - m1_10 * m2_4 - m2_12 * m1_6 - m2_10 * m1_4 - m1_11 * m2_5 + t152 + t24 + t22);\nt261 = (t30 - m3_12 * m1_6 - m1_10 * m3_4 - m1_11 * m3_5 + t160 + t27 + t164 + t165 - m3_11 * m1_5 - m3_10 * m1_4 - m1_12 * m3_6 + t29);\nt275 = (-m3_10 * m2_4 + t56 - m2_10 * m3_4 + t62 - m3_12 * m2_6 - m2_11 * m3_5 + t53 - m3_11 * m2_5 - m2_12 * m3_6 + t179 + t181 + t185);\nt296 = (-m2_12 * m1_9 + t152 + t91 + t90 - m1_11 * m2_8 + t151 - m2_11 * m1_8 + t93 - m1_10 * m2_7 - m1_12 * m2_9 - m2_10 * m1_7 + t154);\nt303 = (t164 + t102 - m3_10 * m1_7 + t160 - m3_12 * m1_9 - m1_10 * m3_7 - m3_11 * m1_8 + t101 - m1_12 * m3_9 + t106 + t165 - m1_11 * m3_8);\nt317 = (t125 + t119 - m3_12 * m2_9 - m3_10 * m2_7 - m2_11 * m3_8 - m3_11 * m2_8 + t122 + t179 - m2_12 * m3_9 + t181 - m2_10 * m3_7 + t185);\nP(1,1) = t1 - 2 * m1_4 * m1_1 + t4 + t5 + t6 - 2 * m1_5 * m1_2 - 2 * m1_6 * m1_3 + t11 + t12;\nP(1,2) = 2 * t26;\nP(1,3) = 2 * t39;\nP(1,4) = t40 + t41 + t42 + t43 + t44 + t45 - 2 * m2_5 * m2_2 - 2 * m2_6 * m2_3 - 2 * m2_4 * m2_1;\nP(1,5) = 2 * t65;\nP(1,6) = t66 - 2 * m3_4 * m3_1 + t69 + t70 + t71 + t72 - 2 * m3_6 * m3_3 + t75 - 2 * m3_5 * m3_2;\nP(2,1) = -2 * m1_8 * m1_2 + t12 + t81 + t5 + t82 + t83 + t1 - 2 * m1_9 * m1_3 - 2 * m1_7 * m1_1;\nP(2,2) = 2 * t98;\nP(2,3) = 2 * t108;\nP(2,4) = -2 * m2_8 * m2_2 - 2 * m2_9 * m2_3 + t113 - 2 * m2_7 * m2_1 + t116 + t117 + t41 + t43 + t45;\nP(2,5) = 2 * t128;\nP(2,6) = t75 + t70 + t129 + t71 + t130 - 2 * m3_9 * m3_3 + t133 - 2 * m3_8 * m3_2 - 2 * m3_7 * m3_1;\nP(3,1) = -2 * m1_11 * m1_2 + t141 + t142 + t12 + t1 + t5 + t143 - 2 * m1_10 * m1_1 - 2 * m1_12 * m1_3;\nP(3,2) = 2 * t158;\nP(3,3) = 2 * t168;\nP(3,4) = t169 + t41 + t43 + t45 + t170 + t171 - 2 * m2_12 * m2_3 - 2 * m2_10 * m2_1 - 2 * m2_11 * m2_2;\nP(3,5) = 2 * t188;\nP(3,6) = t71 - 2 * m3_12 * m3_3 + t75 + t191 + t70 + t192 + t193 - 2 * m3_10 * m3_1 - 2 * m3_11 * m3_2;\nP(4,1) = -2 * m1_9 * m1_6 + t11 + t4 + t81 + t82 + t6 + t83 - 2 * m1_7 * m1_4 - 2 * m1_8 * m1_5;\nP(4,2) = 2 * t212;\nP(4,3) = 2 * t219;\nP(4,4) = t117 + t113 - 2 * m2_8 * m2_5 - 2 * m2_7 * m2_4 - 2 * m2_9 * m2_6 + t116 + t40 + t42 + t44;\nP(4,5) = 2 * t233;\nP(4,6) = t129 - 2 * m3_9 * m3_6 + t69 + t66 + t72 + t133 - 2 * m3_8 * m3_5 - 2 * m3_7 * m3_4 + t130;\nP(5,1) = t4 + t143 + t11 - 2 * m1_12 * m1_6 - 2 * m1_11 * m1_5 - 2 * m1_10 * m1_4 + t6 + t141 + t142;\nP(5,2) = 2 * t254;\nP(5,3) = 2 * t261;\nP(5,4) = t170 + t171 + t169 - 2 * m2_10 * m2_4 - 2 * m2_11 * m2_5 - 2 * m2_12 * m2_6 + t40 + t42 + t44;\nP(5,5) = 2 * t275;\nP(5,6) = t69 + t66 + t72 - 2 * m3_12 * m3_6 - 2 * m3_10 * m3_4 + t193 - 2 * m3_11 * m3_5 + t192 + t191;\nP(6,1) = t142 - 2 * m1_10 * m1_7 + t141 + t83 + t143 + t82 - 2 * m1_12 * m1_9 + t81 - 2 * m1_11 * m1_8;\nP(6,2) = 2 * t296;\nP(6,3) = 2 * t303;\nP(6,4) = t171 + t170 - 2 * m2_12 * m2_9 - 2 * m2_10 * m2_7 - 2 * m2_11 * m2_8 + t113 + t169 + t116 + t117;\nP(6,5) = 2 * t317;\nP(6,6) = -2 * m3_11 * m3_8 + t193 + t133 + t129 + t192 + t130 - 2 * m3_12 * m3_9 + t191 - 2 * m3_10 * m3_7;\n", "meta": {"author": "cvlab-epfl", "repo": "EPnP", "sha": "f9d27b186d9c754b72e076b3843f47ad136e9799", "save_path": "github-repos/MATLAB/cvlab-epfl-EPnP", "path": "github-repos/MATLAB/cvlab-epfl-EPnP/EPnP-f9d27b186d9c754b72e076b3843f47ad136e9799/matlab/EPnP/compute_constraint_distance_3param_6eq_6unk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3865195663926892}}
{"text": "function doseStat = dispDoseStats(doseBinsV, volHistV, name, nameVol, planC, indexS, opt)\n%Command line display of basic dose statistics\n%doseBinsV is a vector of the midpoint doseBin values.\n%volHistV is either a histogram of volumes or surface areas.\n%LM: 14 Oct 02, JOD.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nswitch lower(opt)\n\n case 'standarddose'\n disp('-----------------------')\n disp('')\n disp(['Structure is: ' name])\n\n totalVol = sum(volHistV);\n disp(['Total volume is: ' num2str(totalVol) ' cubic cm.'])\n\n disp(['Dose map name is: ' nameVol])\n\n meanD = sum(doseBinsV(:).*volHistV(:))/sum(volHistV);\n disp(['Mean dose is: ' num2str(meanD)])\n\n ind = max(find([volHistV~=0]));\n maxD = doseBinsV(ind);\n disp(['Max dose is: ' num2str(maxD)])\n\n ind = min(find([volHistV~=0]));\n minD = doseBinsV(ind);\n \n disp(['Min dose is: ' num2str(minD)])\n disp('')\n disp('-----------------------')\n \n doseStat.volume = totalVol;\n\n case 'dshdose'\n\n disp('-----------------------')\n disp('')\n disp(['Structure is: ' name])\n\n areaV = volHistV; %actually areas, not volumes.\n dosesV = doseBinsV;\n\n totalArea = sum(areaV);\n disp(['Total surface area is: ' num2str(totalArea) ' square cm.'])\n \n disp(['Dose map name is: ' nameVol])\n\n meanD = sum(dosesV(:).*areaV(:))/sum(areaV);\n disp(['Mean surface dose is: ' num2str(meanD)])\n\n maxD = max(dosesV);\n disp(['Max dose is: ' num2str(maxD)])\n\n minD = min(dosesV);\n \n disp(['Min dose is: ' num2str(minD)])\n disp('')\n disp('-----------------------')\n \n doseStat.volume = totalArea;\n\nend\n\ndoseStat.min = minD;\ndoseStat.mean = meanD;\ndoseStat.max = maxD;\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanAnalysis/DoseVolumeHistograms/dispDoseStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.38630253392019237}}
{"text": "function [vs, output, v0] = computeRatioConfidenceInterval(v0, expdata, model, max_score, ratio)\n\n% v0 - set of flux vectors to be used as initial guesses. They may be\n% valid or not.\n% expdata - experimental data.\n% model - The standard model. Additional field .N (= null(S)) should also\n% be provided. This is a basis of the flux space.\n% max score - maximum allowable data fit error. \n% ratio - which reactions to take the ratio of. positive values indicate\n% reactions in the numerator and negative values, reactions in the\n% denominator. \n\nmajorIterationLimit = 2000; %max number of iterations\nminorIterationLimit = 1e7; % essentially infinity\ndiffInterval = 1e-5; %gradient step size.\nfeasibilityTolerance = max_score/20; % how close you need to be to the max score.\n\nx0 = model.N\\v0; % back substitute\nnumpoints = size(v0,2);\nnumratios = size(ratio,2);\n\nscores = zeros(numpoints,1);\n\ntProb.user.expdata = expdata;\ntProb.user.model = model;\nfor i = 1:numpoints\n scores(i) = errorComputation2(x0(:,i),tProb);\nend\n\nv0(:,scores > max_score) = fitC13Data(v0(:,scores > max_score),expdata,model);\n\nif ~isfield(model, 'N')\n model.N = null(model.S); \nend\n\nx0 = model.N\\v0; % back substitute\n\n% safety check:\nif (max(abs(model.S*v0))> 1e-6)\n display('v0 not quite in null space');\n pause;\nend\nif(max(abs(model.N*x0 - v0)) > 1e-6)\n display('null basis is weird');\n pause;\nend\n\n\nnalpha = size(model.N, 2);\nx_L = -1000*ones(nalpha,1);\nx_U = 1000*ones(nalpha,1);\nName = 't2';\n[A, b_L, b_U] = defineLinearConstraints(model);\n\n\nscores = zeros(numpoints,1);\n% compute scores for all points.\nfor i = 1:numpoints\n scores(i) = errorComputation2(x0(:,i),tProb);\nend\nvalid_index = scores < max_score + feasibilityTolerance;\nfprintf('found %d valid points\\n', sum(valid_index));\n\n\nc = 'errorComputation2'; \nc_L = 0; c_U = max_score; \n\ndc = 'errorComputation2_grad'; \nd2c = []; ConsPattern = [];\n%pSepFunc = [];\nx_min = []; x_max = []; f_opt = []; x_opt = [];\nH = []; HessPattern = []; pSepFunc = []; fLowBnd = [];\nSolver = 'snopt';\n\noutputminv = 222*ones(numratios, numpoints);\noutputminexitflag = -222*ones(numratios, numpoints);\noutputminfinalscore = -222*ones(numratios, numpoints);\noutputmaxv = -222*ones(numratios, numpoints);\noutputmaxexitflag = -222*ones(numratios, numpoints);\noutputmaxfinalscore = -222*ones(numratios, numpoints);\noutputminstruct = cell(numratios, numpoints);\noutputmaxstruct = cell(numratios, numpoints);\n \n%iterate through directions\nfor i = 1:numratios\n%for i = 10:200\n for j = -1:2:1 % max and min \n ration = zeros(size(objective_coefficient(1,model)));\n ratiod = zeros(size(objective_coefficient(1,model)));\n for m = 1:size(ratio,1);\n if(ratio(m,i) > 0)\n ration = ration + objective_coefficient(m,model)*j;\n elseif(ratio(m,i) < 0)\n ratiod = ratiod + objective_coefficient(m,model);\n end\n end\n\n\n % initialize temp variables to make parfor work.\n v = j*222*ones(1,numpoints);\n exitflag = -222*ones(1,numpoints);\n finalscore = 222*ones(1,numpoints);\n ostruct = cell(1,numpoints);\n\n for k = 1:numpoints\n if exist('ttt.txt', 'file')\n fprintf('quitting due to file found\\n');\n continue;\n end\n xinitial = x0(:,k);\n% Prob = lpconAssign(d, x_L, x_U, Name, xinitial,...\n% A, b_L, b_U,...\n% c, dc, d2c, ConsPattern, c_L, c_U,...\n% fLowBnd, x_min, x_max, f_opt,\n% x_opt);\n\n\n Prob = conAssign('ratioScore', 'ratioScore_grad', H, HessPattern, x_L, x_U, Name, xinitial, ...\n pSepFunc, fLowBnd, ...\n A, b_L, b_U, c, dc, d2c, ConsPattern, c_L, c_U, ...\n x_min, x_max, f_opt, x_opt);\n %Prob.NumDiff = 2; % central diff\n %Prob.optParam.CentralDiff = 1e-5;\n %pause;\n Prob.user.expdata = expdata;\n Prob.user.model = model;\n Prob.user.ration = ration;\n Prob.user.ratiod = ratiod;\n\n Prob.user.max_error = max_score;\n Prob.user.diff_interval = diffInterval;\n Prob.user.useparfor = true;\n\n Prob.optParam.IterPrint = 0;\n %Prob.optParam.cTol = .1*feasibilityTolerance;\n\n Prob.PriLevOpt = 1;\n Prob.SOL.PrintFile = strcat('temp/snoptp', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt');\n Prob.SOL.SummFile = strcat('temp/snopts', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt');\n Prob.SOL.optPar(35) = majorIterationLimit; %This is major iteration count.\n Prob.SOL.optPar(30) = minorIterationLimit; %total iteration limit;\n %Prob.SOL.optPar(11) = feasibilityTolerance; % feasibility tolerance\n\n Result = tomRun(Solver, Prob, 5);\n tscore = errorComputation2(Result.x_k, tProb);\n tbest = Result.f_k;\n\n fprintf('reaction %d (%d), x %d; x=%f (%f); score=%f (%f)\\n', i,length(model.lb),j, tbest,fLowBnd, tscore, max_score)\n\n v(k) = j*tbest;\n exitflag(k) = Result.Inform;\n finalscore(k) = tscore;\n ostruct{k} = Result;\n end\n if (j > 0) %minimizing\n outputminv(i,:) = v; % multiply by j to correct sign.\n outputminexitflag(i,:) = exitflag;\n outputminfinalscore(i,:) = finalscore;\n outputminstruct(i,:) = ostruct;\n else\n outputmaxv(i,:) = v; % multiply by j to correct sign.\n outputmaxexitflag(i,:) = exitflag;\n outputmaxfinalscore(i,:) = finalscore;\n outputmaxstruct(i,:) = ostruct;\n end\n end\nend\n\noutput.minv = outputminv;\noutput.maxv = outputmaxv;\noutput.minexitflag = outputminexitflag;\noutput.maxexitflag = outputmaxexitflag;\noutput.minfinalscore = outputminfinalscore;\noutput.maxfinalscore = outputmaxfinalscore;\noutput.minstruct = outputminstruct;\noutput.maxstruct = outputmaxstruct;\n\nvs = zeros(numratios, 2);\nfor i = 1:numratios\n validindex = output.minfinalscore(i,:) < max_score + feasibilityTolerance;\n if any(validindex)\n vs(i,1) = min(output.minv(i,validindex));\n else\n vs(i,1) = 222;\n end\n validindex = output.maxfinalscore(i,:) < max_score + feasibilityTolerance;\n if any(validindex)\n vs(i,2) = max(output.maxv(i,validindex));\n else\n vs(i,2) = -222;\n end \nend\n\nreturn;\n\n\n\n% function that returns the proper objective coefficient for each reaction\n% takes into account the reversibility of reactinos etc.\nfunction [d] = objective_coefficient(i, model)\nd = zeros(length(model.lb),1);\nd(i) = 1;\nif (model.match(i))\n d(model.match(i)) = -1;\nend\nd = (d'*model.N)'; % transform to null space;\nreturn\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/deprecated/_fluxomics_obsolete/computeRatioConfidenceInterval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3860916262668606}}
{"text": "function [ymu,ys2,fmu,fs2,dymu,dys2,dfmu,dfs2] = gpgrad(x0,gpstruct,method,dx)\n%GPGRAD Gradient of Gaussian process mean prediction\n\nif nargin < 3 || isempty(method); method = 'central'; end\nif nargin < 4 || isempty(dx); dx = 1e-6; end\n\nD = size(x0,2);\nNhyp = length(gpstruct.hyp);\n\n% Initialize variables\nymu = zeros(Nhyp,1);\nfmu = zeros(Nhyp,1);\nys2 = zeros(Nhyp,1);\nfs2 = zeros(Nhyp,1);\n\nif nargout > 4\n dymu = zeros(Nhyp,D);\n dfmu = zeros(Nhyp,D);\n dys2 = zeros(Nhyp,D);\n dfs2 = zeros(Nhyp,D);\nend\n\n% Compute predictions and derivatives for each hyperparameter sample\nfor i = 1:Nhyp\n \n try\n if nargout > 4\n [dy,y0] = fgrad(@(xi_) gpfunc(xi_,gpstruct,gpstruct.hyp(i)),x0,method,'Vectorized','Step',dx); \n else\n y0 = gpfunc(x0,gpstruct,gpstruct.hyp(i));\n end\n catch\n y0 = NaN(1,4);\n if nargout > 4; dy = NaN(4,D); end\n warning('bads:gpGradFail', 'Error in computing the GP derivative.');\n end\n \n ymu(i) = y0(1); \n ys2(i) = y0(2);\n fmu(i) = y0(3);\n fs2(i) = y0(4);\n \n if nargout > 4\n dymu(i,:) = dy(1,:);\n dfmu(i,:) = dy(2,:);\n dys2(i,:) = dy(3,:);\n dfs2(i,:) = dy(4,:);\n end\n \n \nend\n\n%--------------------------------------------------------------------------\n\nfunction yy = gpfunc(xi,gpstruct,hyp)\n if gpstruct.gpmlext\n % Pre-computed Laplace approximation at MAP\n if isfield(gpstruct,'hypSigma') && ~isempty(gpstruct.hypSigma)\n hyp.Sigma = gpstruct.hypSigma;\n end\n \n if isfield(gpstruct,'post') && ~isempty(gpstruct.post)\n % [ymuib,ys2ib,fmuib,fs2ib] = mygp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...\n %gpstruct.lik,gpstruct.x,gpstruct.post,xi);\n \n [ymui,ys2i,fmui,fs2i] = mgp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...\n gpstruct.lik,gpstruct.x,gpstruct.post,xi);\n \n %[fmuib(:) - fmui(:), sqrt(fs2ib(:)) - sqrt(fs2i(:))]\n \n else\n [ymui,ys2i,fmui,fs2i] = mgp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...\n gpstruct.lik,gpstruct.x,gpstruct.y,xi);\n end\n yy = [ymui,ys2i,fmui,fs2i];\n else\n \n if isfield(gpstruct,'post') && ~isempty(gpstruct.post)\n [ymui,ys2i,fmui,fs2i] = mygp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...\n gpstruct.lik,gpstruct.x,gpstruct.post,gpstruct.s,xi);\n else\n [ymui,ys2i,fmui,fs2i] = mygp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...\n gpstruct.lik,gpstruct.x,gpstruct.y,gpstruct.s,xi);\n end\n \n if 1\n % [~, ymui, ys2i] = feval(gpstruct.lik{:}, hyp.lik, [], fmui, fs2i);\n \n lik = hyp.lik; lik(end) = -Inf;\n % fmuiold = fmui; fs2iold = fs2i;\n [~, fmui, fs2i] = feval(gpstruct.lik{:}, lik, [], [], fmui, fs2i);\n end\n \n yy = [ymui,ys2i,fmui,fs2i];\n % [ymui,sqrt(ys2i),fmui,sqrt(fs2i),fmuiold,sqrt(fs2iold)]\n end\n \n ", "meta": {"author": "acerbilab", "repo": "bads", "sha": "019f0b432b9e157a31defbbd303aadcdf57862e7", "save_path": "github-repos/MATLAB/acerbilab-bads", "path": "github-repos/MATLAB/acerbilab-bads/bads-019f0b432b9e157a31defbbd303aadcdf57862e7/utils/gpgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.38587960858502474}}
{"text": "function aistats2012_slides_gp\n\nrandn('state', 1);\n\nplot_gp(true, 0.2, 0.4, 100, false, ...\n '/home/jluttine/papers/aistats2012/slides/fig_short', ...\n 8, 8);\nplot_gp(true, 1.5, 0.4, 100, false, ...\n '/home/jluttine/papers/aistats2012/slides/fig_long', ...\n 8, 8);\nplot_gp(false, 1, 0.2, 6, 5, ...\n '/home/jluttine/papers/aistats2012/slides/fig_gp', ...\n 6, 4);\n\nfunction plot_gp(noisy, lengthscale, noise, N_all, samples, filename, width, height);\nxmin = 0;\nxmax = 10;\n\nNh = 1000;\nxh = linspace(xmin, xmax, Nh);\n\nx_all = linspace(xmin+0.5, xmax-0.5, N_all);\n%x_all = unifrnd(xmin, xmax, 1, N_all);\n\n% Generate data\ncovfunc_all = gp_cov_sum(gp_cov_se(sq_dist(x_all), ...\n 'lengthscale', lengthscale), ...\n gp_cov_scale(gp_cov_delta(N_all), ...\n 'scale', noise));\n\nK_y = covfunc_all([]);\nL_y = chol(K_y + 1e-6*eye(N_all), 'lower');\ny_all = L_y * randn(N_all,1);\n\nfor N = [N_all]\n x = x_all(:,1:N);\n y = y_all(1:N);\n\n covfunc_y = gp_cov_sum(gp_cov_se(sq_dist(x), ...\n 'lengthscale', lengthscale), ...\n gp_cov_scale(gp_cov_delta(N), ...\n 'scale', noise));\n covfunc_yf = gp_cov_se(sq_dist(x,xh), ...\n 'lengthscale', lengthscale);\n if noisy\n covfunc_f = gp_cov_sum(gp_cov_se(zeros(Nh,1), ...\n 'lengthscale', lengthscale), ...\n gp_cov_scale(gp_cov_wrap(ones(Nh,1)), ...\n 'scale', 0.3));\n else\n covfunc_f = gp_cov_se(zeros(Nh,1), ...\n 'lengthscale', lengthscale);\n end\n\n K_y = covfunc_y([]);\n K_yf = covfunc_yf([]);\n k_f = covfunc_f([]);\n\n [fh_mean, fh_var] = gp_predict(y, K_y, K_yf, k_f);\n figure\n errorplot(xh, fh_mean, sqrt(fh_var))\n hold on\n plot(x, y, 'r+')\n set(gca, 'xtick', [], 'ytick', []);\n set(gca, 'box', 'off');\n set_figure_size(width,height);\n print('-dpdf', [filename, '.pdf'])\n yl = get(gca, 'ylim');\n\n if samples\n covfunc_f = gp_cov_se(sq_dist(xh), ...\n 'lengthscale', lengthscale);\n K_f = covfunc_f([]);\n K_post = K_f - K_yf'*(K_y\\K_yf) + 1e-6*eye(Nh);\n L_post = chol(K_post, 'lower');\n f = bsxfun(@plus, ...\n K_yf'*(K_y\\y), ...\n L_post*randn(Nh,samples));\n figure\n plot(xh, f);\n hold on\n plot(x, y, 'k+');\n set(gca, 'xtick', [], 'ytick', []);\n set(gca, 'box', 'off');\n set(gca, 'ylim', yl);\n set_figure_size(width,height); \n print('-dpdf', [filename, '_samples.pdf'])\n end\n \nend\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/publications/aistats2012/aistats2012_slides_gp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.38566038773005334}}
{"text": "function [dP_dV, dP_dlam] = cpf_p_jac(parameterization, z, V, lam, Vprv, lamprv, pv, pq)\n%CPF_P_JAC Computes partial derivatives of CPF parameterization function.\n% [DP_DV, DP_DLAM ] = CPF_P_JAC(PARAMETERIZATION, Z, V, LAM, ...\n% VPRV, LAMPRV, PV, PQ)\n%\n% Computes the partial derivatives of the continuation power flow\n% parameterization function w.r.t. bus voltages and the continuation\n% parameter lambda.\n%\n% Inputs:\n% PARAMETERIZATION : Value of cpf.parameterization option.\n% Z : normalized tangent prediction vector from previous step\n% V : complex bus voltage vector at current solution\n% LAM : scalar lambda value at current solution\n% VPRV : complex bus voltage vector at previous solution\n% LAMPRV : scalar lambda value at previous solution\n% PV : vector of indices of PV buses\n% PQ : vector of indices of PQ buses\n%\n% Outputs:\n% DP_DV : partial of parameterization function w.r.t. voltages\n% DP_DLAM : partial of parameterization function w.r.t. lambda\n%\n% See also CPF_PREDICTOR, CPF_CORRECTOR.\n\n% MATPOWER\n% Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n% by Shrirang Abhyankar, Argonne National Laboratory\n% and Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\nif parameterization == 1 %% natural\n npv = length(pv);\n npq = length(pq);\n dP_dV = zeros(1, npv+2*npq);\n if lam >= lamprv\n dP_dlam = 1.0;\n else\n dP_dlam = -1.0;\n end\nelseif parameterization == 2 %% arc length\n Va = angle(V);\n Vm = abs(V);\n Vaprv = angle(Vprv);\n Vmprv = abs(Vprv);\n dP_dV = 2*([Va([pv; pq]); Vm(pq)] - [Vaprv([pv; pq]); Vmprv(pq)])';\n if lam == lamprv %% first step\n dP_dlam = 1.0; %% avoid singular Jacobian that would result\n %% from [dP_dV, dP_dlam] = 0\n else\n dP_dlam = 2*(lam-lamprv);\n end\nelseif parameterization == 3 %% pseudo arc length\n nb = length(V);\n dP_dV = z([pv; pq; nb+pq])';\n dP_dlam = z(2*nb+1);\nend \n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/cpf_p_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3856015228640355}}
{"text": "% General state space model for gps imu integration formulated in n-frame\n% either in psi model or phi model. Psi model only appears in some\n% papers, Phi model is well documented in books like Jekeli 2000, Titterton\n% and Weston, 2000.\n\n% states: IMU position in e frame, IMU velocity in n frame, \n% attitude w.r.t n frame, accelerometer and gyro biases, accelerometer and gyro scale factors\n\n% the error states are delta(r x,y,z in earth centered\n% \"abused\" n frame), delta(vx, vy, vz in n frame),\n% delta(roll, pitch, yaw) of the imu, accelerometer and gyro bias drift, acc\n% scale and gyro scale factor error\n% accelerometer and gyro bias are usually modeled as random walk, it can\n% also be random constant, This does not make much difference\n% acc scale and gyro scale factor are usually modeled as random walk, it can\n% also be random constant, This does not make much difference\n\n% The state dynamics are driven by a 18 (accel and gyro white noise,\n% bias white noise and scale factor white noise) or 6 (only accel and\n% gyro white noise) dimensional white Gaussian\n% noise and the observations are corrupted by white Gaussian noise\n% test cases: (1) random walk bias and scale facotr error, random constant\n% bias and scale factor error, \n% (2) covariance update step > sample interval\n% (3) different imy types, 3DM GX3-35 AND h764g\n% (4) psi and phi model\n% There is a very subtle point in implementing a class in matlab. Always\n% call a class the same name, do not call it a filter in a function and a\n% model at another. It causes strange behaviors.\nclassdef EKF_filter_nframe < handle\n properties (Hidden)\n type = 'ekf';\n tag = 'EKF_IMU_GPS_NFRM'; % ID tag\n covDim=9+12; % the dimension of covariance matrix\n end\n % The following properties can be set only by class methods\n properties (SetAccess = private)\n invalidateIMUerrors; % reset IMU errors when they goes beyond expectation\n imuType; % the type of IMU, e.g., MEMS 3DX GM 3-35, HG1700, etc.\n imuErrorModel=3;\n % the IMU error model corresponding to random walk bias and\n % random walk scale factor error,\n % 1 without turn on bias estimates,first order GM bias and random walk scale factor errors\n % 2 with random constant turn on bias estimates, first order GM bias and random walk scale factor errors\n % 3 assumes bias and scale factors are random walks\n % 4 assumes random constant bias and random constant scale factor errors\n \n % transform from vehicle body frame to IMU sensor frame \n Cb2imu;\n dt; % sampling interval of IMU, unit sec\n % the translation from antenna to IMU sensor frame, i.e., the antenna's\n % position in the s-frame.\n Tant2imu;\n Cen; % rotation from e frame to n frame\n height; % h in geodetic coordinates\n qs2n; % q s(sensor) 2 navigation frame\n Vn; % velocity of the IMU sensor in n frame\n imuErrors; %ba, bg, sa, sg\n \n imuOrientSIP=7; % imu orientation covariance start index\n imuBiasDriftSIP=10; %imu bias error covariance start index\n imuScaleFactorSIP=16;\n p_k_k; % the covariance of the entire state vector\n mode=1; % 1 for phi model, 2 for psi model\n mechanization=2; % 1 for wander azimuth, 2 for local geodetic\n rvqs2e; % added only for compatibility\n camPose; % added only for compatibility\n end\n methods\n function filter = EKF_filter_nframe(options)\n filter.invalidateIMUerrors=options.InvalidateIMUerrors;\n filter.imuType=options.imutype;\n filter.imuErrorModel=options.imuErrorModel; \n filter.dt=options.dt;\n filter.Cb2imu=options.Cb2imu;\n filter.Tant2imu=filter.Cb2imu*(options.Tant2body-options.Timu2body);\n filter.Vn=options.Vn;\n % initialize states and covariance for imu gps integration,\n % For imu, rs in n, vs in n, q s2n, ba, bg, sa, sg. (s denotes imu)\n % the position of GPS antenna\n inillh=options.inillh_ant;\n % Cb2n initial value given by external reference\n initqbn=options.qb2n; % H764G INS data, this b refers to the vehicle body frame\n filter.qs2n=quatmult_v001(initqbn,rotro2qr(filter.Cb2imu),2);\n \n Ce2n0=llh2dcm_v000(inillh(1:2),[0;1]);\n qs2e=quatmult_v001(rotro2qr(Ce2n0), filter.qs2n,1);\n xyz_imu=ecef2geo_v000(inillh,1)-quatrot_v000(qs2e,filter.Tant2imu,0);\n inillh_imu=ecef2geo_v000(xyz_imu, 0);\n filter.height=inillh_imu(3); %elipsoidal height\n filter.Cen=llh2dcm_v000(inillh_imu(1:2),[0;1]);\n filter.imuErrors=options.imuErrors;\n filter.p_k_k=zeros(filter.covDim);\n filter.p_k_k(1:3,1:3)=eye(3)*1^2; %position errors in meter\n filter.p_k_k(4:6,4:6)=eye(3)*0.1^2; %vel error in m/s\n filter.p_k_k(filter.imuOrientSIP+(0:2),filter.imuOrientSIP+(0:2))=...\n diag([options.initAttVar,options.initAttVar,options.initAttVar*2].^2);\n \n IMU_ERRDEF=imu_err_defs_v000(options.imutype);\n filter.p_k_k(filter.imuBiasDriftSIP+(0:2),filter.imuBiasDriftSIP+(0:2))=4*eye(3)*IMU_ERRDEF.acc_bias_var;% enlarge initial std by 2\n filter.p_k_k(filter.imuBiasDriftSIP+(3:5),filter.imuBiasDriftSIP+(3:5))=4*eye(3)*IMU_ERRDEF.gyro_bias_var;\n \n filter.p_k_k(filter.imuScaleFactorSIP+(0:2),filter.imuScaleFactorSIP+(0:2))=4*eye(3)*IMU_ERRDEF.acc_scale_var;\n filter.p_k_k(filter.imuScaleFactorSIP+(3:5),filter.imuScaleFactorSIP+(3:5))=4*eye(3)*IMU_ERRDEF.gyro_scale_var;\n filter.mode= options.mode;\n end\n %===============================================================================================\n %-- State transition function\n % propogate state with accelerometer and gyro input at time k-1 to state at k,\n % i.e., X(k|k-1), from state at k-1. U1 contains IMU measurement\n % delta v, and delta angle of gyro or acc and angular rate\n % and 7th row is the previous epoch(k-1) and 8th row is the current epoch(k)\n % imuaccum records the accumulated delta v and delta angle for two speed\n % covariance update\n function imuaccum= ffun_state(filter, imuaccum, U1)\n if(sum(abs(U1(1:3,1)))<1)\n dt1=U1(8,end)-U1(7,1);\n gyroinc=sum(U1(4:6,:),2);\n accinc=sum(U1(1:3,:),2);\n \n %reset the imu errors if estimates diverges\n IMU_ERRDEF=imu_err_defs_v000(filter.imuType);\n \n if(filter.invalidateIMUerrors)\n spuracc=find(abs(filter.imuErrors(1:3))>2*IMU_ERRDEF.initacc_bias_err,1);\n spurgyro=find(abs(filter.imuErrors(4:6))>2*IMU_ERRDEF.initgyro_bias_err,1);\n if(~isempty(spuracc)||~isempty(spurgyro))\n disp(['IMU errors diverge at ' num2str(U1(8,end)) '!']);\n filter.imuErrors=zeros(12,1);\n end\n end \n angleinc=gyroinc-filter.imuErrors(4:6)*dt1-diag(gyroinc)*filter.imuErrors(6+(4:6))/1000;\n velinc=accinc-filter.imuErrors(1:3)*dt1-diag(accinc)*filter.imuErrors(6+(1:3))/1000;\n %imu data accumulator for the covariance update\n imuaccum=imuaccum+[velinc;angleinc];\n else\n dt1=U1(8,end)-U1(7,1);\n gyroinc=mean(U1(4:6,:),2);\n accinc=mean(U1(1:3,:),2);\n \n %reset the imu errors if estimates diverges\n IMU_ERRDEF=imu_err_defs_v000(filter.imuType);\n \n if(filter.invalidateIMUerrors)\n spuracc=find(abs(filter.imuErrors(1:3))>2*IMU_ERRDEF.initacc_bias_err,1);\n spurgyro=find(abs(filter.imuErrors(4:6))>2*IMU_ERRDEF.initgyro_bias_err,1);\n if(~isempty(spuracc)||~isempty(spurgyro))\n disp(['IMU errors diverge at ' num2str(U1(8,end)) '!']);\n filter.imuErrors=zeros(12,1);\n end\n end\n gyroinc=gyroinc-filter.imuErrors(4:6)-diag(gyroinc)*filter.imuErrors(6+(4:6))/1000;\n accinc=accinc-filter.imuErrors(1:3)-diag(accinc)*filter.imuErrors(6+(1:3))/1000;\n angleinc=gyroinc*dt1;\n velinc=accinc*dt1; \n %imu data accumulator for the covariance update\n imuaccum=imuaccum+[accinc;gyroinc]*dt1; \n end\n %run strapdown with angle and velocity increments\n [filter.qs2n, filter.Vn, filter.Cen, filter.height]=strapdown_Cen_quat_v000(...\n filter.qs2n, filter.Vn, filter.Cen, filter.height, velinc, angleinc, dt1); \n end\n function ffun_covariance(filter, imuaccum, covupt_time, curimutime)\n %propagate the covariance corresponds to states, rs in n, vs in n, \\psi or \\phi,\n % ba, bg, sa, sg\n covdt=curimutime-covupt_time; \n [STM, Qd]=sys_metric_phipsi_v000(filter.Cen, filter.height, ...\n filter.Vn, filter.qs2n, imuaccum(1:3)/covdt,imuaccum(4:6)/covdt, ...\n covdt,filter.mode,filter.imuType, filter.imuErrorModel); %use psi implementation with 2\n % if(filter.imuErrorModel==4)\n % [STM, Qd]=sys_metric_phipsi_v002(filter.Cen, filter.height, ...\n % filter.Vn, filter.qs2n, imuaccum(1:3)/covdt,imuaccum(4:6)/covdt, ...\n % covdt,filter.mode,filter.imuType); %use psi implementation with 2\n % assert(norm(STM1-STM)+norm(Qd1-Qd)<1e-5);\n % end\n filter.p_k_k=STM*filter.p_k_k*STM'+Qd; % the covariance of the navigation states and imu error terms\n end\n %==============================================================================================\n %update both the covariance and state\n function correctstates(filter, predict,measure, H,R, ~)\n p_km1_k=filter.p_k_k;\n inno= predict-measure;\n %Kalman\n K=p_km1_k*H'/(H*p_km1_k*H'+R);\n deltaX=K*inno;\n % update covariance\n filter.p_k_k=(eye(filter.covDim)-K*H)*p_km1_k*(eye(filter.covDim)-K*H)'+K*R*K';\n % compute updated state\n [filter.qs2n, filter.Vn, filter.Cen, filter.height]=correctnav_Cen_v000(...\n filter.qs2n, filter.Vn, filter.Cen, filter.height,...\n deltaX(1:filter.imuOrientSIP+2), filter.mode, filter.mechanization); \n filter.imuErrors = filter.imuErrors + deltaX(filter.imuBiasDriftSIP:end);\n end\n % output: position of the IMU in a NED frame anchored at some point or in geodetic coordinates,\n % velocity of the IMU in the body frame, and euler angles of\n % rotation from body frame to the moving NED frame, and covariances\n % of 9 navigation ERROR states in the filter\n function SaveToFile(filter, inillh_ant, preimutime, ffilres) \n vr_c=rotqr2eu('xyz',quatmult_v001(filter.qs2n, rotro2qr(filter.Cb2imu), 0))*180/pi; % body frame w.r.t the moving N frame\n xyz_imu= ecef2geo_v000([asin(-filter.Cen(3,3));asin(-filter.Cen(2,1));filter.height],1);\n % xyz_ant= xyz_imu + quatrot_v000(quatmult_v001(rotro2qr(filter.Cen),filter.qs2n,1),filter.Tant2imu,0);\n if(~isempty(inillh_ant))\n vr_a=posdiff_v001(xyz_imu, inillh_ant); % position of IMU in the initial N frame\n fwrite(ffilres,[preimutime;vr_a;filter.Vn;vr_c;sqrt(diag(filter.p_k_k(1:9,...\n 1:9)))],'double');\n else\n fwrite(ffilres,[preimutime;ecef2geo_v000(xyz_imu,0);filter.Vn;vr_c;sqrt(diag(filter.p_k_k(1:9,...\n 1:9)))],'double');\n end\n end\n function mag=GetVelocityMag(filter)\n mag=norm(filter.Vn,2); \n end\n function SetCamAndRvqs2e(filter, options)\n filter.rvqs2e=zeros(10,1);\n Ce2n=filter.Cen;\n heights2n=filter.height;\n Re=6378137/(sqrt(1.0-0.00669437999014*Ce2n(3,3)^2));\n filter.rvqs2e(1:3,1)=-[(Re+heights2n)*Ce2n(3,1);(Re+heights2n)*Ce2n(3,2);(Re*(1-0.00669437999014)+heights2n)*Ce2n(3,3)];\n filter.rvqs2e(4:6,1)=Ce2n'*filter.Vn;\n filter.rvqs2e(7:10,1)=quatmult_v001(rotro2qr(Ce2n),filter.qs2n,1); \n filter.camPose=zeros(7,1);\n filter.camPose(5:7)=options.Cimu2cam*options.Cb2imu*(options.Timu2body-options.Tcam2body);\n filter.camPose(1:4)=rotro2qr(options.Cimu2cam);\n end\n end\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/ekf/EKF_filter_nframe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3854345617876433}}
{"text": "function [f0v,vrv,dfv,nf,aav]=fixpF0VexMltpBG4(x,fs,f0floor,nvc,nvo,mu,imgi,shiftm,smp,minm,pc,nc)\n\n%\tFixed point analysis to extract F0\n%\t[f0v,vrv,dfv,nf]=fixpF0VexMltpBG4(x,fs,f0floor,nvc,nvo,mu,imgi,shiftm,smp,minm,pc,nc)\n%\tx\t: input signal\n%\tfs\t: sampling frequency (Hz)\n%\tf0floor\t: lowest frequency for F0 search\n%\tnvc\t: total number of filter channels\n%\tnvo\t: number of channels per octave\n%\tmu\t: temporal stretching factor\n%\timgi\t: image display indicator (1: display image, default)\n%\tshiftm\t: frame shift in ms\n%\tsmp\t: smoothing length relative to fc (ratio)\n%\tminm\t: minimum smoothing length (ms)\n%\tpc\t: exponent to represent nonlinear summation\n%\tnc\t: number of harmonic component to use (1,2,3)\n\n%\tDesigned and coded by Hideki Kawahara\n%\t28/March/1999\n%\t04/April/1999 revised to multi component version\n%\t07/April/1999 bi-reciprocal smoothing for multi component compensation\n%\t01/May/1999 first derivative of Amplitude is taken into account\n%\t17/Dec./2000 display bug fix\n%\t19/Sep./2002 bug fix (mu information was discarded.)\n% 07/Dec./2002 waitbar was added\n%\t30/April/2005 modification for Matlab v7.0 compatibility\n%\t10/Aug./2005 modified by Takahashi on waitbar\n%\t10/Sept./2005 mofidied by Kawahara on waitbar\n% 11/Sept./2005 fixed waitbar problem\n\t\t\n%f0floor=40;\n%nvo=12;\n%nvc=52;\n%mu=1.1;\n\nx=cleaninglownoise(x,fs,f0floor);\n\nfxx=f0floor*2.0.^((0:nvc-1)/nvo)';\nfxh=max(fxx);\n\ndn=max(1,floor(fs/(fxh*6.3)));\n\nif nc>2\n\tpm3=multanalytFineCSPB(decimate(x,dn),fs/dn,f0floor,nvc,nvo,mu,3,imgi); % error crrect 2002.9.19 (mu was fixed 1.1)\n\tpif3=zwvlt2ifq(pm3,fs/dn);\n\t[~,mm]=size(pif3);\n\tpif3=pif3(:,1:3:mm);\n\tpm3=pm3(:,1:3:mm);\nend;\n\nif nc>1\n\tpm2=multanalytFineCSPB(decimate(x,dn),fs/dn,f0floor,nvc,nvo,mu,2,imgi);% error crrect 2002.9.19(mu was fixed 1.1)\n\tpif2=zwvlt2ifq(pm2,fs/dn);\n\t[~,mm]=size(pif2);\n\tpif2=pif2(:,1:3:mm);\n\tpm2=pm2(:,1:3:mm);\nend;\n\npm1=multanalytFineCSPB(decimate(x,dn*3),fs/(dn*3),f0floor,nvc,nvo,mu,1,imgi);% error crrect 2002.9.19(mu was fixed 1.1)\n%%%% safe guard added on 15/Jan./2003\nmxpm1=max(max(abs(pm1)));\neeps=mxpm1/10000000;\npm1(pm1==0)=pm1(pm1==0)+eeps;\n%%%% safe guard end\npif1=zwvlt2ifq(pm1,fs/(dn*3));\n%keyboard;\n\n[~,mm1]=size(pif1);\nmm=mm1;\nif nc>1\n\t[~,mm2]=size(pif2);\n\tmm=min(mm1,mm2);\nend;\n\nif nc>2\n\t[~,mm3]=size(pif3);\n\tmm=min([mm1 mm2 mm3]);\nend;\n\nif nc == 2\n\tfor ii=1:mm\n\t\tpif2(:,ii)=(pif1(:,ii).*(abs(pm1(:,ii))).^pc ...\n\t\t\t+pif2(:,ii)/2.*(abs(pm2(:,ii))).^pc )...\n\t\t\t./((abs(pm1(:,ii))).^pc+(abs(pm2(:,ii))).^pc);\n\tend;\nend;\nif nc == 3 \n\tfor ii=1:mm\n\t\tpif2(:,ii)=(pif1(:,ii).*(abs(pm1(:,ii))).^pc ...\n\t\t\t+pif2(:,ii)/2.*(abs(pm2(:,ii))).^pc ...\n\t\t\t+pif3(:,ii)/3.*(abs(pm3(:,ii))).^pc )... \n\t\t\t./((abs(pm1(:,ii))).^pc+(abs(pm2(:,ii))).^pc+(abs(pm3(:,ii))).^pc);\n\tend;\nend;\nif nc == 1\n\tpif2=pif1;\nend;\n\n\t\t \n%pif2=zwvlt2ifq(pm,fs/dn)*2*pi;\npif2=pif2*2*pi;\ndn=dn*3;\n\n[slp,~]=zifq2gpm2(pif2,f0floor,nvo);\n[nn,mm]=size(pif2);\ndpif=(pif2(:,2:mm)-pif2(:,1:mm-1))*fs/dn;\ndpif(:,mm)=dpif(:,mm-1);\n[dslp,~]=zifq2gpm2(dpif,f0floor,nvo);\n\ndamp=(abs(pm1(:,2:mm))-abs(pm1(:,1:mm-1)))*fs/dn;\ndamp(:,mm)=damp(:,mm-1);\ndamp=damp./abs(pm1);\n\n%[c1,c2]=znormwght(1000);\nfxx=f0floor*2.0.^((0:nn-1)/nvo)'*2*pi;\nmmp=0*dslp;\n[c1,c2b]=znrmlcf2(1);\nif imgi==1; hpg=waitbar(0,'P/N map calculation'); end; % 07/Dec./2002 by H.K.%10/Aug./2005\nfor ii=1:nn\n%\t[c1,c2]=znrmlcf2(fxx(ii)/2/pi); % This is OK, but the next Eq is much faster.\n\tc2=c2b*(fxx(ii)/2/pi)^2;\n\tcff=damp(ii,:)/fxx(ii)*2*pi*0;\n\tmmp(ii,:)=(dslp(ii,:)./(1+cff.^2)/sqrt(c2)).^2+(slp(ii,:)./sqrt(1+cff.^2)/sqrt(c1)).^2;\n if imgi==1; waitbar(ii/nn); end; %,hpg); % 07/Dec./2002 by H.K.%10/Aug./2005\nend;\nif imgi==1; close(hpg); end;%10/Aug./2005\n\nif smp~=0\n\tsmap=zsmoothmapB(mmp,fs/dn,f0floor,nvo,smp,minm,0.4);\nelse\n\tsmap=mmp;\nend;\n\nfixpp=zeros(round(nn/3),mm);\nfixvv=fixpp+100000000;\nfixdf=fixpp+100000000;\nfixav=fixpp+1000000000;\nnf=zeros(1,mm);\nif imgi==1; hpg=waitbar(0,'Fixed pints calculation'); end; % 07/Dec./2002 by H.K.%10/Aug./2005\nfor ii=1:mm\n\t[ff,vv,df,aa]=zfixpfreq3(fxx,pif2(:,ii),smap(:,ii),dpif(:,ii)/2/pi,pm1(:,ii));\n\tkk=length(ff);\n\tfixpp(1:kk,ii)=ff;\n\tfixvv(1:kk,ii)=vv;\n\tfixdf(1:kk,ii)=df;\n\tfixav(1:kk,ii)=aa;\n\tnf(ii)=kk;\n if imgi==1 && rem(ii,10)==0; waitbar(ii/mm); end;% 07/Dec./2002 by H.K.%10/Aug./2005\nend;\nif imgi==1; close(hpg); end; % 07/Dec./2002 by H.K.%10/Aug./2005\nfixpp(fixpp==0)=fixpp(fixpp==0)+1000000;\n\n%keyboard\n%[vvm,ivv]=min(fixvv);\n%\n%for ii=1:mm\n%\tff00(ii)=fixpp(ivv(ii),ii);\n%\tesgm(ii)=fixvv(ivv(ii),ii);\n%end;\nnp=max(nf);\nf0v=fixpp(1:np,round(1:shiftm/dn*fs/1000:mm))/2/pi;\nvrv=fixvv(1:np,round(1:shiftm/dn*fs/1000:mm));\ndfv=fixdf(1:np,round(1:shiftm/dn*fs/1000:mm));\naav=fixav(1:np,round(1:shiftm/dn*fs/1000:mm));\nnf=nf(round(1:shiftm/dn*fs/1000:mm));\n\nif imgi==1\n\tcnmap(fixpp,smap,fs,dn,nvo,f0floor,shiftm);\nend;\n%ff00=ff00(round(1:shiftm/dn*fs/1000:mm));\n%esgm=sqrt(esgm(round(1:shiftm/dn*fs/1000:mm)));\n%keyboard;\n\nreturn;\n%------------------------------------------------------------------\nfunction okid=cnmap(fixpp,smap,fs,dn,nvo,f0floor,shiftm)\n\n% \tThis function had a bug in map axis.\n%\t17/Dec./2000 bug fix by Hideki Kawahara.\n\ndt=dn/fs;\n[nn,mm]=size(smap);\naa=figure;\nset(aa,'PaperPosition',[0.3 0.25 8 10.9]);\nset(aa,'Position',[30 130 520 680]);\nsubplot(211);\nimagesc([0 (mm-1)*dt*1000],[1 nn],20*log10(smap(:,round(1:shiftm/dn*fs/1000:mm))));axis('xy')\nhold on;\ntx=((1:shiftm/dn*fs/1000:mm)-1)*dt*1000;\nplot(tx,(nvo*log(fixpp(:,round(1:shiftm/dn*fs/1000:mm))/f0floor/2/pi)/log(2)+0.5)','ko');\nplot(tx,(nvo*log(fixpp(:,round(1:shiftm/dn*fs/1000:mm))/f0floor/2/pi)/log(2)+0.5)','w.');\nhold off\nxlabel('time (ms)');\nylabel('channel #');\ncolormap(jet);\n\nokid=1;\nreturn;\n\n%------------------------------------------------------------------\n\n%%function pm=zmultanalytFineCSPm(x,fs,f0floor,nvc,nvo,mu,mlt);\n\n% Dual waveleta analysis using cardinal spline manipulation\n% pm=multanalytFineCSP(x,fs,f0floor,nvc,nvo);\n% Input parameters \n% \n% x : input signal (2kHz sampling rate is sufficient.)\n% fs : sampling frequency (Hz)\n% f0floor : lower bound for pitch search (60Hz suggested)\n% nvc : number of total voices for wavelet analysis\n% nvo : number of voices in an octave\n%\t\t\t\tmu\t\t: temporal stretch factor\n% Outpur parameters\n% pm : wavelet transform using iso-metric Gabor function\n%\n% If you have any questions, mailto:kawahara@hip.atr.co.jp\n%\n% Copyright (c) ATR Human Information Processing Research Labs. 1996\n% Invented and coded by Hideki Kawahara\n% 30/Oct./1996\n\n%t0=1/f0floor;\n%lmx=round(6*t0*fs*mu);\n%wl=2^ceil(log(lmx)/log(2));\n%x=x(:)';\n%nx=length(x);\n%tx=[x,zeros(1,wl)];\n%gent=((1:wl)-wl/2)/fs;\n\n%nvc=18;\n\n%wd=zeros(nvc,wl);\n%wd2=zeros(nvc,wl);\n%ym=zeros(nvc,nx);\n%pm=zeros(nvc,nx);\n%mpv=1;\n%mu=1.0;\n%for ii=1:nvc\n% t=gent*mpv;\n% t=t(abs(t)<3.5*mu*t0);\n% wbias=round((length(t)-1)/2);\n% wd1=exp(-pi*(t/t0/mu).^2);%.*exp(i*2*pi*t/t0); \n% wd2=max(0,1-abs(t/t0/mu));\n% wd2=wd2(wd2>0);\n% wwd=conv(wd2,wd1);\n% wwd=wwd(abs(wwd)>0.0001);\n% wbias=round((length(wwd)-1)/2);\n% wwd=wwd.*exp(i*2*pi*mlt*t(round((1:length(wwd))-wbias+length(t)/2))/t0);\n% pmtmp1=fftfilt(wwd,tx);\n% pm(ii,:)=pmtmp1(wbias+1:wbias+nx)*sqrt(mpv);\n% mpv=mpv*(2.0^(1/nvo));\n% keyboard;\n%end;\n%[nn,mm]=size(pm);\n%pm=pm(:,1:mlt:mm);\n\n%----------------------------------------------------------------\nfunction pif=zwvlt2ifq(pm,fs)\n%\tWavelet to instantaneous frequency map\n%\tfqv=wvlt2ifq(pm,fs)\n\n%\tCoded by Hideki Kawahara\n%\t02/March/1999\n\n[~,mm]=size(pm);\npm=pm./(abs(pm));\npif=abs(pm(:,:)-[pm(:,1),pm(:,1:mm-1)]);\npif=fs/pi*asin(pif/2);\npif(:,1)=pif(:,2);\n\n%----------------------------------------------------------------\n\nfunction [slp,pbl]=zifq2gpm2(pif,f0floor,nvo)\n%\tInstantaneous frequency 2 geometric parameters\n%\t[slp,pbl]=ifq2gpm(pif,f0floor,nvo)\n%\tslp\t\t: first order coefficient\n%\tpbl\t\t: second order coefficient\n\n%\tCoded by Hideki Kawahara\n%\t02/March/1999\n\n[nn,~]=size(pif);\nfx=f0floor*2.0.^((0:nn-1)/nvo)*2*pi;\n\nc=2.0^(1/nvo);\ng=[1/c/c 1/c 1;1 1 1;c*c c 1];\nh=inv(g);\n\n%slp=pif(1:nn-2,:)*h(1,1)+pif(2:nn-1,:)*h(1,2)+pif(3:nn,:)*h(1,3);\nslp=((pif(2:nn-1,:)-pif(1:nn-2,:))/(1-1/c) ...\n +(pif(3:nn,:)-pif(2:nn-1,:))/(c-1))/2;\nslp=[slp(1,:);slp;slp(nn-2,:)];\n\npbl=pif(1:nn-2,:)*h(2,1)+pif(2:nn-1,:)*h(2,2)+pif(3:nn,:)*h(2,3);\npbl=[pbl(1,:);pbl;pbl(nn-2,:)];\n\nfor ii=1:nn\n\tslp(ii,:)=slp(ii,:)/fx(ii);\n\tpbl(ii,:)=pbl(ii,:)/fx(ii);\nend;\n\n%------------------------------------------\n\n%function [c1,c2]=znormwght(n)\n\n%zz=0:1/n:3;\n%hh=[diff(zGcBs(zz,0)) 0]*n;\n%c1=sum((zz.*hh).^2)/n;\n%c2=sum((2*pi*zz.^2.*hh).^2)/n;\n\n%-------------------------------------------\n\nfunction p=zGcBs(x,k)\n\ntt=x+0.0000001;\np=tt.^k.*exp(-pi*tt.^2).*(sin(pi*tt+0.0001)./(pi*tt+0.0001)).^2;\n\n\n%--------------------------------------------\nfunction smap=zsmoothmapB(map,fs,f0floor,nvo,mu,mlim,pex)\n\n[nvc,mm]=size(map);\n%mu=0.4;\nt0=1/f0floor;\nlmx=round(6*t0*fs*mu);\nwl=2^ceil(log(lmx)/log(2));\ngent=((1:wl)-wl/2)/fs;\n\nsmap=map;\nmpv=1;\nzt=0*gent;\niiv=1:mm;\nfor ii=1:nvc\n\tt=gent*mpv; %t0*mu/mpv*1000\n\tt=t(abs(t)<3.5*mu*t0);\n\twbias=round((length(t)-1)/2);\n\twd1=exp(-pi*(t/(t0*(1-pex))/mu).^2);\n\twd2=exp(-pi*(t/(t0*(1+pex))/mu).^2);\n\twd1=wd1/sum(wd1);\n\twd2=wd2/sum(wd2);\n\ttm=fftfilt(wd1,[map(ii,:) zt]);\n\ttm=fftfilt(wd2,[1.0./tm(iiv+wbias) zt]);\n\tsmap(ii,:)=1.0./tm(iiv+wbias);\n\tif t0*mu/mpv*1000 > mlim\n\t\tmpv=mpv*(2.0^(1/nvo));\n\tend;\nend;\n\n%--------------------------------------------\n%function [ff,vv,df]=zfixpfreq2(fxx,pif2,mmp,dfv)\n%\n%nn=length(fxx);\n%iix=(1:nn)';\n%cd1=pif2-fxx;\n%cd2=[diff(cd1);cd1(nn)-cd1(nn-1)];\n%cdd1=[cd1(2:nn);cd1(nn)];\n%fp=(cd1.*cdd1<0).*(cd2<0);\n%ixx=iix(fp>0);\n%ff=pif2(ixx)+(pif2(ixx+1)-pif2(ixx)).*cd1(ixx)./(cd1(ixx)-cdd1(ixx));\n%vv=mmp(ixx);\n%vv=mmp(ixx)+(mmp(ixx+1)-mmp(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));\n%df=dfv(ixx)+(dfv(ixx+1)-dfv(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));\n\n%--------------------------------------------\nfunction [ff,vv,df,aa]=zfixpfreq3(fxx,pif2,mmp,dfv,pm)\n\naav=abs(pm);\nnn=length(fxx);\niix=(1:nn)';\ncd1=pif2-fxx;\ncd2=[diff(cd1);cd1(nn)-cd1(nn-1)];\ncdd1=[cd1(2:nn);cd1(nn)];\nfp=(cd1.*cdd1<0).*(cd2<0);\nixx=iix(fp>0);\nff=pif2(ixx)+(pif2(ixx+1)-pif2(ixx)).*cd1(ixx)./(cd1(ixx)-cdd1(ixx));\n%vv=mmp(ixx);\nvv=mmp(ixx)+(mmp(ixx+1)-mmp(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));\ndf=dfv(ixx)+(dfv(ixx+1)-dfv(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));\naa=aav(ixx)+(aav(ixx+1)-aav(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));\n\n%--------------------------------------------\nfunction [c1,c2]=znrmlcf2(f)\n\nn=100;\nx=0:1/n:3;\ng=zGcBs(x,0);\ndg=[diff(g) 0]*n;\ndgs=dg/2/pi/f;\nxx=2*pi*f*x;\nc1=sum((xx.*dgs).^2)/n*2;\nc2=sum((xx.^2.*dgs).^2)/n*2;\n\n%--------------------------------------------\nfunction x=cleaninglownoise(x,fs,f0floor)\n\nflm=50;\nflp=round(fs*flm/1000);\nnn=length(x);\nwlp=fir1(flp*2,f0floor/(fs/2));\nwlp(flp+1)=wlp(flp+1)-1;\nwlp=-wlp;\n\ntx=[x(:)' zeros(1,2*length(wlp))];\nttx=fftfilt(wlp,tx);\nx=ttx((1:nn)+flp);\n\nreturn;\n\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/src/fixpF0VexMltpBG4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3853469358084859}}
{"text": "function [g1, g2] = simwhiteXrbfinfwhiteKernGradient(simKern, rbfKern, t1, varargin)\n\n% SIMWHITEXRBFINFWHITEKERNGRADIENT Compute a cross gradient between a\n% SIM-WHITE kernel and an RBF-WHITE kernel (with integration limits between\n% minus infinity and infinity).\n% FORMAT\n% DESC computes cross gradient of parameters of a cross kernel between a\n% SIM-WHITE and an RBF-WHITE kernels for the multiple output kernel. \n% ARG simKern : the kernel structure associated with the SIM-WHITE kernel.\n% ARG rbfKern : the kernel structure associated with the RBF-WHITE kernel.\n% ARG t1 : inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the SIM-WHITE kernel, for\n% ordering see simwhiteKernExtractParam.\n% RETURN g2 : gradient of the parameters of the RBF-WHITE kernel, for\n% ordering see rbfwhiteKernExtractParam.\n%\n% FORMAT\n% DESC computes cross kernel terms between a SIM-WHITE kernel and an\n% RBF-WHITE kernel (with integration limits between minus infinity and\n% infinity) for the multiple output kernel. \n% ARG simKern : the kernel structure associated with the SIM-WHITE kernel.\n% ARG rbfKern : the kernel structure associated with the RBF-WHITE kernel.\n% ARG t1 : row inputs for which kernel is to be computed.\n% ARG t2 : column inputs for which kernel is to be computed.\n% ARG covGrad : gradient of the objective function with respect to\n% the elements of the cross kernel matrix.\n% RETURN g1 : gradient of the parameters of the SIM-WHITE kernel, for\n% ordering see simwhiteKernExtractParam.\n% RETURN g2 : gradient of the parameters of the RBF-WHITE kernel, for\n% ordering see rbfwhiteKernExtractParam.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, simwhiteKernParamInit,\n% rbfinfwhiteKernParamInit, simwhiteKernExtractParam, rbfinfwhiteKernExtractParam\n%\n% COPYRIGHT : David Luengo, 2009\n\n% KERN\n\n\nif nargin < 5\n t2 = t1;\nelse\n t2 = varargin{1};\nend\ncovGrad = varargin{end};\n\nif size(t1, 2) > 1 | size(t2, 2) > 1\n error('Input can only have one column');\nend\nif simKern.variance ~= rbfKern.variance\n error('Kernels cannot be cross combined if they have different variances.')\nend\n\ng1 = zeros(1, simKern.nParams);\ng2 = zeros(1, rbfKern.nParams);\n\nT1 = repmat(t1, 1, size(t2, 1));\nT2 = repmat(t2.', size(t1, 1), 1);\ndeltaT = T1 - T2;\n\n% Parameters required for further computations\nisStationary = simKern.isStationary;\nvariance = simKern.variance;\ndecay = simKern.decay;\nsensitivity = simKern.sensitivity;\ninvWidth = rbfKern.inverseWidth;\n\n% Setting normalised parameters for computation of K\nsimKern.variance = 1;\nrbfKern.variance = 1;\nsimKern.sensitivity = 1;\nK = simwhiteXrbfinfwhiteKernCompute(simKern, rbfKern, t1, t2);\n\n% Gradient w.r.t. the decay (simKern)\ng1(1) = variance * sensitivity * sum(sum( ...\n ((decay/invWidth-deltaT) .* K + 1/sqrt(2*pi*invWidth) ...\n * (exp(-(decay*T1+0.5*invWidth*(T2.^2))) * (~isStationary) ...\n - exp(-0.5*invWidth*(deltaT.^2)))) ...\n .* covGrad));\n% * exp(0.5*(decay^2)/invWidth-decay*deltaT) ...\n% .* (exp(-0.5*invWidth*((T2+decay/invWidth).^2)) * (~isStationary) ...\n% - exp(-0.5*invWidth*((deltaT-decay/invWidth).^2)))) ...\n\n% Gradient w.r.t. the inverse width (rbfKern)\ng2(1) = 0.5 * variance * sensitivity * sum(sum( ...\n ((-(decay/invWidth)^2) * K + 1/sqrt(2*pi*invWidth) ...\n * ((T2-decay/invWidth) .* exp(-(decay*T1+0.5*invWidth*(T2.^2))) * (~isStationary) ...\n + (deltaT+decay/invWidth) .* exp(-0.5*invWidth*(deltaT.^2)))) ...\n .* covGrad));\n% * exp(0.5*(decay^2)/invWidth - decay*deltaT) ...\n% .* ((T2-decay/invWidth) .* exp(-0.5*invWidth*((T2+decay/invWidth).^2)) * (~isStationary) ...\n% + (deltaT+decay/invWidth) .* exp(-0.5*invWidth*((deltaT-decay/invWidth).^2)))) ...\n\n% Gradient w.r.t. sigma_r^2\ng1(2) = sensitivity * sum(sum(K .* covGrad));\ng2(2) = 0; % Otherwise it is counted twice\n\n% Gradient w.r.t. sensitivity (only simKern)\ng1(3) = variance * sum(sum(K .* covGrad));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/simwhiteXrbfinfwhiteKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.38471543469059616}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndomain = [-1,1,-1,1,-1,1];\nbc = [1,1,1,1,1,1];\nnx = 10;\nny = nx;\nnz = nx;\nr1 = 1; r2 = 0; r3 = 0; x0 = pi/10^4; y0 = 0; z0 = 0;\nbm = 1; bp = 1; am = 1; ap = 1;\npde = ConstFun(am,ap,bm,bp,r1,r2,r3,x0,y0,z0);\nmesh = genMesh3D(domain, nx, ny, nz);\nmesh = enrichMesh3D(mesh,2); % Mesh detail level = 1 (for IFE).\nmesh = genIntfMesh3D(mesh,pde.intf);\nfem = genNedFEM3D(mesh,bc);\n\n%% 1. use vectorization to generate face and face2elem data structure\n\n% reoder the nodes such that the nodes of interface elements appear at the\n% end\n\nIntMeshNode = unique(reshape(mesh.t(mesh.tLoc<0,:),[],1));\nMeshNodeID = true(size(mesh.p,1),1);\nMeshNodeID(IntMeshNode) = false;\nNodeOrderNew = zeros(size(mesh.p,1),1);\nNodeOrderNew(MeshNodeID) = 1:sum(MeshNodeID);\nNodeOrderNew(~MeshNodeID) = sum(MeshNodeID)+1:size(mesh.p,1);\n\nmesh.t = NodeOrderNew(mesh.t);\nmesh.e = NodeOrderNew(mesh.e);\n[~,NodeOrderNewSortID] = sort(NodeOrderNew);\nmesh.p = mesh.p(NodeOrderNewSortID,:);\nmesh.pLoc = mesh.pLoc(NodeOrderNewSortID);\n\ntic\n\nNp = size(mesh.p,1);\nnode = [mesh.p;mesh.eIntP];\nallCutElem = mesh.t(mesh.tLoc<0,:);\nisCutElem = (mesh.tLoc<0);\nvSign = [mesh.pLoc;zeros(size(mesh.eIntP,1),1)];\nisInterfaceNode = false(size(node,1), 1);\nisInterfaceNode(allCutElem(:)) = true; % include the vertices of allCutElem \nnumCutElemV1 = sum(isInterfaceNode);\nisInterfaceNode(Np+1:end) = true; % and the cut points and the aux points\nallCutElemReoderTmp = zeros(size(node,1),1);\nnumCutElemV2 = sum(isInterfaceNode);\nallCutElemReoderTmp(isInterfaceNode) = 1:numCutElemV2;\nallCutElemReoder = allCutElemReoderTmp(allCutElem);\ninterfaceNode = node(isInterfaceNode,:);\nntI = -min(mesh.tLoc);\nintID = find(mesh.tLoc<0);\n\ntetElem = zeros(12*ntI,4);\ntetElemLoc = zeros(12*ntI,1);\nidx2cube = zeros(12*ntI,1);\ntetcount = 0;\n\nfor i = 1:ntI\n tID = intID(i);\n t_e = mesh.t_e(tID,:);\n pLocK = mesh.pLoc(mesh.t(tID,:));\n vert0 = mesh.p(mesh.t(tID,:),:);\n nodeid = [allCutElemReoder(i,:),numCutElemV1-mesh.eLoc(t_e(mesh.eLoc(t_e)<0))'];\n vert2 = vert0(pLocK>0,:); % plus domain\n vert1 = vert0(pLocK<0,:); % minus domain\n intpt0 = mesh.eIntP(-mesh.eLoc(t_e(mesh.eLoc(t_e)<0)),:);\n id1 = [find(pLocK<0)', 5:4+size(intpt0,1)];\n id2 = [find(pLocK>0)', 5:4+size(intpt0,1)];\n p1 = [vert1;intpt0]; DT = delaunayTriangulation(p1); t1 = DT.ConnectivityList;\n p2 = [vert2;intpt0]; DT = delaunayTriangulation(p2); t2 = DT.ConnectivityList;\n tetElem(tetcount+1:tetcount+size(t1,1),:) = nodeid(id1(t1));\n idx2cube(tetcount+1:tetcount+size(t1,1)) = tID;\n tetElemLoc(tetcount+1:tetcount+size(t1,1)) = 1; % inside subdomain\n tetcount = tetcount+size(t1,1);\n tetElem(tetcount+1:tetcount+size(t2,1),:) = nodeid(id2(t2));\n idx2cube(tetcount+1:tetcount+size(t2,1)) = tID;\n tetElemLoc(tetcount+1:tetcount+size(t2,1)) = 2; % outside subdomain\n tetcount = tetcount+size(t2,1);\nend\ntetElem(tetcount+1:end,:) = [];\ntetElemLoc(tetcount+1:end,:) = [];\nidx2cube(tetcount+1:end,:) = [];\n[tetElem, ortidx, volume] = fixorder3(interfaceNode, tetElem);\n% there are some tets which are coplane, need to get rid of them\nidPlane = (volume<=10^(-12));\ntetElem(idPlane,:) = [];\nvolume(idPlane,:) = [];\ntetElemLoc(idPlane,:) = [];\nidx2cube(idPlane,:) = [];\nlocalidx2globalidx = find(isInterfaceNode); % tetElem points to interfaceNode\ntetElem = localidx2globalidx(tetElem); \n% reorder tetElem such that the index of its nodes are local, i.e.,\n% starting from 1,2,...\n\n% there are some tets which are on the interface, but contained in the surrounding tets\n% need to get rid of them (but the following algorithm may not be robust)\ntetSign = vSign(tetElem);\nidSliver = (sum(abs(tetSign),2)==0);\ntetElem(idSliver,:) = [];\nvolume(idSliver,:) = [];\ntetElemLoc(idSliver,:) = [];\nidx2cube(idSliver,:) = [];\nPolyVolume = accumarray([idx2cube,tetElemLoc],volume);\nPolyVolume = PolyVolume(mesh.tLoc<0,:); \nh = (PolyVolume(:,1) + PolyVolume(:,2)).^(1/3);\n% the first component contains the volume of the polyhedron on the\n% subdomain 1, the first component contains the volume of the polyhedron\n% on the subdomain 2\n\ntoc\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Get triangular faces for interrior elements and interface\n\ntic\nlocalFace = [2 3 4; 1 4 3; 1 2 4; 1 3 2];\nNT = size(tetElem,1);\ntface = zeros(4*NT, 3);\ntface2elem = zeros(4*NT, 1);\niface = zeros(4*NT, 3);\niface2elem = zeros(4*NT, 1);\n% find the interior tet elements\nisIntTet = min(vSign(tetElem),[], 2) == -1; % can not be == -1 as there is sliver\nintTet = tetElem(isIntTet,:);\n% find the corresponding cube indices\nintIdx2cube = idx2cube(isIntTet); \n% find triangular interface\nT = auxstructure3(intTet);\nneighbor = T.neighbor; % if a face is on the boundary, then the neighbor element index is itself\nclear T;\ntmp = (1:size(intTet, 1))';\nct = 0;\nci = 0;\nfor i = 1:4\n face = intTet(:, localFace(i,:));\n % find the triangle faces of polyhedron\n % 1. face and its neighbor associated to different cubes, and\n % 2. face is not on the boundary of all cut elements (which are squares)\n isPolyTriFace = ((neighbor(:, i) == tmp) | (intIdx2cube ~= intIdx2cube(neighbor(:,i)))) &...\n (sum(abs(vSign(face)), 2) > 0);% & (sum(abs(vSign(face)), 2) > 0);\n c2 = ct + sum(isPolyTriFace);\n tface((ct+1):c2,:) = face(isPolyTriFace,:);\n tface2elem((ct+1):c2,:) = intIdx2cube(isPolyTriFace); % the indices of the polyhedron\n ct = c2;\n % note that only interior elements are treated\n \n % find the triangle faces on interface with normal points to exterior\n % 1. face is on the boundary and\n % 2. all vertices are on the interface\n isInterface = (sum(abs(vSign(face)), 2) == 0);\n \n % add to interface \n c4 = ci + sum(isInterface);\n iface((ci+1):c4,:) = face(isInterface,:); % the interface tri faces.\n iface2elem((ci+1):c4,:) = intIdx2cube(isInterface); % the indices of the polyhedron\n ci = c4;\nend\niface((ci+1):end,:) = [];\niface2elem((ci+1):end,:) = [];\nc2old = c2;\n% plot to check\n%trisurf(tface(1:c2,:),node(:,1),node(:,2),node(:,3))\n%trisurf(iface(1:ci,:),node(:,1),node(:,2),node(:,3))\n\n% Find the triangular faces for exterior elements \nextTet = tetElem(~isIntTet, :);\nextIdx2cube = idx2cube(~isIntTet);\n\nT = auxstructure3(extTet);\nneighbor = T.neighbor;\nclear T;\ntmp = (1:size(extTet,1))';\nfor i = 1:4\n face = extTet(:, localFace(i,:));\n % find the triangle faces of polyhedron\n % 1. face and its neighbor associated to different cubes, and\n % 2. face is not on the boundary of all cut elements (which are squares)\n isPolyTriFace = ((neighbor(:, i) == tmp) | (extIdx2cube ~= extIdx2cube(neighbor(:,i)))) &...\n (sum(abs(vSign(face)), 2) > 0);\n c2 = ct + sum(isPolyTriFace);\n tface((ct+1):c2,:) = face(isPolyTriFace,:);\n tface2elem((ct+1):c2,:) = extIdx2cube(isPolyTriFace); \n % index of exterior polyhedron is append to the end of elem\n ct = c2;\nend\ntoc\n\ntface((ct+1):end,:) = []; % remove empty meomory\ntface2elem((ct+1):end) = [];\nface2elemLoc = [ones(c2old,1);2*ones(c2-c2old,1)];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% generate edge structure of elements\n% reorder the DoFs: put the DoFs of the edges of non-interface elements (sans those of interface elements)\n% at the begining, then cancate the new edges including interface edges and\n% non-interface edges\n\nIntNodeID = [unique(reshape(mesh.t(mesh.tLoc<0,:),[],1));...\n (size(mesh.p,1)+1:size(mesh.p,1) + size(mesh.eIntP,1))'];\nAllNodeID = zeros(size(node,1),1);\nAllNodeID(IntNodeID) = 1:length(IntNodeID);\ntfaceNew = AllNodeID(tface);\n[face2EDoF,Newedge,face2EDoFSign] = dof3edge(tfaceNew);\n% IMPORTANT: the Newedge contains those inside elements (4 intersection points)\n% the edge orientation of dof3edge is from 1->2, 2->3, 3->1 of nodes of tfacenew\n% face2EDoFSign assigns a sign such that orientation is from small to large \nNewedge = IntNodeID(Newedge); % transfer the node index of edges to the global ones\n% the new index of non-interface edges of interface elements (starting from 1)\nNewedgeNintID = find(abs(sum(vSign(Newedge),2))==2);\n\nOldedgeID = unique(reshape(mesh.t_e(mesh.tLoc<0,:),[],1));\nOldedge = mesh.e(OldedgeID,:);\nOldEtmp = abs(sum(vSign(Oldedge),2))==2;\nOldedgeNintID = OldedgeID(OldEtmp); \n% the old index of non-interface edges of interface elements\nOldedgeNint = Oldedge(OldEtmp,:);\n[OldedgeNintSort,OldedgeNintSortID] = sortrows(OldedgeNint);\n% ~ should be exactly the same as Newedge(NewedgeNintID)\n% therefore OldedgeNintSortID should be the new index of all the\n% non-interface edges of interface elements\nBasicEdge = ones(size(mesh.e,1),1); BasicEdge(OldedgeID) = false;\nBasicEdge = logical(BasicEdge);\n% basically the non-interface edges sans edges of interface elements\nBasicEdgeNum = sum(BasicEdge);\nTotalOldEdge = zeros(size(mesh.e,1),1);\nTotalOldEdge(BasicEdge) = 1:BasicEdgeNum;\nTotalOldEdge(OldedgeNintID(OldedgeNintSortID)) = BasicEdgeNum + NewedgeNintID; \n% map OldedgeNintSortID to global ones and put them at the location of\n% the original non-interface edges\n% NOTE: at the location of interface edges, TotalOldEdge still contains zero\n\n% generate new global edge DoF structure\nNumEdge = size(mesh.e,1) - size(Oldedge,1) + size(Newedge,1);\n% NumEdge should equal size(mesh.e,1) + sum(mesh.eLoc<0) + 2*sum(mesh.fLoc<0)\ngdof = zeros(NumEdge,2); \ngdof(1:BasicEdgeNum,:) = mesh.e(BasicEdge,:);\ngdof(BasicEdgeNum+1:end,:) = Newedge;\nNintElem = mesh.tLoc>0;\ng2ldofNint = TotalOldEdge(mesh.t_e(NintElem,:));\nface2EDoF = face2EDoF + BasicEdgeNum;\n% each row contains the DoFs of each element\n\n% generate orientation structure for each edge\nt_e_orit = zeros(size(g2ldofNint));\ne_ind = [1,2; 1,3; 1,4; 2,3; 2,4; 3,4];\nfor i = 1:6\n d = mesh.p(mesh.t(NintElem,e_ind(i,2)),:) - mesh.p(mesh.t(NintElem,e_ind(i,1)),:);\n %d_crect = mesh.p(mesh.e(mesh.t_e(NintElem,i),2),:) - mesh.p(mesh.e(mesh.t_e(NintElem,i),1),:);\n d_crect = node(gdof(g2ldofNint(:,i),2),:) - node(gdof(g2ldofNint(:,i),1),:);\n t_e_orit(:,i) = sign(sum(d.*d_crect,2));\nend\n\nmeshI.tface = tface;\nmeshI.tface2elem = tface2elem;\nmeshI.iface = iface;\nmeshI.iface2elem = iface2elem;\nmeshI.face2elemLoc = face2elemLoc;\nmeshI.PolyVolume = PolyVolume;\n% meshI.vSign = vSign;\nmeshI.node = node;\nmeshI.tetElem = tetElem;\nmeshI.tetElemLoc = tetElemLoc;\nmeshI.idx2cube = idx2cube;\nmeshI.tetVolume = volume;\nmeshI.face2EDoF = face2EDoF;\nmeshI.face2EDoFSign = face2EDoFSign;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% 2.use face, face2elem and face2EDoF data structure to compute ife functions\n\nface2elem = meshI.tface2elem;\ntface = meshI.tface;\nN = size(node, 1); NEdof = NumEdge;\nNF = size(tface,1); NC = size(mesh.t, 1);\n\nNP = max(face2elem);\nisCutPoly = false(NP, 1);\nisCutPoly(face2elem) = true;\n% this is the same as:\n% isCutPoly = (mesh.tLoc<0);\n% isCutPoly = isCutPoly(1:max(face2elem));\ncutPolyIdx = zeros(NP, 1);\nisExtPoly = false(NP,1);\nisExtPoly(NC+1:NP) = true;\n\nNP = sum(isCutPoly); % this new NP is max(-mesh.tLoc(mesh.tLoc<0));\ncutPolyIdx(isCutPoly) = 1:NP;\n% this is the same as:\n% cutPolyIdx = zeros(size(mesh.tLoc,1), 1);\n% cutPolyIdx(mesh.tLoc<0) = -mesh.tLoc(mesh.tLoc<0);\n% cutPolyIdx = cutPolyIdxNew(1:max(face2elem));\nface2elem = cutPolyIdx(face2elem);\n% the old face2elem is the global index of interface elements\n% the new one is only the index of interface elements\nisExtPoly = isExtPoly(isCutPoly);\n%%%clear isCutPoly cutPolyIdx\n\n% prepare new data structure to compute projections\npoly2node = sparse(face2elem(:)*ones(1,3), tface(:), 1, NP,N);\npoly2node = (poly2node > 0);\nNV = poly2node*ones(N, 1);\n\npoly2edge = sparse(face2elem(:)*ones(1,3), face2EDoF(:), 1, NP,NEdof);\npoly2edge = (poly2edge > 0);\nNE = poly2edge*ones(NEdof, 1);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% generate local IFE basis functions which are not associated with any DoFs\n% IFEbasis(:,i,:,:) for minus subdomain (i=1) or plus domain (i=2)\niface = meshI.iface;\niface2elem = meshI.iface2elem;\n[iface2elemReduce, uniID] = unique(iface2elem);\n% length(uniID) should be NP\nifaceReduce = iface(uniID,:);\n[IntFnormal,IntFarea,unitNormal,unittgt1,unittgt2] = facenormaltgt(node,ifaceReduce);\n[Fnormal,Farea,FunitNormal,Funittgt1,Funittgt2] = facenormaltgt(node,tface);\n% IFEbasis contains the associated IFE function on each face\n% IFEbasisA is for curl term and IFEbasisB is for u term\nIFEbasisA = zeros(size(face2elem,1),3,3);\n% for two pieces of an ife function, only the normal vector is different\n% on the minus subdomain (1) ife = n; on the plus subdomain (2) ife = n*bm/bp\nIFEbasisA(:,1,:) = unitNormal(face2elem,:);\nIFEbasisA(:,2,:) = unittgt1(face2elem,:);\nIFEbasisA(:,3,:) = unittgt2(face2elem,:);\nIFEbasisB = IFEbasisA;\npiece1tmp = (face2elemLoc==1);\nIFEbasisA(~piece1tmp,2,:) = IFEbasisA(~piece1tmp,2,:)*am/ap;\nIFEbasisA(~piece1tmp,3,:) = IFEbasisA(~piece1tmp,3,:)*am/ap;\nIFEbasisB(~piece1tmp,1,:) = IFEbasisB(~piece1tmp,1,:)*bm/bp;\n% Xmf the centroid of a triangular face on the interface of each interface\n% element but assigned to each face\n% Xf the centroid of each triangular face\nXmf = (node(ifaceReduce(face2elem,1),:) + node(ifaceReduce(face2elem,2),:) +...\n node(ifaceReduce(face2elem,3),:))/3; % the Xm point on the approximate interface plane\nXf = (node(tface(:,1),:) + node(tface(:,2),:) +...\n node(tface(:,3),:))/3;\n\n%% generate boundary integral for computing projections\n% for the curl term, need to compute surface curl (rot) on each face\nBIFEA = zeros(length(face2elem),3);\nBIFEB = zeros(length(face2elem),3,3);\n% BIFEA contains (alpha*(grad vi).(xf -xm))for i=1,2,3 (vi is the test function)\nBIFEA(:,1) = sum(squeeze(IFEbasisA(:,1,:)).*(Xf - Xmf),2);\nBIFEA(:,2) = sum(squeeze(IFEbasisA(:,2,:)).*(Xf - Xmf),2);\nBIFEA(:,3) = sum(squeeze(IFEbasisA(:,3,:)).*(Xf - Xmf),2);\n% no need multiply area for this case as computing curl generates |F|^(-1)\nBIFEA(piece1tmp,:) = am*BIFEA(piece1tmp,:);\nBIFEA(~piece1tmp,:) = ap*BIFEA(~piece1tmp,:);\n% BIFEB contains wh=(beta*(curl vi)times(xf -xm))times n for i=1,2,3\n% position to match the structure of mytimes\nBIFEB(:,:,1) = -cross(cross(squeeze(IFEbasisB(:,1,:)),(Xf - Xmf)),FunitNormal)/2;\nBIFEB(:,:,2) = -cross(cross(squeeze(IFEbasisB(:,2,:)),(Xf - Xmf)),FunitNormal)/2;\nBIFEB(:,:,3) = -cross(cross(squeeze(IFEbasisB(:,3,:)),(Xf - Xmf)),FunitNormal)/2;\n% devided by 2 is because curl(c times x) = 2c\nBIFEB(piece1tmp,:) = bm*BIFEB(piece1tmp,:);\nBIFEB(~piece1tmp,:) = bp*BIFEB(~piece1tmp,:);\n% project the 3D vector onto each face\nFNT = zeros(length(face2elem),3,3);\nFNT(:,1,:) = Funittgt1;\nFNT(:,2,:) = Funittgt2;\nFNT(:,3,:) = FunitNormal;\nBIFEB = mytimes(FNT,BIFEB); \nBIFEB = BIFEB(:,1:2,:);\n%%%%%%%%%%%%%%%%\n% mutiply the inverse the matrix on the left hand side of each interface\n% element for computing projection\n% this is a blocal diagonal matrix\n% for BIFEA (curl):\nVdiagTmp1 = (am*PolyVolume(:,1) + ap*PolyVolume(:,2)).^(-1);\nVdiagTmp2 = (am*PolyVolume(:,1) + am^2/ap*PolyVolume(:,2)).^(-1);\nVdiagTmp3 = (am*PolyVolume(:,1) + am^2/ap*PolyVolume(:,2)).^(-1);\nVdiag1 = VdiagTmp1(face2elem);\nVdiag2 = VdiagTmp2(face2elem);\nVdiag3 = VdiagTmp3(face2elem);\nMdiag = zeros(size(Vdiag1,1),3,3);\nMdiag(:,1,1) = Vdiag1; Mdiag(:,2,2) = Vdiag2; Mdiag(:,3,3) = Vdiag3;\nBIFEA = mytimes(Mdiag,BIFEA);\n%%%%%%%%%%%%%%%%\n% for BIFEB (u):\nVdiagTmp1 = (bm*PolyVolume(:,1) + bm^2/bp*PolyVolume(:,2)).^(-1);\nVdiagTmp2 = (bm*PolyVolume(:,1) + bp*PolyVolume(:,2)).^(-1);\nVdiagTmp3 = (bm*PolyVolume(:,1) + bp*PolyVolume(:,2)).^(-1);\nVdiag1 = VdiagTmp1(face2elem);\nVdiag2 = VdiagTmp2(face2elem);\nVdiag3 = VdiagTmp3(face2elem);\nMdiag = zeros(size(Vdiag1,1),3,3);\nMdiag(:,1,1) = Vdiag1; Mdiag(:,2,2) = Vdiag2; Mdiag(:,3,3) = Vdiag3;\n%%%%%%%%%%%%%%%%\n% compute [-(ym-y1),(xm-x1)]\nVecXm2Pt = (Xf - node(tface(:,1),:))/2;\nVecXm2Pt = mytimes(FNT,VecXm2Pt);\nVecXm2Pt = VecXm2Pt(:,[2,1]); VecXm2Pt(:,1) = -VecXm2Pt(:,1);\n% compute [-(ym-y1),(xm-x1)].wh\nBIFEB1 = zeros(size(VecXm2Pt));\nfor i = 1:3\n BIFEB1(:,i) = sum(VecXm2Pt.*squeeze(BIFEB(:,:,i)),2);\nend\nBIFEB1 = mytimes(Mdiag,BIFEB1);\n% compute inv([t1;t2]) where t1 and t2 are for the 1st and 3rd edges\nMatT = zeros(length(face2elem),3,2);\nMatT(:,:,1) = node(tface(:,2),:) - node(tface(:,1),:);\nMatT(:,:,2) = node(tface(:,1),:) - node(tface(:,3),:);\nMatT = mytimes(FNT,MatT); \nMatT = MatT(:,1:2,:); MatTInv = zeros(size(MatT));\nMatTInv(:,1,1) = MatT(:,2,2)./(-2*Farea); % generate inverse matrix\nMatTInv(:,2,2) = MatT(:,1,1)./(-2*Farea); \nMatTInv(:,1,2) = -MatT(:,1,2)./(-2*Farea); \nMatTInv(:,2,1) = -MatT(:,2,1)./(-2*Farea); \nclear MatT\nBIFEB2 = mytimes(MatTInv,BIFEB,[2,2]); % T^(-1)w_h \nBIFEB2 = mytimes(Mdiag,permute(BIFEB2,[1,3,2]));\nBIFEB2 = permute(BIFEB2,[1,3,2]);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% compute projections to IFE spaces and form the matrices\nface2EDoF = meshI.face2EDoF;\nface2EDoFSign = meshI.face2EDoFSign;\nIFNT = zeros(length(ifaceReduce),3,3);\nIFNT(:,:,1) = unitNormal;\nIFNT(:,:,2) = unittgt1;\nIFNT(:,:,3) = unittgt2;\n\nnnz = sum(NE.^2);\niiP = zeros(nnz, 1);\njjP = zeros(nnz, 1);\nssKC = zeros(nnz, 1);\nssMU = zeros(nnz, 1);\nindexP = 0;\niiF = zeros(nnz, 1);\njjF = zeros(nnz, 1);\nssSC = zeros(nnz, 1);\nssSU = zeros(nnz, 1);\nindexF = 0;\nune = unique(NE);\nhF = h(face2elem);\nb = zeros(NEdof, 1);\n\nfor kk = 1:length(une) % group polys according to their # of nodes\n \n tic\n %% generate IFE functions including the IFE basis functions on each interface\n %% elements which are not associated with any DoFs, and projections of gradients\n %% and the IFE functions with matching face average\n ne = une(kk);\n % some data related to element\n isCurrentFace = (NE(face2elem) == ne);\n CurrentFace = tface(isCurrentFace,:);\n CurrentFaceE = face2EDoF(isCurrentFace,:);\n CurrentFaceS = face2EDoFSign(isCurrentFace,:);\n CNF = size(CurrentFaceE,1);\n Currentfaceloc = face2elemLoc(isCurrentFace);\n Currentface2elem = face2elem(isCurrentFace);\n CurrentFnormal = FunitNormal(isCurrentFace,:);\n FareaCurrent = Farea(isCurrentFace);\n % some data related to face\n isCurrentElem = false(NP, 1);\n isCurrentElem(face2elem(isCurrentFace)) = true;\n CurrentPolyVolume = PolyVolume(isCurrentElem,:);\n IFNTCurrent = IFNT(isCurrentElem,:,:);\n % Current elem to node matrix\n currentPoly2edge = poly2edge(isCurrentElem, :);\n CNP = size(currentPoly2edge, 1);\n currentPolyLocalIdx = zeros(NP, 1);\n currentPolyLocalIdx(isCurrentElem) = 1:CNP;\n \n % currentElem(i,:) contains the edge index of the (current) i-th element\n [I, ~] = find(currentPoly2edge');\n currentElem = reshape(I, ne, [])';\n % localIdx(i,j) contains the (current) i-th element having the\n % node(dof=1,2,3,4) on the j-th location (j is the global node index)\n localIdx = sparse(repmat((1:CNP)', 1, ne), currentElem, ones(CNP, 1)*(1:ne), CNP, NEdof);\n clear currentPoly2edge\n \n %% Deal with current triangle face cases\n %% (1) for projection of curl u\n subs1 = currentPolyLocalIdx(face2elem(isCurrentFace));\n subs2 = [ones(CNF, 1); 2*ones(CNF, 1); 3*ones(CNF, 1)];\n val = BIFEA(isCurrentFace,:);\n \n % compute the projection of gradients\n GPA1 = zeros(CNP,3,ne); \n % coefficient of n t1 and t2 for the subelement on the subdomain 1 \n for m = 1:3\n subs3 = full(localIdx((CurrentFaceE(:, m) - 1)*CNP + subs1));\n SignCurrentE = repmat(CurrentFaceS(:,m),3,1);\n % subs1: new order (range in 1:CNP) of the element index\n % subs2: three components in the vector\n % subs3: the local index (DoF) (w.r.t. element) of the m-th edge of this face\n GPA1 = GPA1 + accumarray([repmat(subs1,3,1), subs2, repmat(subs3, 3, 1)],...\n SignCurrentE.*val(:), [CNP, 3, ne]);\n end\n GPA2 = GPA1; GPA2(:,2,:) = am/ap*GPA2(:,2,:); GPA2(:,3,:) = am/ap*GPA2(:,3,:);\n GPA1 = mytimes(IFNTCurrent,GPA1);\n GPA2 = mytimes(IFNTCurrent,GPA2);\n % the updated GP contains three component values of the projection vector \n % generate IFE vectors on each face\n % clear currentPolyLocalIdx localIdx\n % clear subs1 subs2 subs3\n \n % generate the data for computing stabilization matrices\n CurrentFace2DoF = zeros(NP,ne);\n CurrentFace2DoF(isCurrentElem,:) = currentElem;\n CurrentFace2DoF = CurrentFace2DoF(Currentface2elem,:);\n % CurrentFace2DoF contains the DoFs of the element associated with each face\n \n % compute curl uh.n on each face (uh is an IFE function)\n GPA1tmp = zeros(NP,3,ne); GPA2tmp = zeros(NP,3,ne);\n GPA1tmp(isCurrentElem,:,:) = GPA1; GPA2tmp(isCurrentElem,:,:) = GPA2;\n GAface = zeros(CNF,3,ne);\n GAface(Currentfaceloc==1,:,:) = GPA1tmp(Currentface2elem(Currentfaceloc==1),:,:);\n GAface(Currentfaceloc==2,:,:) = GPA2tmp(Currentface2elem(Currentfaceloc==2),:,:);\n clear GPA1tmp GPA2tmp \n GAfaceP = zeros(size(GAface,1),ne);\n for n = 1:ne\n GAfaceP(:,n) = sum(squeeze(GAface(:,:,n)).*CurrentFnormal,2);\n end\n \n % compute rot_F uh on each face according to DoFs\n TrueCurlTmp = CurrentFaceS./FareaCurrent;\n TrueCurl = zeros(CNF,ne);\n for i = 1:ne\n for j = 1:3\n IDij = (CurrentFaceE(:,j) == CurrentFace2DoF(:,i));\n TrueCurl(IDij,i) = TrueCurlTmp(IDij,j);\n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% (2) for projection of u\n val = BIFEB1(isCurrentFace,:); \n GPB1 = zeros(CNP,3,ne);\n % coefficient of n t1 and t2 for the subelement on the subdomain 1\n for m = 1:3\n subs3 = full(localIdx((CurrentFaceE(:, m) - 1)*CNP + subs1));\n SignCurrentE = repmat(CurrentFaceS(:,m),3,1);\n % subs1: new order (range in 1:CNP) of the element index\n % subs2: three components in the vector\n % subs3: the local index (DoF) (w.r.t. element) of the m-th edge of this face\n GPB1 = GPB1 + accumarray([repmat(subs1,3,1), subs2, repmat(subs3, 3, 1)],...\n SignCurrentE.*val(:), [CNP, 3, ne]);\n end\n \n edgetmp = [1,3];\n for mm = 1:2\n val = squeeze(BIFEB2(isCurrentFace,mm,:));\n m = edgetmp(mm);\n subs3 = full(localIdx((CurrentFaceE(:, m) - 1)*CNP + subs1));\n SignCurrentE = repmat(CurrentFaceS(:,m),3,1);\n Areatmp = repmat(FareaCurrent,3,1);\n % subs1: new order (range in 1:CNP) of the element index\n % subs2: three components in the vector\n % subs3: the local index (DoF) (w.r.t. element) of the m-th edge of this face\n GPB1 = GPB1 + accumarray([repmat(subs1,3,1), subs2, repmat(subs3, 3, 1)],...\n SignCurrentE.*val(:).*Areatmp, [CNP, 3, ne]);\n end \n GPB2 = GPB1; GPB2(:,2,:) = am/ap*GPB2(:,2,:); GPB2(:,3,:) = am/ap*GPB2(:,3,:);\n GPB1 = mytimes(IFNTCurrent,GPB1);\n GPB2 = mytimes(IFNTCurrent,GPB2);\n % the updated GP contains three component values of the projection vector \n % generate IFE vectors on each face\n clear currentPolyLocalIdx localIdx\n clear subs1 subs2 subs3\n \n % compute uh^(\\tau) (projection onto each face)\n GPB1tmp = zeros(NP,3,ne); GPB2tmp = zeros(NP,3,ne);\n GPB1tmp(isCurrentElem,:,:) = GPB1; GPB2tmp(isCurrentElem,:,:) = GPB2;\n GBface = zeros(CNF,3,ne);\n GBface(Currentfaceloc==1,:,:) = GPB1tmp(Currentface2elem(Currentfaceloc==1),:,:);\n GBface(Currentfaceloc==2,:,:) = GPB2tmp(Currentface2elem(Currentfaceloc==2),:,:);\n clear GPA1tmp GPA2tmp \n GBfaceP = zeros(size(GBface));\n for n = 1:ne\n GBfaceP(:,:,n) = GBface(:,:,n) - sum(GBface(:,:,n).*CurrentFnormal,2).*CurrentFnormal;\n end\n clear GBface\n GBfaceP = mytimes(FNT(isCurrentFace,:,:),GBfaceP);\n GBfaceP = GBfaceP(:,1:2,:);\n \n % compute u^(tau)(xm) uh on each face according to DoFs\n TrueUtTmp = zeros(CNF,2,ne);\n TrueUt = zeros(CNF,2,ne);\n MatTInvCurrent = MatTInv(isCurrentFace,:,:);\n for i = 1:ne\n TrueUt(:,:,i) = TrueUt(:,:,i) + TrueCurl(:,i).*VecXm2Pt(isCurrentFace,:);\n for j = 1:2\n jj = edgetmp(j);\n IDij = (CurrentFaceE(:,jj) == CurrentFace2DoF(:,i));\n TrueUtTmp(IDij,:,i) = MatTInvCurrent(IDij,j,:).*CurrentFaceS(IDij,jj);\n end\n end\n TrueUt = TrueUt + TrueUtTmp;\n clear TrueUtTmp\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% generate stiffness and mass matrices\n for n = 1:ne\n for m = 1:ne\n iiP(indexP+1:indexP + CNP) = currentElem(:, n);\n jjP(indexP+1:indexP + CNP) = currentElem(:, m);\n ssKC(indexP+1:indexP + CNP) = am*dot(GPA1(:,:,n), GPA1(:,:,m),2).*CurrentPolyVolume(:,1)+...\n ap*dot(GPA2(:,:,n), GPA2(:,:,m),2).*CurrentPolyVolume(:,2);\n ssMU(indexP+1:indexP + CNP) = bm*dot(GPB1(:,:,n), GPB1(:,:,m),2).*CurrentPolyVolume(:,1)+...\n bp*dot(GPB2(:,:,n), GPB2(:,:,m),2).*CurrentPolyVolume(:,2);\n indexP = indexP + CNP;\n \n iiF(indexF+1:indexF + CNF) = CurrentFace2DoF(:, n);\n jjF(indexF+1:indexF + CNF) = CurrentFace2DoF(:, m);\n ssSC(indexF+1:indexF + CNF) = dot((TrueCurl(:,m) - GAfaceP(:,m)),...\n (TrueCurl(:,n) - GAfaceP(:,n)),2).*...\n Farea(isCurrentFace).*hF(isCurrentFace);\n ssSU(indexF+1:indexF + CNF) = ( dot((TrueUt(:,1,m) - GBfaceP(:,1,m)),...\n (TrueUt(:,1,n) - GBfaceP(:,1,n)),2) + dot((TrueUt(:,2,m) - GBfaceP(:,2,m)),...\n (TrueUt(:,2,n) - GBfaceP(:,2,n)),2) ).*Farea(isCurrentFace).*hF(isCurrentFace);\n indexF = indexF + CNF;\n end\n end\n \n %% form the right-hand side vector\n idx2cubeNew = -mesh.tLoc(idx2cube);\n TetID = isCurrentElem(idx2cubeNew);\n currentvolume = volume(TetID);\n %%% DoFs of elements for tet\n currentTetDoF = zeros(size(isCurrentElem,1),ne);\n currentTetDoF(isCurrentElem,:) = currentElem;\n currentTetDoF = currentTetDoF(idx2cubeNew(TetID),:);\n %%% quadrature points\n X1 = node(tetElem(TetID,1),:); \n X2 = node(tetElem(TetID,2),:); \n X3 = node(tetElem(TetID,3),:);\n X4 = node(tetElem(TetID,4),:);\n ng = 1;\n [gx, gy, gz] = gaussPtetra(X1, X2, X3, X4, ng);\n gw = gaussWtetra(ng);\n Xm = (node(ifaceReduce(isCurrentElem,1),:) + node(ifaceReduce(isCurrentElem,2),:) +...\n node(ifaceReduce(isCurrentElem,3),:))/3;\n Xmtet = zeros(size(isCurrentElem,1),3);\n Xmtet(isCurrentElem,:) = Xm;\n Xmtet = Xmtet(idx2cubeNew(TetID),:);\n %%% projection of u\n Bas1 = zeros(size(isCurrentElem,1),3,ne); Bas2 = Bas1;\n Bas1(isCurrentElem,:,:) = GPB1; \n Bas2(isCurrentElem,:,:) = GPB2; \n Bas1 = Bas1(idx2cubeNew(TetID),:,:); Bas2 = Bas2(idx2cubeNew(TetID),:,:);\n Bas = zeros(sum(TetID),3,ne);\n piecetmp = tetElemLoc(TetID);\n Bas(piecetmp==1,:,:) = Bas1(piecetmp==1,:,:);\n Bas(piecetmp==2,:,:) = Bas2(piecetmp==2,:,:);\n \n \n ft1 = pde.f1(gx,gy,gz);\n ft2 = pde.f2(gx,gy,gz);\n ft3 = pde.f3(gx,gy,gz);\n Currentb = zeros(size(ft1));\n cnt = size(ft1,1);\n bii = ne*cnt;\n count = 0 ;\n for i = 1:ne\n Basi = squeeze(Bas(:,:,i));\n Currentb(:,i) = sum(gw*(ft1.*Basi(:,1)+ft2.*Basi(:,2)+ft3.*Basi(:,3)),2).*...\n currentvolume;\n bii(count+1:count+cnt) = currentTetDoF(:,i);\n count = count+cnt;\n end\n b = b + sparse(bii,1,reshape(Currentb,[],1),NEdof,1);\n \n toc \n \nend\n\nKcurl = sparse(iiP, jjP, ssKC, NEdof, NEdof);\nScurl = sparse(iiF, jjF, ssSC, NEdof, NEdof);\nMU = sparse(iiP, jjP, ssMU, NEdof, NEdof);\nSU = sparse(iiF, jjF, ssSU, NEdof, NEdof);\n\nMatI = Kcurl + Scurl + MU +SU;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% generate matrix on non-interface elements (for test)\nfeEvalBas1 = @EvalNed1Bas3D;\nfeEvalBas2 = @EvalNed1Bas3D;\n\ndof1 = 6; dof2 = 6; nloc = dof1*dof2; \nntID = find(mesh.tLoc > 0); ntN = length(ntID);\n\n%% 1. Matrix on noninterface elements\nMatInd = 1;\nAN = fem.area(ntID); \ngxN = fem.gx(ntID,:); gyN = fem.gy(ntID,:); gzN = fem.gz(ntID,:); gw = fem.gw;\nXN = zeros(nloc*ntN, 1);\n\ncoefN = feval(pde.A,gxN,gyN,gzN);\nIbasx = cell(dof1,1); Ibasy = cell(dof1,1); Ibasz = cell(dof1,1); \nJbasx = cell(dof2,1); Jbasy = cell(dof2,1); Jbasz = cell(dof2,1);\n\nfor i = 1:dof1\n Ibasx{i} = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, MatInd, 1).*t_e_orit(:,i);\n Ibasy{i} = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, MatInd, 2).*t_e_orit(:,i);\n Ibasz{i} = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, MatInd, 3).*t_e_orit(:,i);\nend\nfor j = 1:dof2\n Jbasx{j} = feEvalBas2(fem.bas, ntID, gxN, gyN, gzN, j, MatInd, 1).*t_e_orit(:,j);\n Jbasy{j} = feEvalBas2(fem.bas, ntID, gxN, gyN, gzN, j, MatInd, 2).*t_e_orit(:,j);\n Jbasz{j} = feEvalBas2(fem.bas, ntID, gxN, gyN, gzN, j, MatInd, 3).*t_e_orit(:,j);\nend\n\nIN = reshape(repmat(g2ldofNint(:,1:6),6,1),nloc*ntN,1);\nJN = repmat(reshape(g2ldofNint(:,1:6),dof2*ntN,1),6,1);\nind = 0;\nfor i = 1:dof1\n for j = 1:dof2\n XN(ind+1:ind+ntN) = AN.*(sum(((Ibasx{i}.*(coefN.*Jbasx{j})).*gw'),2) + ...\n sum(((Ibasy{i}.*(coefN.*Jbasy{j})).*gw'),2) + ...\n sum(((Ibasz{i}.*(coefN.*Jbasz{j})).*gw'),2));\n ind = ind + ntN;\n end\nend\nID = find(XN~=0); \nSN = sparse(IN(ID),JN(ID),XN(ID),NEdof,NEdof);\n\nStiffCurl = SN + Kcurl + Scurl;\n\n%%%%%%\n\nMatInd = 0;\nAN = fem.area(ntID); \ngxN = fem.gx(ntID,:); gyN = fem.gy(ntID,:); gzN = fem.gz(ntID,:); gw = fem.gw;\nXN = zeros(nloc*ntN, 1);\n\ncoefN = feval(pde.A,gxN,gyN,gzN);\nIbasx = cell(dof1,1); Ibasy = cell(dof1,1); Ibasz = cell(dof1,1); \nJbasx = cell(dof2,1); Jbasy = cell(dof2,1); Jbasz = cell(dof2,1);\n\nfor i = 1:dof1\n Ibasx{i} = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, MatInd, 1).*t_e_orit(:,i);\n Ibasy{i} = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, MatInd, 2).*t_e_orit(:,i);\n Ibasz{i} = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, MatInd, 3).*t_e_orit(:,i);\nend\nfor j = 1:dof2\n Jbasx{j} = feEvalBas2(fem.bas, ntID, gxN, gyN, gzN, j, MatInd, 1).*t_e_orit(:,j);\n Jbasy{j} = feEvalBas2(fem.bas, ntID, gxN, gyN, gzN, j, MatInd, 2).*t_e_orit(:,j);\n Jbasz{j} = feEvalBas2(fem.bas, ntID, gxN, gyN, gzN, j, MatInd, 3).*t_e_orit(:,j);\nend\n\nIN = reshape(repmat(g2ldofNint(:,1:6),6,1),nloc*ntN,1);\nJN = repmat(reshape(g2ldofNint(:,1:6),dof2*ntN,1),6,1);\nind = 0;\nfor i = 1:dof1\n for j = 1:dof2\n XN(ind+1:ind+ntN) = AN.*(sum(((Ibasx{i}.*(coefN.*Jbasx{j})).*gw'),2) + ...\n sum(((Ibasy{i}.*(coefN.*Jbasy{j})).*gw'),2) + ...\n sum(((Ibasz{i}.*(coefN.*Jbasz{j})).*gw'),2));\n ind = ind + ntN;\n end\nend\nID = find(XN~=0); \nMN = sparse(IN(ID),JN(ID),XN(ID),NEdof,NEdof);\n\nMassU = MN + MU + SU;\n\n%%%%%%%%%%\n\ndof = 6; nloc = dof;\nX = zeros(nloc*ntN, 1);\n\nfN1 = feval(pde.exactu1,gxN,gyN,gzN);\nfN2 = feval(pde.exactu2,gxN,gyN,gzN);\nfN3 = feval(pde.exactu3,gxN,gyN,gzN);\nind = 0;\nI = reshape(g2ldofNint(:,1:6),nloc*ntN,1);\nfor i = 1:dof\n ibas1 = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, 0, 1);\n ibas2 = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, 0, 2);\n ibas3 = feEvalBas1(fem.bas, ntID, gxN, gyN, gzN, i, 0, 3);\n X(ind+1:ind+ntN) = AN.*sum((ibas1.*fN1+ibas2.*fN2+ibas3.*fN3).*gw',2).*fem.t_e_orit(ntID,i);\n ind = ind + ntN;\nend\nrhsN = sparse(I,1,X,NEdof,1);\n\nrhs = rhsN + b;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[gew,gex,gey,gez] = gaussPedge(node(gdof(:,1),:),node(gdof(:,2),:),1);\n\n\ntu1 = sum(feval(pde.exactu1,gex,gey,gez).*gew,2);\ntu2 = sum(feval(pde.exactu2,gex,gey,gez).*gew,2);\ntu3 = sum(feval(pde.exactu3,gex,gey,gez).*gew,2);\n\ntgt = node(gdof(:,2),:) - node(gdof(:,1),:);\ntgt = tgt./sum(tgt.^2,2).^(1/2);\ntu = tu1.*tgt(:,1) + tu2.*tgt(:,2) + tu3.*tgt(:,3);\n\nAtotal = StiffCurl + MassU;\n%b = ones(size(MassU,1),1);\nx0 = zeros(size(b));\n\nbcind = fem.bcind;\n[bc,mapper] = boundaryEdge3D(node,gdof,bcind);\nbdidx = zeros(NEdof,1); \nisBdEdge = true(NEdof,1);\nisBdEdge(mapper) = false;\nbdidx(isBdEdge) = 1;\nTbd = spdiags(bdidx,0,NEdof,NEdof);\nT = spdiags(1-bdidx,0,NEdof,NEdof);\nA = T*Atotal*T + Tbd;\n\nub = tu;\nub(mapper) = 0;\nrhsB = Atotal*ub;\nf = rhs - rhsB;\nf(isBdEdge) = tu(isBdEdge);\n\noption.outsolver = 'cg';\nalpha = am*ones(size(gdof,1),1);\n% alpha(femI.eLoc>0) = ap;\n% alpha(femI.eLoc==0) = (am+ap)/2;\nbeta = bm*ones(size(gdof,1),1);\n% beta(femI.eLoc>0) = bp;\n% beta(femI.eLoc==0) = (bm+bp)/2;\noption.alpha = alpha;\noption.beta = beta;\noption.solver = 'amg';\nedge = gdof;\noption.isBdEdge = isBdEdge;\noption.smoother = 'BD';\nD = diag(A); D = D(1:BasicEdgeNum);\nM = sparse(1:BasicEdgeNum,1:BasicEdgeNum,D,NEdof,NEdof);\nM(BasicEdgeNum+1:end,BasicEdgeNum+1:end) = M(BasicEdgeNum+1:end,BasicEdgeNum+1:end) +...\n A(BasicEdgeNum+1:end,BasicEdgeNum+1:end);\noption.M = M;\n%option.M = A(BasicEdgeNum+1:end,BasicEdgeNum+1:end);\noption.blkId = BasicEdgeNum;\n[x,info] = amgMaxwell(A,f,node,edge,option);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% generate exact solution \n\n% [gew,gex,gey,gez] = gaussPedge(node(gdof(:,1),:),node(gdof(:,2),:),1);\n% \n% \n% tu1 = sum(feval(pde.exactu1,gex,gey,gez).*gew,2);\n% tu2 = sum(feval(pde.exactu2,gex,gey,gez).*gew,2);\n% tu3 = sum(feval(pde.exactu3,gex,gey,gez).*gew,2);\n% \n% tgt = node(gdof(:,2),:) - node(gdof(:,1),:);\n% tgt = tgt./sum(tgt.^2,2).^(1/2);\n% tu = tu1.*tgt(:,1) + tu2.*tgt(:,2) + tu3.*tgt(:,3);\n% \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %% test\n% DC = full(StiffCurl*tu);\n% DU = full(SU*tu);\n\n\n% for i = 1:CNP\n% vv = sum(tu(currentElem(1,:)).*(squeeze(GPA1(1,:,:))'),1);\n% if sum(abs(vv)) > 10^(-8)\n% stp\n% end\n% end", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/TestFunFiles/TestFace2elemHcurl2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3844277324436496}}
{"text": "% Usage: [xopt, fmin, retcode] = nlopt_minimize(algorithm, f, f_data, lb, ub,\n% xinit, stop)\n%\n% Minimizes a nonlinear multivariable function f(x, f_data{:}), where\n% x is a row vector, returning the optimal x found (xopt) along with\n% the minimum function value (fmin = f(xopt)) and a return code (retcode).\n% A variety of local and global optimization algorithms can be used,\n% as specified by the algorithm parameter described below. lb and ub\n% are row vectors giving the upper and lower bounds on x, xinit is\n% a row vector giving the initial guess for x, and stop is a struct\n% containing termination conditions (see below).\n%\n% This function is a front-end for the external routine nlopt_minimize\n% in the free NLopt nonlinear-optimization library, which is a wrapper\n% around a number of free/open-source optimization subroutines. More\n% details can be found on the NLopt web page (ab-initio.mit.edu/nlopt)\n% and also under 'man nlopt_minimize' on Unix.\n%\n% f should be a handle (@) to a function of the form:\n%\n% [val, gradient] = f(x, ...)\n%\n% where x is a row vector, val is the function value f(x), and gradient\n% is a row vector giving the gradient of the function with respect to x.\n% The gradient is only used for gradient-based optimization algorithms;\n% some of the algorithms (below) are derivative-free and only require\n% f to return val (its value). f can take additional arguments (...)\n% which are passed via the argument f_data: f_data is a cell array\n% of the additional arguments to pass to f. (Recall that cell arrays\n% are specified by curly brackets { ... }. For example, pass f_data={}\n% for functions that require no additional arguments.)\n%\n% stop describes the termination criteria, and is a struct with a\n% number of optional fields:\n% stop.ftol_rel = fractional tolerance on function value\n% stop.ftol_abs = absolute tolerance on function value\n% stop.xtol_rel = fractional tolerance on x\n% stop.xtol_abs = row vector of absolute tolerances on x components\n% stop.fmin_max = stop when f < fmin_max is found\n% stop.maxeval = maximum number of function evaluations\n% stop.maxtime = maximum run time in seconds\n% stop.verbose = > 0 indicates verbose output\n% Minimization stops when any one of these conditions is met; any\n% condition that is omitted from stop will be ignored. WARNING:\n% not all algorithms interpret the stopping criteria in exactly the\n% same way, and in any case ftol/xtol specify only a crude estimate\n% for the accuracy of the minimum function value/x.\n%\n% The algorithm should be one of the following constants (name and\n% interpretation are the same as for the C function). Names with\n% _G*_ are global optimization, and names with _L*_ are local\n% optimization. Names with _*N_ are derivative-free, while names\n% with _*D_ are gradient-based algorithms. Algorithms:\n%\n% NLOPT_GD_MLSL_LDS, NLOPT_GD_MLSL, NLOPT_GD_STOGO, NLOPT_GD_STOGO_RAND, \n% NLOPT_GN_CRS2_LM, NLOPT_GN_DIRECT_L, NLOPT_GN_DIRECT_L_NOSCAL, \n% NLOPT_GN_DIRECT_L_RAND, NLOPT_GN_DIRECT_L_RAND_NOSCAL, NLOPT_GN_DIRECT, \n% NLOPT_GN_DIRECT_NOSCAL, NLOPT_GN_ISRES, NLOPT_GN_MLSL_LDS, NLOPT_GN_MLSL, \n% NLOPT_GN_ORIG_DIRECT_L, NLOPT_GN_ORIG_DIRECT, NLOPT_LD_AUGLAG_EQ, \n% NLOPT_LD_AUGLAG, NLOPT_LD_LBFGS, NLOPT_LD_LBFGS_NOCEDAL, NLOPT_LD_MMA, \n% NLOPT_LD_TNEWTON, NLOPT_LD_TNEWTON_PRECOND, \n% NLOPT_LD_TNEWTON_PRECOND_RESTART, NLOPT_LD_TNEWTON_RESTART, \n% NLOPT_LD_VAR1, NLOPT_LD_VAR2, NLOPT_LN_AUGLAG_EQ, NLOPT_LN_AUGLAG, \n% NLOPT_LN_BOBYQA, NLOPT_LN_COBYLA, NLOPT_LN_NELDERMEAD, \n% NLOPT_LN_NEWUOA_BOUND, NLOPT_LN_NEWUOA, NLOPT_LN_PRAXIS, NLOPT_LN_SBPLX\n%\n% For more information on individual algorithms, see their individual\n% help pages (e.g. \"help NLOPT_LN_SBPLX\").\nfunction [xopt, fmin, retcode] = nlopt_minimize(algorithm, f, f_data, lb, ub, xinit, stop)\n \n [xopt, fmin, retcode] = nlopt_minimize_constrained(algorithm, f, f_data, {}, {}, lb, ub, xinit, stop);\n \n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/nlopt/distribution/nlopt_minimize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3844277250924534}}
{"text": "function [spectrum,ntaper,freqoi] = ft_specest_mtmfft(dat, time, varargin)\n\n% FT_SPECEST_MTMFFT computes a fast Fourier transform using multitapering with\n% multiple tapers from the DPSS sequence or using a variety of single tapers.\n%\n% Use as\n% [spectrum,ntaper,freqoi] = ft_specest_mtmfft(dat,time...)\n% where\n% dat = matrix of chan*sample\n% time = vector, containing time in seconds for each sample\n% spectrum = matrix of taper*chan*freqoi of fourier coefficients\n% ntaper = vector containing number of tapers per element of freqoi\n% freqoi = vector of frequencies in spectrum\n%\n% Optional arguments should be specified in key-value pairs and can include\n% taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss')\n% pad = number, total length of data after zero padding (in seconds)\n% padtype = string, indicating type of padding to be used (see ft_preproc_padding, default: zero)\n% freqoi = vector, containing frequencies of interest\n% tapsmofrq = the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box\n% dimord = 'tap_chan_freq' (default) or 'chan_time_freqtap' for memory efficiency (only when use variable number slepian tapers)\n% polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component)\n% taperopt = additional taper options to be used in the WINDOW function, see WINDOW\n% verbose = output progress to console (0 or 1, default 1)\n%\n% See also FT_FREQANALYSIS, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET\n\n% Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% these are for speeding up computation of tapers on subsequent calls\npersistent previous_argin previous_tap\n\n% get the optional input arguments\ntaper = ft_getopt(varargin, 'taper'); if isempty(taper), ft_error('You must specify a taper'); end\npad = ft_getopt(varargin, 'pad');\npadtype = ft_getopt(varargin, 'padtype', 'zero');\nfreqoi = ft_getopt(varargin, 'freqoi', 'all');\ntapsmofrq = ft_getopt(varargin, 'tapsmofrq');\ndimord = ft_getopt(varargin, 'dimord', 'tap_chan_freq');\nfbopt = ft_getopt(varargin, 'feedback');\nverbose = ft_getopt(varargin, 'verbose', true);\npolyorder = ft_getopt(varargin, 'polyorder', 0);\ntapopt = ft_getopt(varargin, 'taperopt');\n\nif isempty(fbopt)\n fbopt.i = 1;\n fbopt.n = 1;\nend\n\n% throw errors for required input\nif isempty(tapsmofrq) && (strcmp(taper, 'dpss') || strcmp(taper, 'sine'))\n ft_error('you need to specify tapsmofrq when using dpss or sine tapers')\nend\n\n% this does not work on integer data\ndat = cast(dat, 'double');\n\n% Set n's\n[nchan,ndatsample] = size(dat);\n\n% This does not work on integer data\nif ~isa(dat, 'double') && ~isa(dat, 'single')\n dat = cast(dat, 'double');\nend\n\n% Remove polynomial fit from the data -> default is demeaning\nif polyorder >= 0\n dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample);\nend\n\n% Determine fsample and set total time-length of data\nfsample = 1./mean(diff(time));\ndattime = ndatsample / fsample; % total time in seconds of input data\n\n% Zero padding\nif round(pad * fsample) < ndatsample\n ft_error('the padding that you specified is shorter than the data');\nend\nif isempty(pad) % if no padding is specified padding is equal to current data length\n pad = dattime;\nend\npostpad = ceil((pad - dattime) * fsample);\nendnsample = round(pad * fsample); % total number of samples of padded data\nendtime = pad; % total time in seconds of padded data\n\n% Set freqboi and freqoi\nfreqoiinput = freqoi;\nif isnumeric(freqoi) % if input is a vector\n freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; % is equivalent to: round(freqoi .* endtime) + 1;\n freqboi = unique(freqboi);\n freqoi = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output\nelseif strcmp(freqoi,'all') % if input was 'all'\n freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1;\n freqboi = freqboilim(1):1:freqboilim(2);\n freqoi = (freqboi-1) ./ endtime;\nend\nnfreqboi = length(freqboi);\nnfreqoi = length(freqoi);\nif (strcmp(taper, 'dpss') || strcmp(taper, 'sine')) && numel(tapsmofrq)~=1 && (numel(tapsmofrq)~=nfreqoi)\n ft_error('tapsmofrq needs to contain a smoothing parameter for every frequency when requesting variable number of slepian tapers')\nend\n\n% throw a warning if input freqoi is different from output freqoi\nif isnumeric(freqoiinput)\n % check whether padding is appropriate for the requested frequency resolution\n rayl = 1/endtime;\n if any(rem(freqoiinput,rayl)) % not always the case when they mismatch\n ft_warning('padding not sufficient for requested frequency resolution, for more information please see the FAQs on www.ru.nl/neuroimaging/fieldtrip');\n end\n if numel(freqoiinput) ~= numel(freqoi) % freqoi will not contain double frequency bins when requested\n ft_warning('output frequencies are different from input frequencies, multiples of the same bin were requested but not given');\n else\n if any(abs(freqoiinput-freqoi) >= eps*1e6)\n ft_warning('output frequencies are different from input frequencies');\n end\n end\nend\n\n% determine whether tapers need to be recomputed\ncurrent_argin = {time, postpad, taper, tapsmofrq, freqoi, tapopt, dimord}; % reasoning: if time and postpad are equal, it's the same length trial, if the rest is equal then the requested output is equal\nif isequal(current_argin, previous_argin)\n % don't recompute tapers\n tap = previous_tap;\n \nelse\n % recompute tapers\n switch taper\n \n case 'dpss'\n if numel(tapsmofrq)==1\n % create a sequence of DPSS tapers, ensure that the input arguments are double precision\n tap = double_dpss(ndatsample,ndatsample*(tapsmofrq./fsample))';\n % remove the last taper because the last slepian taper is always messy\n tap = tap(1:(end-1), :);\n \n % give error/warning about number of tapers\n if isempty(tap)\n ft_error('datalength to short for specified smoothing\\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',ndatsample/fsample,tapsmofrq,fsample/ndatsample);\n elseif size(tap,1) == 1\n ft_warning('using only one taper for specified smoothing');\n end\n elseif numel(tapsmofrq)>1\n tap = cell(1,nfreqoi);\n for ifreqoi = 1:nfreqoi\n % create a sequence of DPSS tapers, ensure that the input arguments are double precision\n currtap = double_dpss(ndatsample, ndatsample .* (tapsmofrq(ifreqoi) ./ fsample))';\n % remove the last taper because the last slepian taper is always messy\n currtap = currtap(1:(end-1), :);\n \n % give error/warning about number of tapers\n if isempty(currtap)\n ft_error('%.3f Hz: datalength to short for specified smoothing\\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',freqoi(ifreqoi), ndatsample/fsample,tapsmofrq(ifreqoi),fsample/ndatsample(ifreqoi));\n elseif size(currtap,1) == 1\n disp([num2str(freqoi(ifreqoi)) ' Hz: WARNING: using only one taper for specified smoothing'])\n end\n tap{ifreqoi} = currtap;\n end\n end\n \n case 'sine'\n if numel(tapsmofrq)==1\n % create a sequence of sine tapers, \n tap = sine_taper(ndatsample, ndatsample*(tapsmofrq./fsample))';\n % remove the last taper \n tap = tap(1:(end-1), :);\n \n % give error/warning about number of tapers\n if isempty(tap)\n ft_error('datalength to short for specified smoothing\\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',ndatsample/fsample,tapsmofrq,fsample/ndatsample);\n elseif size(tap,1) == 1\n ft_warning('using only one taper for specified smoothing');\n end\n elseif numel(tapsmofrq)>1\n tap = cell(1,nfreqoi);\n for ifreqoi = 1:nfreqoi\n % create a sequence of sine tapers\n currtap = sine_taper(ndatsample, ndatsample .* (tapsmofrq(ifreqoi) ./ fsample))';\n % remove the last taper because the last slepian taper is always messy\n currtap = currtap(1:(end-1), :);\n \n % give error/warning about number of tapers\n if isempty(currtap)\n ft_error('%.3f Hz: datalength to short for specified smoothing\\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',freqoi(ifreqoi), ndatsample/fsample,tapsmofrq(ifreqoi),fsample/ndatsample(ifreqoi));\n elseif size(currtap,1) == 1\n disp([num2str(freqoi(ifreqoi)) ' Hz: WARNING: using only one taper for specified smoothing'])\n end\n tap{ifreqoi} = currtap;\n end\n end \n \n case 'sine_old'\n % to provide compatibility with the tapers being scaled (which was default\n % behavior prior to 29apr2011) yet this gave different magnitude of power\n % when comparing with slepian multi tapers\n tap = sine_taper_scaled(ndatsample, ndatsample*(tapsmofrq./fsample))';\n tap = tap(1:(end-1), :); % remove the last taper\n \n case 'alpha'\n ft_error('not yet implemented');\n \n case 'hanning'\n tap = hanning(ndatsample)';\n tap = tap./norm(tap, 'fro');\n \n otherwise\n % create the taper and ensure that it is normalized\n if isempty(tapopt) % some windowing functions don't support nargin>1, and window.m doesn't check it\n tap = window(taper, ndatsample)';\n else\n tap = window(taper, ndatsample, tapopt)';\n end\n tap = tap ./ norm(tap,'fro');\n \n end % switch taper\nend % isequal currargin\n\n% set ntaper\nif ~((strcmp(taper,'dpss') || strcmp(taper,'sine')) && numel(tapsmofrq)>1) % variable number of slepian tapers not requested\n ntaper = repmat(size(tap,1),nfreqoi,1);\nelse % variable number of slepian tapers requested\n ntaper = cellfun(@size,tap,repmat({1},[1 nfreqoi]));\nend\n\n% determine phase-shift so that for all frequencies angle(t=0) = 0\ntimedelay = time(1);\nif timedelay ~= 0\n angletransform = complex(zeros(1,nfreqoi));\n for ifreqoi = 1:nfreqoi\n missedsamples = round(timedelay * fsample);\n % determine angle of freqoi if oscillation started at 0\n % the angle of wavelet(cos,sin) = 0 at the first point of a cycle, with sine being in upgoing flank, which is the same convention as in mtmconvol\n anglein = (missedsamples) .* ((2.*pi./fsample) .* freqoi(ifreqoi));\n coswav = cos(anglein);\n sinwav = sin(anglein);\n angletransform(ifreqoi) = atan2(sinwav, coswav);\n end\n angletransform = repmat(angletransform,[nchan,1]);\nend\n\n% compute fft\nif ~((strcmp(taper,'dpss') || strcmp(taper,'sine')) && numel(tapsmofrq)>1) % ariable number of slepian tapers not requested\n str = sprintf('nfft: %d samples, datalength: %d samples, %d tapers',endnsample,ndatsample,ntaper(1));\n [st, cws] = dbstack;\n if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis')\n % specest_mtmfft has been called by ft_freqanalysis, meaning that ft_progress has been initialised\n ft_progress(fbopt.i./fbopt.n, ['processing trial %d/%d ',str,'\\n'], fbopt.i, fbopt.n);\n elseif verbose\n fprintf([str, '\\n']);\n end\n spectrum = cell(ntaper(1),1);\n \n for itap = 1:ntaper(1)\n dum = fft(ft_preproc_padding(bsxfun(@times,dat,tap(itap,:)), padtype, 0, postpad),[], 2);\n dum = dum(:,freqboi);\n % phase-shift according to above angles\n if timedelay ~= 0\n dum = dum .* exp(-1i*angletransform);\n end\n dum = dum .* sqrt(2 ./ endnsample);\n spectrum{itap} = dum;\n end\n \n spectrum = reshape(vertcat(spectrum{:}),[nchan ntaper(1) nfreqboi]); % collecting in a cell-array and later reshaping provides significant speedups\n spectrum = permute(spectrum, [2 1 3]);\n \n \nelse % variable number of slepian tapers requested\n switch dimord\n \n case 'tap_chan_freq' % default\n % start fft'ing\n spectrum = complex(NaN([max(ntaper) nchan nfreqoi]));\n for ifreqoi = 1:nfreqoi\n str = sprintf('nfft: %d samples, datalength: %d samples, frequency %d (%.2f Hz), %d tapers',endnsample,ndatsample,ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi));\n [st, cws] = dbstack;\n if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose\n % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised\n ft_progress(fbopt.i./fbopt.n, ['processing trial %d, ',str,'\\n'], fbopt.i);\n elseif verbose\n fprintf([str, '\\n']);\n end\n for itap = 1:ntaper(ifreqoi)\n \n dum = fft(ft_preproc_padding(bsxfun(@times,dat,tap{ifreqoi}(itap,:)), padtype, 0, postpad), [], 2);\n \n dum = dum(:,freqboi(ifreqoi));\n % phase-shift according to above angles\n if timedelay ~= 0\n dum = dum .* exp(-1i*angletransform(:,ifreqoi));\n end\n dum = dum .* sqrt(2 ./ endnsample);\n spectrum(itap,:,ifreqoi) = dum;\n end\n end % for nfreqoi\n \n case 'chan_freqtap' % memory efficient representation\n % create tapfreqind\n freqtapind = cell(1,nfreqoi);\n tempntaper = [0; cumsum(ntaper(:))];\n for ifreqoi = 1:nfreqoi\n freqtapind{ifreqoi} = tempntaper(ifreqoi)+1:tempntaper(ifreqoi+1);\n end\n \n % start fft'ing\n spectrum = complex(zeros([nchan sum(ntaper)]));\n for ifreqoi = 1:nfreqoi\n str = sprintf('nfft: %d samples, datalength: %d samples, frequency %d (%.2f Hz), %d tapers',endnsample,ndatsample,ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi));\n [st, cws] = dbstack;\n if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose\n % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised\n ft_progress(fbopt.i./fbopt.n, ['processing trial %d, ',str,'\\n'], fbopt.i);\n elseif verbose\n fprintf([str, '\\n']);\n end\n for itap = 1:ntaper(ifreqoi)\n \n dum = fft(ft_preproc_padding(bsxfun(@times,dat,tap{ifreqoi}(itap,:)), padtype, 0, postpad), [], 2);\n \n dum = dum(:,freqboi(ifreqoi));\n % phase-shift according to above angles\n if timedelay ~= 0\n dum = dum .* exp(-1i*angletransform(:,ifreqoi));\n end\n dum = dum .* sqrt(2 ./ endnsample);\n spectrum(:,freqtapind{ifreqoi}(itap)) = dum;\n end\n end % for nfreqoi\n end % switch dimord\nend\n\n% remember the current input arguments, so that they can be\n% reused on a subsequent call in case the same input argument is given\nprevious_argin = current_argin;\nprevious_tap = tap;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION ensure that the first two input arguments are of double\n% precision this prevents an instability (bug) in the computation of the\n% tapers for MATLAB 6.5 and 7.0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [tap] = double_dpss(a, b, varargin)\ntap = dpss(double(a), double(b), varargin{:});\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/specest/ft_specest_mtmfft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3842660424578724}}
{"text": "function gr = lme_mass_RgGradient1(X,Zcols,SIGMA,W,invH,L,phi,re,ni,G,GDa,GDb)\n% gr = lme_mass_RgGradient1(X,Zcols,W,invH,L,phi,re,ni,G,GDa,GDb)\n% \n% Gradient vector of the restricted log-likelihood for a whole region. This\n% is less computationally efficient than lme_mass_RgGradient but more \n% numerically stable.\n%\n% Input\n% X: Ordered design Matrix (according to time for each subject).\n% Zcols: Vector with the indices of the colums of X that will be considered\n% as random effects.\n% W: Inverses of the estimated temporal covariance matrices for each \n% subject stacked in W.\n% invH: Asymptotic covariance matrix of the fixed effects.\n% L: Cholesky factor of the covariance matrix of the random effects (D).\n% phi: Within-subject standard deviation of the errors.\n% re: Residuals;\n% ni: Vector whose entries are the number of repeated measures for each\n% subject in the study (ordered according to X).\n% G: Spatial covariance matrix.\n% GDa: Derivative of the spatial covariance matrix for the first spatial \n% parameter.\n% GDb: Derivative of the spatial covariance matrix for the second spatial \n% parameter (empty for spatial models with a single parameter).\n%\n% Output\n% gr: Gradient vector.\n%\n% $Revision: 1.2 $ $Date: 2015/01/06 17:14:55 $\n% Original Author: Jorge Luis Bernal Rusiel \n% CVS Revision Info:\n% $Author: mreuter $\n% $Date: 2015/01/06 17:14:55 $\n% $Revision: 1.2 $\n%\nm = length(ni);\nq = length(Zcols);\nZ = X(:,Zcols);\nnth = q*(q+1)/2+1;\nnv = size(G,1);\n%Log-likelihoood derivative for L\ngr = zeros(nth+2,1);\njk = 0;\nfor k=1:q\n for j=1:k\n jk = jk + 1;\n posi = 1; posir = 1;\n a1 = 0; a2 = 0; M1 = 0;\n for i=1:m\n posf = posi+ni(i)-1;\n posfr = posir+ni(i)*nv-1;\n Zi = Z(posi:posf,:);\n Wi = W(posi:posf,1:ni(i));\n SIGMAi = SIGMA(posi:posf,1:ni(i));\n Xi = X(posi:posf,:);\n rei = re(posir:posfr);\n Mjki = Zi(:,k)*L(j,:)*Zi';\n Mjki = Mjki + Mjki';\n Maux = Mjki*Wi;\n a1 = a1 - trace(Maux);\n a2 = a2 + (rei'/kron(G,SIGMAi))*(kron(eye(nv),Mjki*Wi)*rei);\n M1 = M1 + Xi'*Wi*Maux*Xi;\n posi = posf+1;\n posir = posfr+1;\n end;\n a3 = -trace(invH*M1);\n gr(jk) = (nv*a1+a2-nv*a3)/2;\n end;\nend;\n%Log-likelihoood derivative for phi\nposi = 1; posir = 1;\na1 = 0; a2 =0; M1 = 0;\nfor i=1:m\n posf = posi+ni(i)-1;\n posfr = posir+ni(i)*nv-1;\n Wi = W(posi:posf,1:ni(i));\n SIGMAi = SIGMA(posi:posf,1:ni(i));\n Xi = X(posi:posf,:);\n rei = re(posir:posfr);\n a1 = a1 - trace(Wi);\n Maux = Wi*Wi;\n a2 = a2 + (rei'/kron(G,SIGMAi))*(kron(eye(nv),Wi)*rei);\n M1 = M1 + Xi'*Maux*Xi;\n posi = posf+1;\n posir = posfr+1;\nend;\na3 = -trace(invH*M1);\ngr(nth) = phi*(nv*a1+a2-nv*a3);\n%Log-likelihoood derivative for a\nposi = 1; posir = 1;\na2 =0; \nfor i=1:m\n posf = posi+ni(i)-1;\n posfr = posir+ni(i)*nv-1;\n SIGMAi = SIGMA(posi:posf,1:ni(i));\n rei = re(posir:posfr);\n a2 = a2 + (rei'/kron(G,eye(ni(i))))*(kron(GDa,eye(ni(i))))*(kron(G,SIGMAi)\\rei);\n posi = posf+1;\n posir = posfr+1;\nend;\naux = -trace(G\\GDa);\na1 = sum(ni)*aux;\na3 = size(X,2)*aux;\ngr(nth+1) = (a1+a2-a3)/2;\nif ~isempty(GDb)\n %Log-likelihoood derivative for b\n posi = 1; posir = 1;\n a2 =0;\n for i=1:m\n posf = posi+ni(i)-1;\n posfr = posir+ni(i)*nv-1;\n SIGMAi = SIGMA(posi:posf,1:ni(i));\n rei = re(posir:posfr);\n a2 = a2 + (rei'/kron(G,eye(ni(i))))*(kron(GDb,eye(ni(i))))*(kron(G,SIGMAi)\\rei);\n posi = posf+1;\n posir = posfr+1;\n end;\n aux = -trace(G\\GDb);\n a1 = sum(ni)*aux;\n a3 = size(X,2)*aux;\n gr(nth+2) = (a1+a2-a3)/2;\nelse\n gr = gr(1:nth+1);\nend;\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/freesurfer/lme/mass_univariate/lme_mass_RgGradient1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3842660372949212}}
{"text": "function [gmu, gsigmavar, factors] = gpPosteriorGradMeanCovar(model, X);\n\n% GPPOSTERIORGRADMEANCOVAR Gadient of the mean and variances of the posterior at points given by X.\n% FORMAT\n% DESC computes the gradient of the mean and covariances of the\n% posterior distribution of a Gaussian process with respect to the\n% input locations. \n% ARG model : the model for which gradients are to be computed.\n% ARG X : the input locations where gradients are to be computed.\n% RETURN gmu : the gradient of the posterior mean with respect to\n% the input locations.\n% RETURN gCovar : the gradients of the posterior covariance with\n% respect to the input locations. By raw, we mean that the gradient\n% has not yet been multiplied by any output scale in that direction\n% (as is done for gpPosteriorGradMeanCovar). The gradients are\n% stored in a cell array of dimension MODEL.q x MODEL.d. \n%\n% DESC computes the gradient of the mean and covariances of the\n% posterior distribution of a Gaussian process with respect to the\n% input locations. Returns a compact representation for the\n% covariances which separates the factors associated with the\n% different dimensions from the covariance gradients.\n% ARG model : the model for which gradients are to be computed.\n% ARG X : the input locations where gradients are to be computed.\n% RETURN gmu : the gradient of the posterior mean with respect to\n% the input locations.\n% RETURN grCovar : the 'raw' gradient of the posterior covariance with\n% respect to the input locations. By raw, we mean that the gradient\n% has not yet been multiplied by any output scale in that direction\n% (as is done for gpPosteriorGradMeanCovar). The gradients are\n% stored in a cell array of length MODEL.q. \n% RETURN factors : the factors for multiplying the 'raw' gradients\n% of the covariances by. \n%\n% SEEALSO : gpCreate, gpPosteriorMeanVar\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006, 2009\n\n% GP\n\n\nif ~isfield(model, 'alpha')\n model = gpComputeAlpha(model);\nend\n\nswitch model.approx\n case 'ftc'\n gX = kernGradX(model.kern, X, model.X);\n kX_star = kernCompute(model.kern, X, model.X)';\n case {'dtc', 'dtcvar', 'fitc', 'pitc'}\n gX = kernGradX(model.kern, X, model.X_u);\n kX_star = kernCompute(model.kern, X, model.X_u)';\n otherwise\n error('Unrecognised approximation type');\n \nend\nK = kernGradX(model.kern, X);\n\n\nif ~model.isMissingData\n for i = 1:model.q\n switch model.approx\n case 'ftc'\n KinvgK = model.invK_uu*squeeze(gX(:, i, :));\n case {'dtc', 'dtcvar', 'fitc', 'pitc'}\n KinvgK = (model.invK_uu - (1/model.beta)*model.Ainv)*squeeze(gX(:, i, :));\n otherwise\n error('Unrecognised approximation type');\n end\n kXTKinvgK = kX_star'*KinvgK;\n gCovar{i} = squeeze(K(:, i, :))-kXTKinvgK - diag(diag(kXTKinvgK));\n gmu{i} = squeeze(gX(:, i, :))'*model.alpha.*repmat(model.scale, ...\n size(X, 1), 1);\n end\n \n \n % Deal with scaling.\n if nargout < 3\n for i = 1:model.q\n for j = 1:model.d\n gsigmavar{i, j} = gCovar{i}*model.scale(j)*model.scale(j);\n end\n end\n else\n factors = model.scale.*model.scale;\n gsigmavar = gCovar;\n end\nelse\n error('Not yet implemented for models trained on missing data.');\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/gp/gpPosteriorGradMeanCovar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.38425309893106296}}
{"text": " function fit = de_ftab_fit_exp3(xrs, mac, varargin)\n%|function fit = de_ftab_fit_exp3(xrs, mac, [options])\n%|\n%| Fit to DE table fm(), suitable for subsequent interpolation / extrapolation.\n%| Uses a special experimental exponential model:\n% todo -log(sum_k p_k exp(-m_k . s))\n% fit a 3-term exponential model that has the proper derivatives\n% at 0, and at +/- infinity\n%|\n%| in\n%|\txrs\tstrum\t\tX-ray spectra; see xray_read_spectra.m\n%|\tmac\t[Ne,L]\t\tmass attenuation coefficients\n%|\n%| option\n%|\t'show'\t1|0\t\tplot?\n%|\n%| out\n%|\tfit\tstrum\t\tstrum object for fitted f_m(s_1,...,s_L)\n%|\n%|\tmethods:\n%|\t.fmfun(sll)\t\tfm function evaluation, for stacked array sll\n%|\t.fgrad(sll)\t\tfm gradient evaluation, for stacked array sll\n%|\t.show_sp(en, sp)\tplot true spectrum vs fitted spectrum\n%|\t.show_fm(sl, fm)\tmesh plot of fm and its fit\n%|\t.show_err(sl, fm)\tmesh plot of fit error\n%|\t.mac_eff\t\teffective mass atten coef based on fit\n%|\t\t\t\t(valid for 'exp' only)\n%|\n%| Copyright 2008-8-10, Jeff Fessler, University of Michigan\n\n%if nargin == 1 && streq(xrs, 'test'), de_ftab_fit_exp3_test, return, end\nif nargin < 2, ir_usage, end\n\narg.show = false;\narg = vararg_pair(arg, varargin);\n\nLL = ncol(mac);\nif LL ~= 1, fail 'only 1 component done', end\n\nMM = ncol(xrs.Ide);\n\nfit.MM = MM;\nfit.type = 'exp3';\n\nmassbar = (xrs.Ide' * mac) ./ sum(xrs.Ide)'; % [M,1]\n\n%if ~isempty(wt), warn 'weighting ignored', end\n% if isempty(wt), wt = num2cell(ones(MM,1)); end\n\nfit.kev = cell(1,MM);\nfit.mac = cell(1,MM);\nfit.coef = cell(1,MM);\nfor mm=1:MM\n\tgood = xrs.sp(:,mm) > 0;\n\tsp_m = xrs.sp(good,mm); % nonzero spectrum\n\tsp_m = sp_m / sum(sp_m);\n\t[mac_m ii] = sort(mac(good));\n\tif any(mac_m(2:end)) == mac_m(1), error 'non unique min', end\n\tif any(mac_m(1:end-1)) == mac_m(end), error 'non unique max', end\n\tkev_m = xrs.en(good);\n\tkev_m = kev_m(ii);\n\tq1 = sp_m(1);\n\tqN = sp_m(end);\n\tb1 = mac_m(1);\n\tbN = mac_m(end);\n\tmac_mid = (massbar(mm) - q1 * b1 - qN * bN) / (1 - q1 - qN);\n\tfit.mac{mm} = [b1 mac_mid bN]';\n\tfit.coef{mm} = [q1 1-q1-qN qN]';\n\n\tkev_mid = interp1(mac_m, kev_m, mac_mid);\n\tfit.kev{mm} = [kev_m(1) kev_mid kev_m(end)]';\nend\n\nmeth = {'fmfun', @de_ftab_fit_exp_eval, '(sll)'; ...\n\t'fgrad', @de_ftab_fit_exp_grad, '(sll)'; ...\n\t'show_err', @de_ftab_fit_show_err, '(sl, fm)'; ...\n\t'show_fm', @de_ftab_fit_show_fm, '(sl, fm)'; ...\n\t'show_sp', @de_ftab_fit_show_sp, '(en, sp)'; ...\n\t};\nfit = strum(fit, meth);\n\nif arg.show\n\tfit.show_fm(sl, fm);\nend\n\nend % de_ftab_fit_exp3()\n\n\n%\n% de_ftab_fit_exp()\n% todo: more documentation\n%\nfunction [fit, ffun, fgrad] = de_ftab_fit_exp(sl, fm, MM, wt, mtype, mac, kev)\n\nsll = ndgrid_jf('mat', sl{:});\n\nif isempty(mac)\n\tif isempty(mtype), error 'mac or mtype required', end\n\tmac = xray_read_atten(mtype, kev);\nend\n\nLL = length(sl);\n\nif isempty(wt), wt = num2cell(ones(MM,1)); end\n\nAb = 1;\nfor ll=1:LL\n\tsl = col(stackpick(sll, ll));\n\tAb = Ab .* exp(-sl * mac(:,ll)'); % [#s*, #E]\nend\n\nfit.kev = cell(1,MM);\nfit.mac = cell(1,MM);\nfit.coef = cell(1,MM);\nfor mm=1:MM\n\tif LL == 1\n\t\tdat = fm(:,mm);\n\telseif LL == 2\n\t\tdat = fm(:,:,mm);\n\telse\n\t\tfail 'not done'\n\tend\n\tdat = stackpick(fm,mm);\n\ty = exp(-dat);\n\tWh = spdiag(sqrt(wt{mm}(:)), 'nowarn');\n\tx = wls_simplex(Ab, y(:), Wh); % coefficients for each energy\n\n\tie = x > 1e-6; % find key energies\n\tfit.kev{mm} = kev(ie);\n\tfit.mac{mm} = mac(ie,:); % [#E,L]\n\tA = 1;\n\tfor ll=1:LL\n\t\tsl = col(stackpick(sll,ll));\n\t\tA = A .* exp(-sl * fit.mac{mm}(:,ll)'); % [#s*, #E]\n\tend\n\tfit.coef{mm} = wls_simplex(A, y(:), Wh); % refit with key energies\nend\nffun = @de_ftab_fit_exp_eval;\nfgrad = @de_ftab_fit_exp_grad;\n\nend % de_ftab_fit_exp()\n\n\n%\n% de_ftab_fit_exp_eval()\n% evaluate \n% in\n%\tsll\t[(Nd),L]\tstackup of s1,s2,...,s_L\n% out\n%\tf\t[(Nd),M]\tstackup of f1,f2,...,f_M\n%\nfunction f = de_ftab_fit_exp_eval(fit, sll)\nNd = size(sll); LL = Nd(end); Nd = Nd(1:end-1);\nsll = reshape(sll, [], LL); % [*Nd,L]\nMM = fit.MM;\nf = zeros(prod(Nd),MM);\nfor mm=1:MM\n\tA = 1;\n\tmac = fit.mac{mm};\n\tfor ll=1:LL\n\t\tsl = sll(:,ll);\n\t\tA = A .* exp(-sl * mac(:,ll)'); % [*Nd,ne]\n\tend\n\ttmp = -log(A * fit.coef{mm}); % [*Nd,1]\n\tf(:,mm) = tmp;\nend\nf = reshape(f, [Nd MM]);\n\nend % de_ftab_fit_exp_eval()\n\n\n%\n% de_ftab_fit_exp_grad()\n% evaluate gradient of f for each of the given s vectors.\n% in\n%\tsll\t[(Nd),L]\tstackup of s1,s2,...,s_L\n% out\n%\tg\t[(Nd),L,M]\tstackup of gradients of f(s)\n%\nfunction g = de_ftab_fit_exp_grad(fit, sll)\nNd = size(sll); LL = Nd(end); Nd = Nd(1:end-1);\nsll = reshape(sll, [], LL); % [*Nd,L]\nMM = fit.MM;\ng = zeros(prod(Nd), LL, MM);\nfor mm=1:fit.MM\n\tA = 1;\n\tmac = fit.mac{mm}; % [ne,L]\n\talf = fit.coef{mm}; % [ne,1]\n\tfor ll=1:LL\n\t\tsl = sll(:,ll);\n\t\tA = A .* exp(-sl * mac(:,ll)'); % [*Nd,ne]\n\tend\n\tvm = A * alf; % [*Nd,1]\n\ttmp = A * (mac .* repmat(alf, [1 LL])); % [*Nd,L]\n\tg(:,:,mm) = tmp ./ repmat(vm, [1 LL]);\nend\ng = reshape(g, [Nd LL MM]);\n\nend % de_ftab_fit_exp_grad()\n\n\n%\n% de_ftab_fit_show_sp()\n% compare true spectra to fitted spectra\n%\nfunction out = de_ftab_fit_show_sp(fit, en, sp)\nif nargin < 3, fail 'de_ftab_fit_show_sp(fit, en, sp)', end\n\nif ~streq(fit.type, 'exp3'), printm 'show_sp only done for exp3', return, end\nif im\n\tclf, pl = (fit.MM+1)*100 + 10 + 1;\n\tsubplot(pl)\n\tplot(en, sp * diag(1 ./ max(sp)))\n\tif isfield(fit, 'kev')\n\t\tfor mm=1:fit.MM\n\t\t\tsubplot(pl+mm)\n\t\t\tbar(fit.kev{mm}, fit.coef{mm})\n\t\t\taxis tight, axisx(minmax(en))\n\t\tend\n\telse\n\t\twarn 'kev unknown'\n\tend\nend\n\nif nargout, out = []; end\n\nend % de_ftab_fit_show_sp()\n\n\n%\n% de_ftab_fit_show_fm()\n% compare fit to sampled fm\n%\nfunction out = de_ftab_fit_show_fm(fit, sl, fm)\nif nargin < 3, error 'de_ftab_fit_show_fm(fit, sl, fm)', end\n\nsll = ndgrid_jf('mat', sl{:});\n\nif fit.MM ~= 2, error 'only M=2 done', end\n\nfh = fit.fmfun(sll);\n\nswitch length(sl) % LL\ncase 1\n\ts1 = sl{1};\n\tim clf\n\tplot(\ts1, fm(:,1), 'c.', s1, fm(:,2), 'y.', ...\n\t\ts1, fh(:,1), 'c-', s1, fh(:,2), 'y-')\n\txlabel 's1'\n\tylabel 'fm(s1)'\n\tlegend('true m=1', 'true m=2', 'fit m=1', 'fit m=2', 4)\n\ncase 2\n\ts1 = sl{1};\n\ts2 = sl{2};\n\tsmax(1) = max(s1);\n\tsmax(2) = max(s2);\n\tfmax = max(fm(:));\n\n\tax = [0 smax(1) 0 smax(2) 0 fmax];\n\tcax = [0 fmax];\n\n\tim clf\n\tim pl 2 2\n\n\tshow(1, s1, s2, fm(:,:,1), ax, cax, 'f_1(s)')\n\t% text(-60, 10, '[cm^2/g]')\n\tshow(2, s1, s2, fm(:,:,2), ax, cax, 'f_2(s)')\n\n\tshow(3, s1, s2, fh(:,:,1), ax, cax, 'f_1 approx')\n\tshow(4, s1, s2, fh(:,:,2), ax, cax, 'f_2 approx')\notherwise\n\tfail 'not done'\nend\n\nif nargout, out = []; end\n\nend % de_ftab_fit_show_fm()\n\n\n%\n% de_ftab_fit_show_err()\n% show fit errors, and relate to HU\n% f = mac s, mac(70kev,H2O) = 0.2 cm^2 / g = 1000 HU\n% mh = mac * 1000 HU / (0.2 g/cm^2)\n% so Df/Dmh = Df/Dmac * Dmac/Dmh = (50 g/cm^2) (0.2 cm^2/g) / 1000 HU = 1/100 HU\n% so Dmh = 100 HU * Df for 50 cm of H2O.\n%\nfunction out = de_ftab_fit_show_err(fit, sl, fm)\nif nargin < 3, error 'de_ftab_fit_show_err(fit, sl, fm)', end\n\nsll = ndgrid_jf('mat', sl{:});\n\nfh = fit.fmfun(sll);\nerr = fh - fm;\nprintm('worst model error = %g of %g', max(abs(err(:))), max(fm(:)))\nprintm('worst model error = %g HU over 50cm H2O', 100*max(abs(err(:))))\nfor mm=1:fit.MM\n\tee = stackpick(err,mm);\n\tprintm('worst error (mm=%d): %g', mm, max(abs(ee(:))))\nend\n\nif max(abs(err(:))) == 0, return, end\nif fit.MM > 2, error 'only M=2 done', end\nif 0\n\te1 = err(:,:,1);\n\te2 = err(:,:,2);\n\tdisp([minmax(e1); minmax(e2)]')\n\tprintm('worst error1 %g', max(col(abs(err(:,1,:)))))\n\tprintm('worst error2 %g', max(col(abs(err(:,2,:)))))\nend\n%err = abs(err);\n\nswitch length(sl) % LL\ncase 1\n\ts1 = sl{1};\n\tplot(s1, err(:,1), 'c-', s1, err(:,2), 'y-')\n\txlabel 's1'\n\tylabel 'error'\n\tlegend('m=1', 'm=2', 4)\n\ncase 2\n\ts1 = sl{1};\n\ts2 = sl{2};\n\tsmax(1) = max(s1);\n\tsmax(2) = max(s2);\n\n\telim = minmax(err(:))';\n\t%elim = [-1 1] * 0.01; % +/- 1 HU\n\tax = [0 smax(1) 0 smax(2) elim];\n\tim plc 1 2\n\tfor mm=1:fit.MM\n\t\tshow(mm, s1, s2, err(:,:,mm), ax, elim, sprintf('f_%d error', mm))\n\tend\notherwise\n\tfail 'not done'\nend\n\nif nargout, out = []; end\n\nend % de_ftab_fit_show_err()\n\n\n%\n% show()\n%\nfunction show(pl, x, y, f, ax, cax, ti)\nif ~im, return, end\nim('subplot', pl)\nif 1\n\tmesh(x,y,f')\n\tcolormap hsv, caxis(cax), cbar\n\taxis(ax)\n\txtick, ytick, ztick, zwhite\nelse\n\tim(x,y,f), cbar\n\txtick, ytick\nend\nxlabel 's_1', ylabel 's_2', title(ti)\n\nend % show()\n\n\n%\n% de_ftab_fit_exp3_test()\n%\nfunction de_ftab_fit_exp3_test\n\n%stype = 'mono,70';\nstype = 'ps1';\nxrs = xray_read_spectra(stype);\n\nif 1 % L=1 component\n\tsl{1} = linspace(0, 50, 26);\n\tmtype = {'water'};\n\tmas = xray_read_mac(mtype);\n\tmac = mas.mac(xrs.en);\n\tif im\n\t\tclf, semilogy(xrs.en, mac), legend(mtype{:})\n\tend\n\tsll = ndgrid_jf('mat', sl{:});\n\tfm = de_ftab_fm(sll, mac, xrs.Ide);\n\tfit = de_ftab_fit(sl, fm, 'type', 'exp', 'mtype', mtype);\n\tg = fit.fgrad(sll);\n%\tfit = de_ftab_fit(sl, fm, 'type', 'poly')\n\n\tif 1\n\t\tfit.show_sp(xrs.en, xrs.sp);\n\t\tprompt\n\t\tfit.show_fm(sl, fm);\n\t\tprompt\n\t\tfit.show_err(sl, fm);\n\t\tprompt\n\tend\nend\n\nif 1 % L=2\n\tsl{1} = linspace(0, 50, 26);\n\tsl{2} = linspace(0, 30, 31);\n\tmtype = {'water', 'bone'};\n\tmas = xray_read_mac(mtype);\n\tmac = mas.mac(xrs.en);\n\tif im\n\t\tclf, semilogy(xrs.en, mac), legend(mtype{:})\n\tend\n\tsll = ndgrid_jf('mat', sl{:});\n\tfm = de_ftab_fm(sll, mac, xrs.Ide);\n\tfit = de_ftab_fit(sl, fm, 'type', 'exp', 'mtype', mtype);\n\tg = fit.fgrad(sll);\n\t%fit = de_ftab_fit(sl, fm, 'type', 'poly')\n\n\tif 1\n\t\tfit.show_sp(xrs.en, xrs.sp);\n\t\tprompt\n\t\tfit.show_fm(sl, fm);\n\t\tprompt\n\t\tfit.show_err(sl, fm);\n\t\tprompt\n\tend\nend\n\nend % de_ftab_fit_exp3_test()\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/arch/de_ftab_fit_exp3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.38416472747513797}}
{"text": "function [x,testdata]=alstpz_solve(A,y,tol,varargin)\n%Solution of linear systems in TT-format via ALS(t+z) iteration\n%!Note! This method is provided mostly for test purposes.\n%!Note! You may prefer to use amen_solve2 instead.\n% [X,somedata]=ALSTPZ_SOLVE(A,Y,TOL,OPTIONS) Attempts to solve the linear\n% system A*X = Y with accuracy/residual TOL using the global (t+z)-enriched ALS.\n% Matrix A has to be given in the TT-format, right-hand side Y should be\n% given in the TT-format also. Options are provided in form\n% 'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2 and so\n% on. The parameters are set to default (in brackets in the following)\n% The list of option names and default values are:\n% o x0 - initial approximation [random rank-2 tensor]\n% o nswp - maximal number of sweeps [10]\n% o max_full_size - maximal size of the local matrix to full solver [50]\n% o local_prec - local preconditioner: '' (no prec.), 'ljacobi',\n% 'cjacobi', 'rjacobi' ['']\n% o local_iters - number of local gmres restarts [2]\n% o local_restart - dimension of local gmres [40]\n% o kickrank - compression rank of the residual Z, i.e. expansion\n% size [4]\n% o kicktype - how to approximate the residual: via the SVD rounding ('svd'),\n% or using one approximation ALS sweep ('als'). ['svd']\n% o ismex - shall we use the MEX lib solve3d_2 for local solution [true]\n% o resid_damp - solve local problems with accuracy tol/resid_damp.\n% Larger value may reduce a spurious noise from inexact local\n% solutions, but increase CPU time [2]\n% o symm - shall we consider the symmetrized system (A'A)x=(A'y). [false]\n%\n% Example:\n% d=8; f=8;\n% mat=tt_qlaplace_dd(d*ones(1,f)); % Laplace in the QTT-format\n% rhs=tt_ones(2,d*f); % Right-hand side of all ones\n% sol = alstpz_solve(mat, rhs, 1e-5); % solve the Poisson eqn.\n%\n%********\n% References:\n% S. Dolgov, D. Savostyanov.\n% http://arxiv.org/abs/1301.6068 \n% http://arxiv.org/abs/1304.1222\n% \n% Please send feedback to: {sergey.v.dolgov,dmitry.savostyanov}@gmail.com\n%\n%********\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n% Inner parameters\nmax_full_size=50;\n\nresid_damp = 2; % Truncation error to true residual treshold\n\nnswp=10;\nlocal_restart=40;\nlocal_iters=2;\n\nlocal_prec = '';\n\nismex = true;\n\n% kicktype = 'als';\nkicktype = 'svd';\n\nkickrank = 4;\nx=[];\nsymm = false;\nverb = 3;\n\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'x0'\n x=varargin{i+1};\n case 'local_prec'\n local_prec=varargin{i+1};\n case 'local_restart'\n local_restart=varargin{i+1};\n case 'ismex'\n ismex=varargin{i+1}; \n case 'local_iters'\n local_iters=varargin{i+1};\n case 'kickrank'\n kickrank=varargin{i+1};\n case 'kicktype'\n kicktype=varargin{i+1}; \n case 'max_full_size'\n max_full_size=varargin{i+1};\n case 'resid_damp'\n resid_damp = varargin{i+1};\n case 'symm'\n symm=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n \n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\n% Disable MEX if it does not exist\nif (ismex)&&(exist('solve3d_2', 'file')<2)\n warning('MEX local solver is not found, disabled');\n ismex = false;\nend;\n\n% Extract sizes and TT blocks\nd = y.d;\nn = A.n;\nif (isempty(x))\n x = tt_rand(n, A.d, 2);\nend;\n\nif (symm)\n % Symmetrize the system if necessary\n A2 = A'*A;\n Ay = A'*y;\nend;\n\nif (strcmp(kicktype, 'als'))&&(kickrank>0)\n z = tt_rand(n, d, kickrank);\n rz = z.r;\n phi = cell(d+1,1); phi{1}=1; phi{d+1}=1;\nend;\n\n% Test output data -- e.g. for convergence tracking\ntestdata = cell(3,1);\ntestdata{2} = cell(d, nswp);\ntestdata{1} = zeros(d, nswp);\ntestdata{3} = zeros(1, nswp);\nt_corr_amen = tic;\n\n% ALS(t+z) sweeps\nfor swp=1:nswp\n % Truncate the solution first\n x = round(x,tol);\n if (strcmp(kicktype, 'als'))&&(kickrank>0)\n % Update the residual approximation via one ALS sweep for |z-ZZ|->min\n % Exact residual\n if (symm)\n ZZ = Ay - A2*x;\n else\n ZZ = y - A*x;\n end;\n rZZ = ZZ.r;\n ZZ = core2cell(ZZ);\n z = core2cell(z); % Approximate one\n for i=1:d-1\n % Go backward and prepare projections\n cr = reshape(z{i}, rz(i)*n(i), rz(i+1));\n [cr,rv]=qr(cr,0);\n cr2 = reshape(z{i+1}, rz(i+1), n(i+1)*rz(i+2));\n cr2 = rv*cr2;\n rz(i+1) = size(cr, 2);\n z{i} = reshape(cr, rz(i), n(i), rz(i+1));\n z{i+1} = reshape(cr2, rz(i+1), n(i+1), rz(i+2));\n \n phi{i+1} = compute_next_Phi(phi{i}, z{i}, [], ZZ{i}, 'lr');\n end;\n for i=d:-1:1\n % Go forward and project exact ZZ\n cr = reshape(ZZ{i}, rZZ(i)*n(i), rZZ(i+1));\n cr = cr*phi{i+1};\n cr = reshape(cr, rZZ(i), n(i)*rz(i+1));\n cr = phi{i}*cr;\n if (i>1)\n [cr,rv]=qr(cr.', 0);\n cr2 = reshape(z{i-1}, rz(i-1)*n(i-1), rz(i));\n cr2 = cr2*rv.';\n rz(i) = size(cr, 2);\n z{i} = reshape(cr.', rz(i), n(i), rz(i+1));\n z{i-1} = reshape(cr2, rz(i-1), n(i-1), rz(i));\n \n phi{i} = compute_next_Phi(phi{i+1}, z{i}, [], ZZ{i}, 'rl');\n else\n z{i} = reshape(cr, rz(i), n(i), rz(i+1));\n end;\n end;\n z = cell2core(tt_tensor, z);\n else\n % SVD rounding of the exact residual up to kickrank\n if (kickrank>0)\n if (symm)\n z = round(Ay - A2*x, tol, kickrank);\n else\n z = round(y - A*x, tol, kickrank);\n end;\n end;\n end;\n\n % Augment the solution with Z basis\n if (kickrank>0)\n x = x+0*z;\n end;\n t_old = toc(t_corr_amen);\n % Update via the ALS iteration\n if (symm)\n [x,td_als] = als_solve(A2, Ay, tol, 'max_full_size', max_full_size, 'x0', x, 'verb', verb, 'local_prec', local_prec, 'local_iters', local_iters, 'local_restart', local_restart, 'resid_damp', resid_damp, 'ismex', ismex);\n else\n [x,td_als] = als_solve(A, y, tol, 'max_full_size', max_full_size, 'x0', x, 'verb', verb, 'local_prec', local_prec, 'local_iters', local_iters, 'local_restart', local_restart, 'resid_damp', resid_damp, 'ismex', ismex);\n end;\n testdata{1}(:, swp) = t_old+td_als{1}(:,1);\n testdata{2}(:, swp) = td_als{2};\n testdata{3}(swp) = max(td_als{3});\nend;\n\nend\n\n\n\nfunction [x,td]=als_solve(A, y, tol, varargin)\n% One sweep of the one-site DMRG solution scheme.\n% Uses the same parameters as in the main function\n\nlocal_prec_char = 0;\nverb = 1;\nismex = true;\n\nx=[];\n\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'x0'\n x=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'local_prec'\n local_prec=varargin{i+1};\n case 'local_restart'\n local_restart=varargin{i+1};\n case 'local_iters'\n local_iters=varargin{i+1};\n case 'ismex'\n ismex=varargin{i+1}; \n case 'max_full_size'\n max_full_size=varargin{i+1};\n case 'resid_damp'\n resid_damp = varargin{i+1};\n \n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\nif (strcmp(local_prec, 'cjacobi')); local_prec_char = 1; end;\nif (strcmp(local_prec, 'ljacobi')); local_prec_char = 2; end;\nif (strcmp(local_prec, 'rjacobi')); local_prec_char = 3; end;\n\n% Extract sizes and TT cores\nd = y.d;\nn = A.n;\nif (isempty(x))\n x = tt_rand(n, A.d, 2);\nend;\n\n\nry = y.r;\nra = A.r;\nrx = x.r;\n\ncry = core2cell(y);\ncrA = core2cell(A);\ncrx = core2cell(x);\n\n% Interfaces\nphia = cell(d+1,1); phia{1}=1; phia{d+1}=1;\nphiy = cell(d+1,1); phiy{1}=1; phiy{d+1}=1;\n\n\n% This is some convergence output for test purposes\ntd = cell(3,1); \ntd{1} = zeros(d, 1);\ntd{2} = cell(d, 1);\ntd{3} = zeros(d, 1);\n\nt_amr_solve = tic;\n\n% Orthogonalization\nfor i=d:-1:2\n cr = crx{i};\n cr = reshape(cr, rx(i), n(i)*rx(i+1));\n [cr, rv]=qr(cr.', 0);\n cr2 = crx{i-1};\n cr2 = reshape(cr2, rx(i-1)*n(i-1), rx(i));\n cr2 = cr2*(rv.');\n rx(i) = size(cr, 2);\n cr = reshape(cr.', rx(i), n(i), rx(i+1));\n crx{i-1} = reshape(cr2, rx(i-1), n(i-1), rx(i));\n crx{i} = cr;\n\n phia{i} = compute_next_Phi(phia{i+1}, cr, crA{i}, cr, 'rl');\n phiy{i} = compute_next_Phi(phiy{i+1}, cr, [], cry{i}, 'rl');\nend;\n\nmax_res = 0;\nmax_dx = 0;\n\n% DMRG sweep\nfor i=1:d\n % Extract elements - matrix\n Phi1 = phia{i}; Phi2 = phia{i+1};\n % Phi1: rx'1, rx1, ra1, or rx'1, ry1\n % Phi2: rx2, ra2, rx'2, or ry'2, rx2\n A1 = crA{i}; y1 = cry{i};\n % RHS - rewrite it in accordance with new index ordering\n rhs = phiy{i}; % rx'1, ry1\n y1 = reshape(y1, ry(i), n(i)*ry(i+1));\n rhs = rhs*y1;\n rhs = reshape(rhs, rx(i)*n(i), ry(i+1));\n rhs = rhs*phiy{i+1}; \n rhs = reshape(rhs, rx(i)*n(i)*rx(i+1),1);\n norm_rhs = norm(rhs);\n % sol_prev\n sol_prev = reshape(crx{i}, rx(i)*n(i)*rx(i+1), 1);\n\n real_tol = (tol/sqrt(d))/resid_damp;\n\n if (rx(i)*n(i)*rx(i+1)real_tol)\n sol = B \\ rhs;\n res_new = norm(B*sol-rhs)/norm_rhs;\n else\n sol = sol_prev;\n res_new = res_prev;\n end;\n\n else % Structured solution.\n \n res_prev = norm(bfun3(Phi1, A1, Phi2, sol_prev) - rhs)/norm_rhs;\n \n if (res_prev>real_tol)\n if (~ismex)\n sol = solve3d_2ml(Phi1, A1, Phi2, rhs, real_tol, sol_prev, local_prec_char, local_restart, local_iters);\n else % use MEX\n sol = solve3d_2(Phi1, A1, Phi2, rhs, real_tol, 1, sol_prev, local_prec_char, local_restart, local_iters, 0);\n end;\n \n res_new = norm(bfun3(Phi1, A1, Phi2, sol) - rhs)/norm_rhs;\n else\n sol = sol_prev;\n res_new = res_prev;\n end;\n \n end;\n\n if (res_prev/res_newreal_tol)\n fprintf('--warn-- the residual damp was smaller than in the truncation\\n');\n end;\n\n dx = norm(sol-sol_prev)/norm(sol);\n max_dx = max(max_dx, dx);\n max_res = max(max_res, res_prev);\n \n td{3}(i) = dx;\n \n % QR\n sol = reshape(sol, rx(i)*n(i), rx(i+1));\n [u,v]=qr(sol, 0);\n r = size(u,2);\n\n if (verb==2)\n fprintf('=als_solve= block %d, dx: %3.3e, res: %3.3e, r: %d\\n', i, dx, res_prev, r);\n end;\n\n if (i2)\n td{1}(i) = toc(t_amr_solve);\n if (verb>3)||(i==d) % each microstep is returned only if really asked for\n % Otherwise the memory will blow up\n x = cell2core(x, crx); % for test\n td{2}{i} = x;\n end;\n end;\n\nend;\n\nif (verb>0) \n fprintf('=als_solve= max_dx: %3.3e, max_res: %3.3e, erank: %g\\n', max_dx, max_res, sqrt(rx(1:d)'*(n.*rx(2:d+1))/sum(n)));\nend;\n\nx = cell2core(x, crx);\n\nend\n\n\nfunction [Phi] = compute_next_Phi(Phi_prev, x, A, y, direction)\n% Performs the recurrent Phi (or Psi) matrix computation\n% Phi = Phi_prev * (x'Ay).\n% If direction is 'lr', computes Psi\n% if direction is 'rl', computes Phi\n% A can be empty, then only x'y is computed.\n\n% Phi1: rx1, ry1, ra1, or rx1, ry1\n% Phi2: ry2, ra2, rx2, or ry2, rx2\n\n\nrx1 = size(x,1); n = size(x,2); rx2 = size(x,3);\nry1 = size(y,1); m = size(y,2); ry2 = size(y,3);\nif (~isempty(A))\n ra1 = size(A,1); ra2 = size(A,4);\nelse\n ra1 = 1; ra2 = 1;\nend;\n\nif (strcmp(direction, 'lr'))\n %lr: Phi1\n x = reshape(x, rx1, n*rx2);\n Phi = reshape(Phi_prev, rx1, ry1*ra1);\n Phi = x'*Phi;\n if (~isempty(A))\n Phi = reshape(Phi, n*rx2*ry1, ra1);\n Phi = Phi.';\n Phi = reshape(Phi, ra1*n, rx2*ry1);\n A = reshape(A, ra1*n, m*ra2);\n Phi = A.'*Phi;\n Phi = reshape(Phi, m, ra2*rx2*ry1);\n else\n Phi = reshape(Phi, n, rx2*ry1);\n end;\n Phi = Phi.';\n Phi = reshape(Phi, ra2*rx2, ry1*m);\n\n y = reshape(y, ry1*m, ry2);\n Phi = Phi*y;\n if (~isempty(A))\n Phi = reshape(Phi, ra2, rx2*ry2);\n Phi = Phi.';\n end;\n Phi = reshape(Phi, rx2, ry2, ra2); \nelse\n %rl: Phi2\n y = reshape(y, ry1*m, ry2);\n Phi = reshape(Phi_prev, ry2, ra2*rx2);\n Phi = y*Phi;\n if (~isempty(A))\n Phi = reshape(Phi, ry1, m*ra2*rx2);\n Phi = Phi.';\n Phi = reshape(Phi, m*ra2, rx2*ry1);\n A = reshape(A, ra1*n, m*ra2);\n Phi = A*Phi;\n Phi = reshape(Phi, ra1*n*rx2, ry1);\n Phi = Phi.';\n end;\n \n Phi = reshape(Phi, ry1*ra1, n*rx2);\n x = reshape(x, rx1, n*rx2);\n Phi = Phi*x';\n if (~isempty(A))\n Phi = reshape(Phi, ry1, ra1, rx1);\n else\n Phi = reshape(Phi, ry1, rx1);\n end;\nend;\n\nend\n\n\n% new\nfunction [y]=bfun3(Phi1, A, Phi2, x)\n% Phi1: ry1, rx1, ra1\nry1 = size(Phi1,1);\nrx1 = size(Phi1,2);\nra1 = size(Phi1,3);\n% Phi2: rx2, ra2, ry2\nry2 = size(Phi2,3);\nrx2 = size(Phi2,1);\nra2 = size(Phi2,2);\n\nn = size(A,2);\nm = size(A,3);\n\ny = reshape(x, rx1*m, rx2);\nPhi2 = reshape(Phi2, rx2, ra2*ry2);\ny = y*Phi2;\ny = reshape(y, rx1, m*ra2*ry2);\ny = y.';\ny = reshape(y, m*ra2, ry2*rx1);\nA = reshape(A, ra1*n, m*ra2);\ny = A*y;\ny = reshape(y, ra1*n*ry2, rx1);\ny = y.';\ny = reshape(y, rx1*ra1, n*ry2);\nPhi1 = reshape(Phi1, ry1, rx1*ra1);\ny = Phi1*y;\ny = reshape(y, ry1*n*ry2, 1);\nend\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/solve/alstpz_solve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3840495154040556}}
{"text": "function a = lt( x, y )\n\n% Disciplined convex programming information for LT (<):\n% The left-hand side of a less-than constraint must be convex. The\n% right-hand side must be concave. Of course, real constant and \n% affine expressions are both convex and concave and can be used on\n% either side as well.\n% \n% Disciplined geometric programming information for LT (<):\n% The left-hand side of a less-than constraint must be log-convex,\n% including positive constants, monomials, posynomials, generalized\n% posynomials, and products thereof. The right-hand side must be \n% log-concave---including positive constants, monomials, \n% reciprocals of log-convex expressions, and products thereof.\n% \n% Note that CVX does not distinguish between strict less-than (<) and\n% less-than-or-equal (<=) constraints; they are treated identically. \n% Feasible interior-point solvers tend to return points which satisfy\n% strict inequality, but not all solvers do.\n\nevalin( 'caller', 'cvx_verify' );\nb = cvx_pushcnstr( x, y, '<' );\nif nargout, a = b; end\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/builtins/@cvxcnst/lt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.383192225968809}}
{"text": "function [W,BC,DV,Q,r,B] = voxelize(V,F,side,varargin)\n % VOXELIZE Given a mesh compute a voxelization of that mesh on a regular grid\n % fit to the bounding box.\n %\n % W = voxelize(V,F,side)\n % [W,BC,DV,Q] = voxelize(V,F,side,'ParameterName',ParameterValue, ...)\n %\n % Inputs:\n % V #V by 3 list of vertex positions\n % F #F by 3 list of triangle indices into V, expects counterclockwise\n % orientation to produce outward pointing normal\n % side either the number of cells in the x direction or a triple\n % containing the number of cells in each dimension\n % Optional:\n % 'Pad' followed by number of padding to add to each side. 1 would mean\n % add one extra cell on the top, bottom, left, right, front, and back\n % of bounding box lattice {0}.\n % 'Boundary' followed by wether to consider any cell intersecting the\n % mesh as inside {true}.\n % 'Interior' followed by whether to consider any cell full inside the\n % mesh as inside {true}\n % 'Closed' followed by whether to assume mesh is closed when determining\n % interior (avoid winding number computation, use flood filling)\n % 'Centers' followed by prod(side) centers (e.g., already produced by\n % call to previous call to voxel_grid.m)\n % Outputs:\n % W side(1) by side(2) by side(3) matrix with W(i,j,k) ~= if location\n % cell centered at BC(i,j,k) overlaps with the volume of (V,F)\n % BC prod(side) by dim matrix of cell barycenters\n % DV side(1)+1 by side(2)+1 by side(3)+1 matrix of cell corner locations\n % Q #Q by 4 list of quads indexing DV\n % r dim-long list of voxel widths in each direction\n %\n % Known issues: the ouput surface mesh will contain non-manifold edges and\n % vertices at voxels that meet at such edges or vertices. \n %\n % Example:\n % [W,BC,DV,Q] = voxelize(V,F,50);\n % % Get triangles from quads\n % DF = [Q(:,[1 2 3]);Q(:,[1 3 4])];\n % % Remove unreferenced corners\n % [SV,IM] = remove_unreferenced(DV,DF);\n % % re-index\n % SF = IM(DF);\n % SQ = IM(Q);\n %\n % [W,BC] = voxelize(V,F,50,'Pad',1);\n % % Use matlab's isosurface to extract surface as triangle mesh\n % BC = reshape(BC,[size(W) 3]);\n % surf = isosurface(BC(:,:,:,1),BC(:,:,:,2),BC(:,:,:,3),W,0.5);\n % DV = bsxfun(@plus,bsxfun(@times,bsxfun(@rdivide,surf.vertices-1, ...\n % [size(W,2) size(W,1) size(W,3)]-1),max(BC)-min(BC)),min(BC));\n % DF = surf.faces;\n % \n %\n % See also: bwboundaries, isosurface\n\n with_boundary = true;\n with_interior = true;\n pad_count = 0;\n closed = [];\n BC = [];\n % default values\n % Map of parameter names to variable names\n params_to_variables = containers.Map( ...\n {'Boundary','Interior','Pad','Centers','Closed'}, ...\n {'with_boundary','with_interior','pad_count','BC','closed'});\n v = 1;\n while v <= numel(varargin)\n param_name = varargin{v};\n if isKey(params_to_variables,param_name)\n assert(v+1<=numel(varargin));\n v = v+1;\n % Trick: use feval on anonymous function to use assignin to this workspace\n feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n else\n error('Unsupported parameter: %s',varargin{v});\n end\n v=v+1;\n end\n if isempty(closed)\n closed = isempty(boundary_faces(F));\n end\n\n\n assert(any(size(side) == 1),'side should be a vector');\n % Make sure we have a row vector\n side = side(:)';\n\n dim = size(V,2);\n\n if isempty(BC)\n [BC,side,r] = voxel_grid(V,side,'Pad',pad_count);\n else\n assert(prod(side) == size(BC,1),'side dims must match BC');\n r = (max(BC)-min(BC))./(side-1);\n end\n NV = min(BC);\n XV = max(BC);\n\n switch dim\n case 2\n W = zeros([side(2) side(1)]);\n [DV,~,QT,QL] = voxel_surface(W,'Centers',BC);\n\n if with_interior && ~closed\n WDV = reshape(winding_number(V,F,DV),[side(2) side(1)]+1);\n WDV = abs(WDV) >= 0.5;\n W = ( ...\n WDV(1:end-1,1:end-1) | ...\n WDV(1:end-1, 2:end) | ...\n WDV( 2:end,1:end-1) | ...\n WDV( 2:end, 2:end));\n end\n Q = [QT;QL];\n if with_boundary\n for ei = 1:size(F,1)\n\n sqrD = segment_segment_squared_distance( ...\n V(F(ei,1),:), V(F(ei,2),:), ...\n DV(Q(:,1),:), DV(Q(:,2),:));\n IF = mod(find(sqrDsize(QT,1))-size(QT,1);\n\n [II,JJ] = ind2sub([side(2) side(1)]+1,max(QT(iQT,:),[],2));\n W(sub2ind(side([2 1]),II-1,JJ-1)) = 1;\n W(sub2ind(side([2 1]),II ,JJ-1)) = 1;\n\n [II,JJ] = ind2sub([side(2) side(1)]+1,max(QL(iQL,:),[],2));\n W(sub2ind(side([2 1]),II-1,JJ-1)) = 1;\n W(sub2ind(side([2 1]),II-1,JJ )) = 1;\n\n %clf;\n %hold on;\n %surf(reshape(BC(:,1),size(W)),reshape(BC(:,2),size(W)),reshape(BC(:,1)*0,size(W)),'CData',W*1,fphong,'EdgeColor','none');\n %plot_edges(V,F(ei,:),'y','LineWidth',8);\n %plot_edges(V,F,'g','LineWidth',4);\n %text(BC(:,1),BC(:,2),num2str((1:size(BC,1))'),'BackgroundCOlor',[0.8 0.8 0.8]);\n %text(DV(:,1),DV(:,2),num2str((1:size(DV,1))'),'BackgroundCOlor',[0.8 0.1 0.1]);\n %plot_edges(DV,QT,'--r','LineWidth',1);\n %plot_edges(DV,QL,'--b','LineWidth',1);\n %plot_edges(DV,QT(iQT,:),'r','LineWidth',3);\n %plot_edges(DV,QL(iQL,:),'b','LineWidth',3);\n %hold off;\n %axis equal;\n %colormap([zeros(20,3);1 1 1]);\n %drawnow;\n\n end\n end\n if with_interior && closed\n W = imfill(W,'holes');\n end\n % Pad winding number with 0s and take differences in all 6 directions\n Wp = padarray(W,[1 1],0);\n Dy = diff(Wp,1,1);\n Dx = diff(Wp,1,2);\n Q = [ ...\n QL(Dx(2:end-1,1:end,2:end-1)>0.5,:); ...\n QT(Dy(1:end,2:end-1,2:end-1)>0.5,:); ...\n fliplr(QL(Dx(2:end-1,1:end,2:end-1)<-0.5,:)); ...\n fliplr(QT(Dy(1:end,2:end-1,2:end-1)<-0.5,:)); ...\n ];\n case 3\n W = zeros([side(2) side(1) side(3)]);\n [DV,~,QT,QF,QL] = voxel_surface(W,'Centers',BC);\n \n if with_interior && ~closed\n % Winding number is a heavy handed way of determining inside/outside for a\n % simple closed polyhedron. If the boundary has already been detected then\n % this should be floodfilling instead.\n \n %W = winding_number(V,F,BC);\n WDV = reshape(winding_number(V,F,DV,'Fast',true),[side(2) side(1) side(3)]+1);\n WDV = abs(WDV) >= 0.5;\n W = ( ...\n WDV(1:end-1,1:end-1,1:end-1) | ...\n WDV(1:end-1,1:end-1,2:end) | ...\n WDV(1:end-1, 2:end,1:end-1) | ...\n WDV(1:end-1, 2:end,2:end) | ...\n WDV( 2:end,1:end-1,1:end-1) | ...\n WDV( 2:end,1:end-1,2:end) | ...\n WDV( 2:end, 2:end,1:end-1) | ...\n WDV( 2:end, 2:end,2:end));\n end\n \n Q = [QT;QF;QL];\n \n if with_boundary\n % TODO: Could at least ignore already-inside cells.\n DF = [Q(:,[3 2 1]);Q(:,[4 3 1])];\n IF = intersect_other(V,F,DV,DF);\n JF = IF(:,1);\n IF = mod(IF(:,2)-1,size(Q,1))+1;\n B = zeros(side(2),side(1),side(3));\n % Force winding number to mark voxels intersecting boundary as inside\n % (This should just be replaced with rasterizing the surface)\n iQ = cell(3,1);\n iQ{1} = IF(IF<=size(QT,1));\n iQ{3} = IF(IF>size(QT,1) & IF<=size(QT,1)+size(QF,1))-size(QT,1);\n iQ{2} = IF(IF>size(QT,1)+size(QF,1))-size(QT,1)-size(QF,1);\n jQ{1} = JF(IF<=size(QT,1));\n jQ{3} = JF(IF>size(QT,1) & IF<=size(QT,1)+size(QF,1));\n jQ{2} = JF(IF>size(QT,1)+size(QF,1));\n\n side123 = side([2 1 3]);\n for d = 1:3\n sz = side123;\n sz(d) = sz(d)+1;\n II = cell(3,1);\n [II{1},II{2},II{3}] = ind2sub(sz,iQ{d});\n for pass = 0:1\n II{d} = II{d}-pass;\n keep = II{d}<=side123(d);\n B(sub2ind(side123,II{1}(keep),II{2}(keep),II{3}(keep))) = jQ{d}(keep);\n end\n end\n\n W = W | B;\n end\n \n if with_interior && closed\n W = imfill(W,'holes');\n end\n \n %trisurf(Q(IF,:),DV(:,1),DV(:,2),DV(:,3),'FaceColor','r');\n %hold on;\n %tsurf(F,V,'FaceColor','g','FaceAlpha',0.2,'EdgeAlpha',0.2);\n %hold off;\n \n %% From cells to faces:\n %[II,JJ,KK] = ind2sub([side(2) side(1) side(3)],find(abs(W)>0.5));\n %Q = [ ...\n % QT(sub2ind([side(2)+1 side(1) side(3) ],II+1,JJ,KK),:); ...\n % QT(sub2ind([side(2)+1 side(1) side(3) ],II+0,JJ,KK),:); ...\n % QF(sub2ind([side(2) side(1) side(3)+1],II,JJ,KK+1),:); ...\n % QF(sub2ind([side(2) side(1) side(3)+1],II,JJ,KK+0),:); ...\n % QL(sub2ind([side(2) side(1)+1 side(3) ],II,JJ+1,KK),:); ...\n % QL(sub2ind([side(2) side(1)+1 side(3) ],II,JJ+0,KK),:); ...\n % ];\n %trisurf(Q,DV(:,1),DV(:,2),DV(:,3),'FaceAlpha',0.5,'EdgeAlpha',0.5);\n %hold on;\n %tsurf(F,V,'FaceColor','g','FaceAlpha',0.2,'EdgeAlpha',0.2);\n %hold off;\n %axis equal\n %\n %error\n \n % Pad winding number with 0s and take differences in all 6 directions\n Wp = padarray(W,[1 1 1],0);\n Dy = diff(Wp,1,1);\n Dx = diff(Wp,1,2);\n Dz = diff(Wp,1,3);\n Q = [ ...\n QF(Dz(2:end-1,2:end-1,1:end)>0.5,:); ...\n QL(Dx(2:end-1,1:end,2:end-1)>0.5,:); ...\n QT(Dy(1:end,2:end-1,2:end-1)>0.5,:); ...\n fliplr(QF(Dz(2:end-1,2:end-1,1:end)<-0.5,:)); ...\n fliplr(QL(Dx(2:end-1,1:end,2:end-1)<-0.5,:)); ...\n fliplr(QT(Dy(1:end,2:end-1,2:end-1)<-0.5,:)); ...\n ];\n end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/voxelize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3831447774255979}}
{"text": "function model = ml_traincov(varargin)\n% Learn a linear predictive model using covariance-based classification.\n% Model = ml_traincov(Trials, Targets, Options...)\n%\n% This method assumes that the given trials values represent covariance matrices and offers various\n% methods, including information geometric approaches, to classify them. This implementation uses\n% the covariance toolbox by Alexandre Barachant.\n%\n% In:\n% Trials : training data, as in ml_train\n%\n% Targets : target variable, as in ml_train\n%\n% Out:\n% Model : the predictive model; can be used with ml_predictcov\n%\n% Examples:\n% % learn a model using the defaults\n% model = ml_traincov(trials,targets);\n%\n% See also:\n% ml_predictcov\n%\n% Christian Kothe, Syntrogi\n% 2015-04-21\ndp;\n\narg_define([0 3],varargin, ...\n arg_norep('trials'), ...\n arg_norep('targets'), ...\n arg({'classifier','ClassificationMethod'},'mdm',{'mdm','fgmdm','tslda'}, 'Classification method to use. The mdm method (minimum distance to mean) is based on minimum distance to class mean using a given distance metric and mean estimation metric. The fgmdm (filtered geodesic mdm) method additionally performs geodesic filtering. The tslda method (tangent-space linear discriminant analysis) is an LDA implementation that respects the Riemannian geometry of the data.'), ...\n arg({'mean_est','MeanEstimator'},'riemann',{'arithmetic','riemann','riemanndiag','riemanntrim','median','riemannmed','logeuclid','opttransp','ld','geodesic','harmonic','geometric'},'Method to average covariance matrices. Various methods are supported, including Riemannian mean/median/trimmed mean, log-euclidean mean, optimal transportation mean, log determinant mean, and geodesic iterative mean.'), ...\n arg({'distance_metric','DistanceMetric'},'riemann',{'euclid','riemann','kullback','logeuclid','opttransp','ld'},'Distance metric to use. This is only used for the mdm and fgmdm methods. Different distance metrics are supported, including the Euclidean metric, the Riemannian distance, Kullback-Leibler divergence, log-euclidean distance, optimal transportation distance, and log determinant distance'));\n\n% find the class labels\nclasses = unique(targets);\nif length(classes) == 1\n error('BCILAB:only_one_class','Your training data set has no trials for one of your classes; you need at least two classes to train a classifier.\\n\\nThe most likely reasons are that one of your target markers does not occur in the data, or that all your trials of a particular class are concentrated in a single short segment of your data (10 or 20 percent). The latter would be a problem with the experiment design.');\nelse\n % reformat feature shape to DxDxN\n if ndims(trials) == 2 %#ok\n [N,F] = size(trials);\n D = sqrt(F);\n if abs(D-round(D)) > 0\n error('The number of features in your trials must be a square of an integer.'); end\n trials = reshape(trials',[D,D,N]);\n else\n [U,V,N] = size(trials); %#ok\n if U ~= V\n error('Your feature matrices are not square, i.e., cannot be covariance matrices.'); end\n end\n \n model.classes = classes;\n switch classifier\n case 'mdm'\n % minimum distance to mean: estimate class means\n for c=length(classes):-1:1\n model.C{c} = mean_covariances(trials(:,:,targets==classes(c)),mean_est); end\n case 'fgmdm'\n % filtered geodesic minimum distance to mean \n % geodesic filtering\n [model.W,model.Cg] = fgda(trials,targets,mean_est,{},'shcov',{});\n trials = geodesic_filter(trials,model.Cg,model.W(:,1:length(model.classes)-1));\n % estimate class means\n for c=length(classes):-1:1\n model.C{c} = mean_covariances(trials(:,:,targets==classes(c)),mean_est); end\n case 'tslda'\n error('This variant is not yet implemented!');\n otherwise\n error('Unsupported classification method: %s',hlp_tostring(classifier));\n end\nend\n\nmodel.classifier = classifier;\nmodel.mean_est = mean_est;\nmodel.distance_metric = distance_metric;\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/machine_learning/ml_traincov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3829067913879946}}
{"text": "function [fx,dfdx,dfdp] = f_HRF2(Xt,P,ut,in)\n% Balloon (HRF) model evolution function in log-space\n% function [fx,dfdx,dfdp] = f_HRF2(Xt,P,ut,in)\n% This function evaluates the evolution function derived from the balloon\n% model for the hemodynamic response function. It can be called in two\n% ways: (i) as a \"stand-alone\" evolution function, whereby the system's\n% states are hemodynamic states of the balloon model, or (ii) as a\n% generalized observation function, where the real system's states are the\n% neuronal states of a DCM for fMRI model. Note that the hemodynamic states\n% are in log-space, for positivity constrints.\n\n\ndeltat = in.deltat;\nn = size(Xt,1);\n\n% Get parameters\n[E0,V0,tau0,kaf,kas,epsilon,alpha] = BOLD_parameters;\nif isfield(in,'fullDCM') && in.fullDCM\n nreg = n./5;\n ind1 = in.ind1;\n ind2 = in.ind2;\n ind3 = in.ind3;\n ind4 = in.ind4;\n n1 = in.n1;\n n2 = in.n2;\n n3 = in.n3;\n n4 = in.n4;\n try, n5=in.n5; catch, n5=[];end\n epsilon = 1;\n alpha = alpha.*exp(P(in.ind5));\nelse\n nreg = n./4;\n ind1 = 1;\n ind2 = 2;\n ind3 = 3;\n ind4 = 4;\n n1 = 1;\n n2 = 2;\n n3 = 3;\n n4 = 4;\n epsilon = epsilon.*exp(P(5));\n alpha = alpha.*exp(P(6));\nend\n% [E0,dsdp] = sigm(P(ind1)-0.6633,struct('beta',1,'G0',1,'INV',0));\n% E0 = E0(:);\nE0 = 1./(1+exp(-(P(ind1)-0.6633)));\ndsdp = E0.*(1-E0);\ntau0 = tau0.*exp(P(ind2));\nkaf = kaf.*exp(P(ind3));\nkas = kas.*exp(P(ind4));\n\nif isfield(in,'xshift') % for numerical stability\n xshift = in.xshift;\nelse\n xshift = 0;\nend\n\n% hemodynamic states ...\nif isfield(in,'linearized') && in.linearized\n x1 = zeros(nreg,1);\n x2 = ones(nreg,1);\n x3 = ones(nreg,1);\n x4 = ones(nreg,1);\nelse\n % vasodilatory signal s(t)\n x1 = Xt(n1,:);\n % blood inflow f(t)\n if isfield(in,'logx2') && ~in.logx2\n x2 = Xt(n2,:) + 1; % deviation to steady-state!\n else\n x2 = exp(Xt(n2,:)) + xshift;\n end\n % blood volume v(t)\n x3 = exp(Xt(n3,:)) + 0.*xshift;\n % dHb content q(t)\n x4 = exp(Xt(n4,:)) + 0.*xshift;\nend\n% blood outflow\nfv = x3.^(1./alpha);\n% d[blood flow]/dXt(3)\ndfvdx = (1./alpha).*fv;\n% oxygen extraction\nff = (1-(1-E0).^(1./x2))./E0;\n% d[O2 extraction]/dXt(2)\nif isfield(in,'logx2') && ~in.logx2\n dffdx = log(1-E0).*(1-E0).^(1./x2)./(E0.*x2.^2);\nelse\n dffdx = log(1-E0).*(1-E0).^(1./x2)./(E0.*x2);\nend\n% ... and flow field, derivatives, etc...\nf = zeros(n,1);\nJ = zeros(n,n);\ndfdp = zeros(size(P,1),n);\n\n% Evaluate flow field\nf(n1) = (epsilon.*ut - kas.*x1 - kaf.*(x2 - 1));\nif isfield(in,'logx2') && ~in.logx2\n f(n2) = x1;\nelse\n f(n2) = x1./x2;\nend\nf(n3) = (x2 - fv)./(tau0.*x3);\nf(n4) = (x2.*ff./x4 - fv./x3)./tau0;\n\n\n% Evaluate jacobian and gradients wrt parameters\nfor i=1:nreg\n \n if isfield(in,'logx2') && ~in.logx2\n J(n1(i),n1(i):n1(i)+3) = [ -kas(i) , 1, 0, 0 ];\n J(n2(i),n1(i):n1(i)+3) = [ -kaf(i), 0, ...\n 1./(tau0(i).*x3(i)), ...\n (ff(i)+x2(i).*dffdx(i))./(x4(i).*tau0(i))];\n else\n J(n1(i),n1(i):n1(i)+3) = [ -kas(i) , 1./x2(i), 0, 0 ];\n J(n2(i),n1(i):n1(i)+3) = [ -kaf(i).*x2(i), -x1(i)./x2(i), ...\n x2(i)./(tau0(i).*x3(i)), ...\n x2(i).*(ff(i)+dffdx(i))./(tau0(i).*x4(i))];\n end\n J(n3(i),n1(i):n1(i)+3) = [ 0, 0,...\n -f(n3(i)) - dfvdx(i)./(tau0(i).*x3(i)) , ...\n (fv(i)-dfvdx(i))./(tau0(i).*x3(i))];\n J(n4(i),n1(i):n1(i)+3) = [ 0, 0, 0, ...\n -(x2(i).*ff(i))./(tau0(i).*x4(i)) ];\n \n \n if isfield(in,'linearized') && in.linearized\n \n tmp = log(1-E0(i))./E0(i);\n \n dfdp(ind1(i),n1(i):n1(i)+3) = [0,0,0,...\n -dsdp(i).*(1+tmp).*Xt(n2(i))./(tau0(i).*E0(i))];\n dfdp(ind2(i),n1(i):n1(i)+3) = [0,0,...\n (-Xt(n2(i))+Xt(n3(i))./alpha(i))./tau0(i),...\n -((ff(i)+dffdx(i)).*Xt(n2(i)) + (fv(i)-dfvdx(i)).*Xt(n3(i)) ...\n - ff(i).*Xt(n4(i)))./tau0(i)];\n dfdp(ind3(i),n1(i):n1(i)+3) = kaf(i).*[-Xt(n2(i)),0,0,0];\n dfdp(ind4(i),n1(i):n1(i)+3) = kas(i).*[-Xt(n1(i)),0,0,0];\n \n if isfield(in,'fullDCM') && in.fullDCM\n if ~isempty(n5)\n J(n5(i),n1(i)) = epsilon;\n end\n dfdp(in.ind5(i),n1(i):n1(i)+3) = [0,0,...\n Xt(n3(i))./(tau0(i).*alpha(i)),...\n Xt(n3(i))./(tau0(i).*alpha(i))];\n else\n dfdp(5,:) = epsilon.*[ut,0,0,0];\n dfdp(6,:) = [0,0,...\n Xt(n3(i))./(tau0(i).*alpha(i)),...\n Xt(n3(i))./(tau0(i).*alpha(i))];\n end\n \n else\n \n % gradient wrt parameters\n dfdp(ind1(i),n1(i):n1(i)+3) = [0,0,0,...\n (((1-E0(i)).^(-1+1./x2(i)))-x2(i).*ff(i))...\n .*dsdp(i)./(tau0(i).*x4(i).*E0(i))];\n dfdp(ind2(i),n1(i):n1(i)+3) = [0,0,...\n -(x2(i) - fv(i))./(tau0(i).*x3(i)),...\n -(x2(i).*ff(i)./x4(i) - fv(i)./x3(i))./tau0(i)];\n dfdp(ind3(i),n1(i):n1(i)+3) = kaf(i).*[-x2(i)+1,0,0,0];\n dfdp(ind4(i),n1(i):n1(i)+3) = kas(i).*[-x1(i),0,0,0];\n \n % complement gradients if used for full DCM model\n if isfield(in,'fullDCM') && in.fullDCM\n if ~isempty(n5)\n J(n5(i),n1(i)) = epsilon;\n end\n dfdp(in.ind5(i),n1(i):n1(i)+3) = [0,0,...\n log(x3(i)).*fv(i)./(tau0(i).*x3(i).*alpha(i)),...\n log(x3(i)).*fv(i)./(tau0(i).*x3(i).*alpha(i))];\n else\n dfdp(5,:) = epsilon.*[ut,0,0,0];\n dfdp(6,:) = [0,0,...\n log(x3).*fv./(tau0.*x3.*alpha),...\n log(x3).*fv./(tau0.*x3.*alpha)];\n end\n \n end\n \nend\n\n% Apply Euler discretization\nif isfield(in,'linearized') && in.linearized\n if isfield(in,'fullDCM') && in.fullDCM && ~isempty(n5)\n Cu = 0;\n else \n Cu = zeros(n,1);\n Cu(n1) = epsilon.*ut;\n end\n fx = Xt + deltat.*(J'*Xt + Cu);\nelse\n fx = Xt + deltat.*f;\nend\ndfdp = deltat.*dfdp;\ndfdx = eye(n) + deltat.*J;\n\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/f_HRF2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.38229675209645364}}
{"text": "function [ eigenvalues, kpoints, nelect ] = import_eigenval( filename )\n%IMPORT_EIGENVAL Import a VASP EIGENVAL file.\n% [eigenvalues,kpoints,nelect] = IMPORT_EIGENVAL(filename) imports a VASP\n% EIGENVAL file. Optional parameter filename specifies the name of the \n% file. eigenvalues is a NKPOINTS x NBANDS x ISPIN array of eigenvalues,\n% kpoints is a NKPOINTS x 4 array of k-point coordinates and weights, and\n% nelect is the number of electrons.\n\n% todo:\n% check compatibility with non-spin-polarized files\n\n if nargin == 0\n filename='EIGENVAL';\n end\n \n fid = fopen(filename);\n if fid==-1\n error(['File ' filename ' not found']); \n end\n \n buffer = fscanf(fid, '%d', 4); % various data\n ispin = buffer(4); % 1 = non-polarized, 2 = polarized\n fgetl(fid); % empty string\n fgetl(fid); % various data\n fgetl(fid); % various data\n fgetl(fid); % various data\n fgetl(fid); % comment\n nelect = fscanf(fid, '%d', 1); % number of electrons\n nkpoints = fscanf(fid, '%d', 1); % number of k-points\n nbands = fscanf(fid, '%d', 1); % number of bands\n\n fgetl(fid); % empty string\n \n kpoints = zeros(nkpoints,4);\n eigenvalues = zeros(nkpoints, nbands, ispin);\n \n for kpoint = 1:nkpoints\n fgetl(fid); % blank line\n kpoints(kpoint,:) = fscanf(fid, '%f', 4)';\n fgetl(fid); % empty string\n for band = 1:nbands\n buffer = fscanf(fid,'%f',ispin+1);\n eigenvalues(kpoint,band,1:ispin) = buffer(2:(ispin+1));\n fgetl(fid); % empty string\n end\n end\n \n eigenvalues = sort(eigenvalues,2); % sort the bands by energy\n \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36836-vasplab/vasplab/import_eigenval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.38223607393474995}}
{"text": "function [mpe, ll] = calc_mpe_bucket(bnet, new_evidence, max_over)\n%\n% PURPOSE:\n% CALC_MPE Computes the most probable explanation to the network nodes\n% given the evidence.\n% \n% [mpe, ll] = calc_mpe(engine, new_evidence, max_over)\n%\n% INPUT:\n% bnet - the bayesian network\n% new_evidence - optional, if specified - evidence to be incorporated [cell(1,n)]\n% max_over - optional, if specified determines the variable elimination order [1:n]\n%\n% OUTPUT:\n% mpe - the MPE assignmet for the net variables (or [] if no satisfying assignment)\n% ll - log assignment probability.\n%\n% Notes:\n% 1. Adapted from '@var_elim_inf_engine\\marginal_nodes' for MPE by Ron Zohar, 8/7/01\n% 2. Only discrete potentials are supported at this time.\n% 3. Complexity: O(nw*) where n is the number of nodes and w* is the induced tree width.\n% 4. Implementation based on:\n% - R. Dechter, \"Bucket Elimination: A Unifying Framework for Probabilistic Inference\", \n% UA1 96, pp. 211-219.\n\n\nns = bnet.node_sizes;\nn = length(bnet.dag);\nevidence = cell(1,n);\nif (nargin<2)\n new_evidence = evidence;\nend\n\nonodes = find(~isemptycell(new_evidence)); % observed nodes\nhnodes = find(isemptycell(new_evidence)); % hidden nodes\npot_type = determine_pot_type(bnet, onodes);\n\nif pot_type ~= 'd'\n error('only disrete potentials supported at this time') \nend\n\nfor i=1:n\n fam = family(bnet.dag, i);\n CPT{i} = convert_to_pot(bnet.CPD{bnet.equiv_class(i)}, pot_type, fam(:), evidence); \nend \n\n% handle observed nodes: set impossible cases' probability to zero\n% rather than prun matrix (this makes backtracking easier)\n\nfor ii=onodes\n lIdx = 1:ns(ii);\n lIdx = setdiff(lIdx, new_evidence{ii});\n \n sCPT=struct(CPT{ii}); % violate object privacy\n \n sargs = '';\n for jj=1:(length(sCPT.domain)-1)\n sargs = [sargs, ':,']; \n end \n for jj=lIdx\n eval(['sCPT.T(', sargs, num2str(jj), ')=0;']);\n end\n CPT{ii}=dpot(sCPT.domain, sCPT.sizes, sCPT.T); \nend\n\nB = cell(1,n); \nfor b=1:n\n B{b} = mk_initial_pot(pot_type, [], [], [], []);\nend\n\nif (nargin<3)\n max_over = (1:n);\nend \norder = max_over; % no attempt to optimize this\n\n\n% Initialize the buckets with the CPDs assigned to them\nfor i=1:n\n b = bucket_num(domain_pot(CPT{i}), order);\n B{b} = multiply_pots(B{b}, CPT{i});\nend\n\n% Do backward phase\nmax_over = max_over(length(max_over):-1:1); % reverse\nfor i=max_over(1:end-1) \n % max-ing over variable i which occurs in bucket j\n j = bucket_num(i, order);\n rest = mysetdiff(domain_pot(B{j}), i);\n %temp = marginalize_pot_max(B{j}, rest);\n temp = marginalize_pot(B{j}, rest, 1);\n b = bucket_num(domain_pot(temp), order);\n % fprintf('maxing over bucket %d (var %d), putting result into bucket %d\\n', j, i, b);\n sB=struct(B{b}); % violate object privacy\n if ~isempty(sB.domain)\n B{b} = multiply_pots(B{b}, temp);\n else\n B{b} = temp;\n end\nend\nresult = B{1};\nmarginal = pot_to_marginal(result);\n[prob, mpe] = max(marginal.T);\n\n% handle impossible cases\nif ~(prob>0)\n mpe = []; \n ll = -inf;\n %warning('evidence has zero probability')\n return\nend\n\nll = log(prob);\n\n% Do forward phase \nfor ii=2:n\n marginal = pot_to_marginal(B{ii});\n mpeidx = [];\n for jj=order(1:length(mpe))\n assert(ismember(jj, marginal.domain)) %%% bug\n temp = find_equiv_posns(jj, marginal.domain);\n mpeidx = [mpeidx, temp] ;\n if isempty(temp)\n mpeidx = [mpeidx, Inf] ;\n end\n end\n [mpeidxsorted sortedtompe] = sort(mpeidx) ;\n \n % maximize the matrix obtained from assigning values from previous buckets.\n % this is done by building a string and using eval.\n \n kk=1;\n sargs = '(';\n for jj=1:length(marginal.domain)\n if (jj~=1)\n sargs = [sargs, ','];\n end\n if (mpeidxsorted(kk)==jj)\n sargs = [sargs, num2str(mpe(sortedtompe(kk)))];\n if (kk2057 and find the actual\n%epoch year.\nif (epochYear < 57)\n year=epochYear+2000;\nelse\n year=epochYear+1900;\nend\n%Convert into a two-part Julian date in TT.\n[month,dayOfMonth]=dayOfYear2MonthDay(year,fix(epochDays));\ndayFrac=epochDays-fix(epochDays);\n[hour,minute,second]=fracDayOfMonth2HourMinSec(year,month,dayOfMonth,dayFrac);\n[TTEpoch1,TTEpoch2]=Cal2TT(year,month,dayOfMonth,hour,minute,second);\n\nSGP4Elements=zeros(7,1);\nSGP4Elements(1)=eccentricity;\nSGP4Elements(2)=inclination;\nSGP4Elements(3)=argumentOfPerigee;\nSGP4Elements(4)=RAAscendingNode;\nSGP4Elements(5)=meanAnomaly;\nSGP4Elements(6)=meanMotion;\nSGP4Elements(7)=BSTARDrag;\nend\n\nfunction isValid=validateTLEChecksum(theTLELine)\n%The validation comes from the explanation of how the checksum is formed\n%from http://www.celestrak.com/NORAD/elements/ It is the last digit of the\n%sum of all of the digits in the string plus an extra 1 for each '-'. \n theSum=0;\n for curCharIdx=1:68\n curChar=theTLELine(curCharIdx);\n if(curChar=='-')\n theSum=theSum+1;\n elseif(curChar>='0'&&curChar<='9')\n theSum=theSum+str2double(curChar);\n end\n end\n\n %Get the last digit of the sum.\n sumStr=num2str(theSum);\n isValid=(sumStr(end)==theTLELine(69));\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Astronomical_Code/TLE2SGP4OrbEls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3818809126870243}}
{"text": "function [mustUU, pos_mustUU, mustUU_linear, pos_mustUU_linear] = findMustUUWithGAMS(model, minFluxesW, maxFluxesW, constrOpt, excludedRxns, mustSetFirstOrder, solverName, runID, outputFolder, outputFileName, printExcel, printText, printReport, keepInputs, keepGamsOutputs, verbose)\n% This function runs the second step of `optForce`, that is to solve a\n% bilevel mixed integer linear programming problem to find a second order\n% `MustUU` set.\n%\n% USAGE:\n%\n% [mustUU, pos_mustUU, mustUU_linear, pos_mustUU_linear] = findMustUUWithGAMS(model, minFluxesW, maxFluxesW, varargin)\n%\n% INPUTS:\n% model: (structure) a metabolic model with at\n% least the following fields:\n%\n% * .rxns - Reaction IDs in the model\n% * .mets - Metabolite IDs in the model\n% * .S - Stoichiometric matrix (sparse)\n% * .b - RHS of `Sv = b` (usually zeros)\n% * .c - Objective coefficients\n% * .lb - Lower bounds for fluxes\n% * .ub - Upper bounds for fluxes\n% minFluxesW: (double array of size `n_rxns x 1`) minimum\n% fluxes for each reaction in the model for\n% wild-type strain. This can be obtained by\n% running the function `FVAOptForce`. E.g.:\n% `minFluxesW = [-90; -56];`\n% maxFluxesW: (double array of size `n_rxns x 1`) maximum\n% fluxes for each reaction in the model for\n% wild-type strain. This can be obtained by\n% running the function `FVAOptForce`. E.g.:\n% `maxFluxesW = [90; 56];`\n%\n% OPTIONAL INPUTS:\n% constrOpt: (Structure) structure containing\n% additional contraints. Include here only\n% reactions whose flux is fixed, i.e.,\n% reactions whose lower and upper bounds\n% have the same value. Do not include here\n% reactions whose lower and upper bounds\n% have different values. Such contraints\n% should be defined in the lower and upper\n% bounds of the model. The structure has the\n% following fields:\n%\n% * .rxnList - Reaction list (cell array)\n% * .values - Values for constrained\n% reactions (double array)\n% E.g.: `struct('rxnList', {{'EX_gluc', 'R75', 'EX_suc'}}, 'values', [-100, 0, 155.5]');`\n% excludedRxns: (cell array) Reactions to be excluded to\n% the `MustUU` set. This could be used to\n% avoid finding transporters or exchange\n% reactions in the set. Default = empty.\n% mustSetFirstOrder: (cell array) Reactions that belong to\n% `MustU` and `MustL` (first order sets).\n% Default = empty.\n% solverName: (string) Name of the solver used in\n% GAMS. Default = 'cplex'.\n% runID: (string) ID for identifying this run.\n% Default = ['run' date hour].\n% outputFolder: (string) name for folder in which\n% results will be stored. Default =\n% 'OutputsFindMustUU'.\n% outputFileName: (string) name for files in which\n% results. will be stored Default =\n% 'MustUUSet'.\n% printExcel: (double) boolean to describe wheter\n% data must be printed in an excel file or\n% not. Default = 1\n% printText: (double) boolean to describe wheter\n% data must be printed in an plaint text\n% file or not. Default = 1\n% printReport: (double) 1 to generate a report in a\n% plain text file. 0 otherwise. Default = 1\n% keepInputs: (double) 1 to mantain folder with\n% inputs to run `findMustUU.gms`. 0 otherwise.\n% Default = 1\n% keepGamsOutputs: (double) 1 to mantain files returned by\n% `findMustUU.gms`. 0 otherwise. Default = 1\n% verbose: (double) 1 to print results in console.\n% 0 otherwise. Default = 0\n%\n% OUTPUTS:\n% mustUU: (cell array of size number of sets found X\n% 2) Cell array containing the reactions IDs\n% which belong to the `MustUU` set. Each row\n% contain a couple of reactions that must\n% decrease their flux.\n% pos_mustUU: (double array of size number of sets found\n% X 2) double array containing the positions\n% of each reaction in `mustUU` with regard to\n% `model.rxns`\n% mustUU_linear: (cell array of size number of unique\n% reactions found X 1) Cell array containing\n% the unique reactions ID which belong to\n% the `MustUU` Set\n% pos_mustUU_linear: (double array of size number of unique\n% reactions found X 1) double array\n% containing positions for reactions in\n% `mustUU_linear`. with regard to `model.rxns`\n% outputFileName.xls: (file) File containing one column\n% array with identifiers for reactions in\n% MustUU. This file will only be generated\n% if the user entered `printExcel = 1`. Note\n% that the user can choose the name of this\n% file entering the input `outputFileName = 'PutYourOwnFileNameHere';`\n% outputFileName.txt: (file) File containing one column\n% array with identifiers for reactions in\n% MustUU. This file will only be generated\n% if the user entered `printText = 1`. Note\n% that the user can choose the name of this\n% file entering the input `outputFileName = 'PutYourOwnFileNameHere';`\n% outputFileName_Info.xls: (file) File containing one column\n% array. In each row the user will find a\n% couple of reactions. Each couple of\n% reaction was found in one iteration of\n% `FindMustUU.gms`. This file will only be\n% generated if the user entered `printExcel = 1`.\n% Note that the user can choose the name\n% of this file entering the input\n% `outputFileName = 'PutYourOwnFileNameHere';`\n% outputFileName_Info.txt: (file) File containing one column\n% array. In each row the user will find a\n% couple of reactions. Each couple of\n% reaction was found in one iteration of\n% `FindMustUU.gms`. This file will only be\n% generated if the user entered `printText = 1`.\n% Note that the user can choose the name\n% of this file entering the input\n% `outputFileName = 'PutYourOwnFileNameHere';`\n% findMustUU.lst: (file) file autogenerated by GAMS. It\n% contains information about equations,\n% variables, parameters as well as\n% information about the running (values at\n% each iteration). This file only will be\n% saved in the output folder is the user\n% entered `keepGamsOutputs = 1`\n% GtoMUU.gdx: (file) file containing values for\n% variables, parameters, etc. which were\n% found by GAMS when solving `findMustUU.gms`.\n% This file only will be saved in the output\n% folder is the user entered `keepInputs = 1`\n%\n% NOTE:\n%\n% This function is based in the GAMS files written by Sridhar\n% Ranganathan which were provided by the research group of Costas D.\n% Maranas. For a detailed description of the `optForce` procedure, please\n% see: `Ranganathan S, Suthers PF, Maranas CD (2010) OptForce: An\n% Optimization Procedure for Identifying All Genetic Manipulations\n% Leading to Targeted Overproductions. PLOS Computational Biology 6(4):\n% e1000744`. https://doi.org/10.1371/journal.pcbi.1000744\n%\n% .. Author: - Sebastian Mendoza, May 30th 2017, Center for Mathematical Modeling, University of Chile, snmendoz@uc.cl\n\noptionalParameters = {'constrOpt', 'excludedRxns', 'mustSetFirstOrder', 'solverName', 'runID', 'outputFolder', 'outputFileName', ...\n 'printExcel', 'printText', 'printReport', 'keepInputs', 'keepGamsOutputs', 'verbose'};\n\nif (numel(varargin) > 0 && (~ischar(varargin{1}) || ~any(ismember(varargin{1},optionalParameters))))\n\n tempargin = cell(1,2*(numel(varargin)));\n for i = 1:numel(varargin)\n\n tempargin{2*(i-1)+1} = optionalParameters{i};\n tempargin{2*(i-1)+2} = varargin{i};\n end\n varargin = tempargin;\n\nend\n\nparser = inputParser();\nparser.addRequired('model', @(x) isstruct(x) && isfield(x, 'S') && isfield(model, 'rxns')...\n && isfield(model, 'mets') && isfield(model, 'lb') && isfield(model, 'ub') && isfield(model, 'b')...\n && isfield(model, 'c'))\nparser.addRequired('minFluxesW', @isnumeric)\nparser.addRequired('maxFluxesW', @isnumeric)\nparser.addParamValue('constrOpt', struct('rxnList', {{}}, 'values', []),@ (x) isstruct(x) && isfield(x, 'rxnList') && isfield(x, 'values') ...\n && length(x.rxnList) == length(x.values) && length(intersect(x.rxnList, model.rxns)) == length(x.rxnList))\nparser.addParamValue('excludedRxns', {}, @(x) iscell(x) && length(intersect(x, model.rxns)) == length(x))\nparser.addParamValue('mustSetFirstOrder', {}, @(x) iscell(x) && length(intersect(x, model.rxns)) == length(x))\nsolvers = checkGAMSSolvers('MIP');\nif isempty(solvers)\n error('there is no GAMS solvers available to solve Mixed Integer Programming problems') ;\nelse\n if ismember('cplex', lower(solvers))\n defaultSolverName = 'cplex';\n else\n defaultSolverName = lower(solvers(1));\n end\nend\n\nparser.addParamValue('solverName', defaultSolverName, @(x) ischar(x))\nhour = clock; defaultRunID = ['run-' date '-' num2str(hour(4)) 'h' '-' num2str(hour(5)) 'm'];\nparser.addParamValue('runID', defaultRunID, @(x) ischar(x))\nparser.addParamValue('outputFolder', 'OutputsFindMustUU', @(x) ischar(x))\nparser.addParamValue('outputFileName', 'MustUUSet', @(x) ischar(x))\nparser.addParamValue('printExcel', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('printText', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('printReport', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('keepInputs', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('keepGamsOutputs', 1, @(x) isnumeric(x) || islogical(x));\nparser.addParamValue('verbose', 1, @(x) isnumeric(x) || islogical(x));\n\nparser.parse(model, minFluxesW, maxFluxesW, varargin{:})\nmodel = parser.Results.model;\nminFluxesW = parser.Results.minFluxesW;\nmaxFluxesW = parser.Results.maxFluxesW;\nconstrOpt= parser.Results.constrOpt;\nexcludedRxns= parser.Results.excludedRxns;\nmustSetFirstOrder = parser.Results.mustSetFirstOrder;\nsolverName = parser.Results.solverName;\nrunID = parser.Results.runID;\noutputFolder = parser.Results.outputFolder;\noutputFileName = parser.Results.outputFileName;\nprintExcel = parser.Results.printExcel;\nprintText = parser.Results.printText;\nprintReport = parser.Results.printReport;\nkeepInputs = parser.Results.keepInputs;\nkeepGamsOutputs = parser.Results.keepGamsOutputs;\nverbose = parser.Results.verbose;\n\n% correct size of constrOpt\nif ~isempty(constrOpt.rxnList)\n if size(constrOpt.rxnList, 1) > size(constrOpt.rxnList,2); constrOpt.rxnList = constrOpt.rxnList'; end;\n if size(constrOpt.values, 1) > size(constrOpt.values,2); constrOpt.values = constrOpt.values'; end;\nend\n\n% first, verify that GAMS is installed in your system\ngamsPath = which('gams');\nif isempty(gamsPath); error('OptForce: GAMS is not installed in your system. Please install GAMS.'); end;\n\n%name of the function to solve the optimization problem in GAMS\ngamsMustUUFunction = 'findMustUU.gms';\n%path of that function\npathGamsFunction = which(gamsMustUUFunction);\nif isempty(pathGamsFunction); error(['OptForce: ' gamsMustUUFunction ' not in MATLAB path.']); end;\n%current path\nworkingPath = pwd;\n%go to the path associate to the ID for this run.\nif ~isdir(runID); mkdir(runID); end; cd(runID);\n\n% if the user wants to generate a report.\nif printReport\n %create name for file.\n hour = clock;\n reportFileName = ['report-' date '-' num2str(hour(4)) 'h' '-' num2str(hour(5)) 'm.txt'];\n freport = fopen(reportFileName, 'w');\n reportClosed = 0;\n % print date of running.\n fprintf(freport, ['findMustUUWithGAMS.m executed on ' date ' at ' num2str(hour(4)) ':' num2str(hour(5)) '\\n\\n']);\n % print matlab version.\n fprintf(freport, ['MATLAB: Release R' version('-release') '\\n']);\n % print gams version.\n fprintf(freport, ['GAMS: ' regexprep(gamsPath, '\\\\', '\\\\\\') '\\n']);\n % print solver used in GAMS to solve optForce.\n fprintf(freport, ['GAMS solver: ' solverName '\\n']);\n\n %print each of the inputs used in this running.\n fprintf(freport, '\\nThe following inputs were used to run OptForce: \\n');\n fprintf(freport, '\\n------INPUTS------\\n');\n %print model.\n fprintf(freport, '\\nModel:\\n');\n for i = 1:length(model.rxns)\n rxn = printRxnFormula(model, model.rxns{i}, false);\n fprintf(freport, [model.rxns{i} ': ' rxn{1} '\\n']);\n end\n %print lower and upper bounds, minimum and maximum values for each of\n %the reactions in wild-type and mutant strain\n fprintf(freport, '\\nLB\\tUB\\tMin_WT\\tMax_WT\\n');\n for i = 1:length(model.rxns)\n fprintf(freport, '%6.4f\\t%6.4f\\t%6.4f\\t%6.4f\\n', model.lb(i), model.ub(i), minFluxesW(i), maxFluxesW(i));\n end\n\n %print constraints\n fprintf(freport,'\\nConstrained reactions:\\n');\n for i = 1:length(constrOpt.rxnList)\n fprintf(freport,'%s: fixed in %6.4f\\n',constrOpt.rxnList{i},constrOpt.values(i));\n end\n\n fprintf(freport, '\\nExcluded Reactions:\\n');\n for i = 1:length(excludedRxns)\n rxn = printRxnFormula(model, excludedRxns{i}, false);\n fprintf(freport, [excludedRxns{i} ': ' rxn{1} '\\n']);\n end\n\n fprintf(freport, '\\nReactions from first order sets(MustU and MustL):\\n');\n for i = 1:length(mustSetFirstOrder)\n rxn = printRxnFormula(model, mustSetFirstOrder{i}, false);\n fprintf(freport, [mustSetFirstOrder{i} ': ' rxn{1} '\\n']);\n end\n\n fprintf(freport,'\\nrunID(Main Folder): %s \\n\\noutputFolder: %s \\n\\noutputFileName: %s \\n',...\n runID, outputFolder, outputFileName);\n\n\n fprintf(freport,'\\nprintExcel: %1.0f \\n\\nprintText: %1.0f \\n\\nprintReport: %1.0f \\n\\nkeepInputs: %1.0f \\n\\nkeepGamsOutputs: %1.0f \\n\\nverbose: %1.0f \\n',...\n printExcel,printText,printReport,keepInputs,keepGamsOutputs,verbose);\n\nend\n\ncopyfile(pathGamsFunction);\n\n% export inputs for running the optimization problem in GAMS to find the\n% MustUU Set\ninputFolder = 'InputsMustUU';\nexportInputsMustOrder2ToGAMS(model, 'UU', minFluxesW, maxFluxesW, constrOpt, excludedRxns, mustSetFirstOrder, inputFolder)\n\n% create a directory to save results if this don't exist\nif ~exist(outputFolder, 'dir')\n mkdir(outputFolder);\nend\n\n%run\nif verbose\n run = system(['gams ' gamsMustUUFunction ' lo=3 --myroot=' inputFolder '/ --solverName=' solverName ' gdx=GtoMUU']);\nelse\n run=system(['gams ' gamsMustUUFunction ' --myroot=' inputFolder '/ --solverName=' solverName ' gdx=GtoMUU']);\nend\n\nif printReport; fprintf(freport, '\\n------RESULTS------\\n'); end;\n\n%if user decide not to show inputs files for findMustUU.gms\nif ~keepInputs; rmdir(inputFolder,'s'); end;\n\n%if findMustUU.gms was executed correctly \"run\" should be 0\nif run == 0\n\n if printReport; fprintf(freport,'\\nGAMS was executed correctly\\n'); end;\n if verbose; fprintf('GAMS was executed correctly\\nSummary of information exported by GAMS:\\n'); end;\n %show GAMS report in MATLAB console\n if verbose; gdxWhos GtoMUU; end;\n try\n findMustUU.name = 'findMustUU';\n rgdx('GtoMUU',findMustUU); %if do not exist the variable findMustUU in GtoMUU, an error will ocurr.\n if printReport; fprintf(freport,'\\nGAMS variables were read by MATLAB correctly\\n'); end;\n if verbose; fprintf('GAMS variables were read by MATLAB correctly\\n'); end;\n\n %Using GDXMRW to read solutions found by findMustUU.gms\n %extract matrix 1 found by findMustII.gms. This matrix contains the\n %first reaction in each couple of reactions\n m1.name = 'matrix1';\n m1.compress = 'true';\n m1 = rgdx('GtoMUU',m1);\n uels_m1 = m1.uels{2};\n\n\n if ~isempty(uels_m1)\n %if the uel array for m1 is not empty, at least 1 couple of reations was found.\n if printReport; fprintf(freport,'\\na MustUU set was found\\n'); end;\n if verbose; fprintf('a MustUU set was found\\n'); end;\n\n %find values for matrix 1\n val_m1 = m1.val;\n m1_full = full(sparse(val_m1(:,1),val_m1(:,2:end-1),val_m1(:,3)));\n\n %find values for matrix 2\n m2.name = 'matrix2';\n m2.compress = 'true';\n m2 = rgdx('GtoMUU',m2);\n uels_m2 = m2.uels{2};\n val_m2 = m2.val;\n m2_full = full(sparse(val_m2(:,1),val_m2(:,2:end-1),val_m2(:,3)));\n\n %initialize empty array for storing\n n_mustSet = size(m1_full,1);\n mustUU = cell(n_mustSet,2);\n pos_mustUU = zeros(size(mustUU));\n mustUU_linear = {};\n\n %write each couple of reactions.\n for i = 1:n_mustSet\n rxn1 = uels_m1(m1_full(i,:) == 1);\n rxn2 = uels_m2(m2_full(i,:) == 1);\n mustUU(i,1) = rxn1;\n mustUU(i,2) = rxn2;\n pos_mustUU(i,1) = find(strcmp(model.rxns,rxn1));\n pos_mustUU(i,2) = find(strcmp(model.rxns,rxn2));\n mustUU_linear = union(mustUU_linear,[rxn1;rxn2]);\n end\n pos_mustUU_linear = cell2mat(arrayfun(@(x)find(strcmp(x,model.rxns)),mustUU_linear,'UniformOutput', false))';\n else\n %if the uel array for m1 is empty, no couple of reations was found.\n if printReport; fprintf(freport,'\\na MustUU set was not found\\n'); end;\n if verbose; fprintf('a MustUU set was not found\\n'); end;\n\n %initialize arrays to be returned by this function\n mustUU = {};\n pos_mustUU = [];\n mustUU_linear = {};\n pos_mustUU_linear = [];\n end\n\n % print info into an excel file if required by the user\n if printExcel\n if ~isempty(uels_m1)\n currentFolder = pwd;\n cd(outputFolder);\n must = cell(size(mustUU,1),1);\n for i = 1:size(mustUU,1)\n must{i} = strjoin(mustUU(i,:),' or ');\n end\n xlswrite([outputFileName '_Info'],[{'Reactions'};must]);\n xlswrite(outputFileName,mustUU_linear);\n cd(currentFolder);\n if verbose\n fprintf(['MustUU set was printed in ' outputFileName '.xls \\n']);\n fprintf(['MustUU set was also printed in ' outputFileName '_Info.xls \\n']);\n end\n if printReport\n fprintf(freport,['\\nMustUU set was printed in ' outputFileName '.xls \\n']);\n fprintf(freport,['\\nMustUU set was printed in ' outputFileName '_Info.xls \\n']);\n end\n else\n if verbose; fprintf('No mustUU set was found. Therefore, no excel file was generated\\n'); end;\n if printReport; fprintf(freport, '\\nNo mustUU set was found. Therefore, no excel file was generated\\n'); end;\n end\n end\n\n % print info into a plain text file if required by the user\n if printText\n if ~isempty(uels_m1)\n currentFolder = pwd;\n cd(outputFolder);\n f = fopen([outputFileName '_Info.txt'],'w');\n fprintf(f,'Reactions\\n');\n for i = 1:size(mustUU,1)\n fprintf(f,'%s or %s\\n',mustUU{i,1},mustUU{i,2});\n end\n fclose(f);\n\n f = fopen([outputFileName '.txt'],'w');\n for i = 1:length(mustUU_linear)\n fprintf(f,'%s\\n',mustUU_linear{i});\n end\n fclose(f);\n\n cd(currentFolder);\n if verbose\n fprintf(['MustUU set was printed in ' outputFileName '.txt \\n']);\n fprintf(['MustUU set was also printed in ' outputFileName '_Info.txt \\n']);\n end\n if printReport\n fprintf(freport,['\\nMustUU set was printed in ' outputFileName '.txt \\n']);\n fprintf(freport,['\\nMustUU set was printed in ' outputFileName '_Info.txt \\n']);\n end\n\n else\n if verbose; fprintf('No mustUU set was found. Therefore, no plain text file was generated\\n'); end;\n if printReport; fprintf(freport, '\\nNo mustUU set was found. Therefore, no plain text file was generated\\n'); end;\n end\n end\n\n %close file for saving report\n if printReport; fclose(freport); reportClosed = 1; end;\n if printReport; movefile(reportFileName,outputFolder); end;\n delete(gamsMustUUFunction);\n\n %remove or move additional files that were generated during running\n if keepGamsOutputs\n if ~isdir(outputFolder); mkdir(outputFolder); end;\n movefile('GtoMUU.gdx',outputFolder);\n movefile(regexprep(gamsMustUUFunction,'gms','lst'),outputFolder);\n else\n delete('GtoMUU.gdx');\n delete(regexprep(gamsMustUUFunction,'gms','lst'));\n end\n\n %go back to the original path\n cd(workingPath);\n catch\n %GAMS variables were not read correctly by MATLAB\n if verbose; fprintf('GAMS variables were not read by MATLAB corretly\\n'); end;\n if printReport && ~reportClosed; fprintf(freport, '\\nGAMS variables were not read by MATLAB corretly\\n'); fclose(freport); end;\n cd(workingPath);\n error('OptForce: GAMS variables were not read by MATLAB corretly');\n\n end\n\n %if findMustUU.gms was not executed correctly \"run\" should be different from 0\nelse\n %if GAMS was not executed correcttly\n if printReport && ~reportClosed; fprintf(freport, '\\nGAMS was not executed correctly\\n'); fclose(freport); end;\n if verbose; fprintf('GAMS was not executed correctly\\n'); end;\n cd(workingPath);\n error('OptForce: GAMS was not executed correctly');\n\nend\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/design/optForceGAMS/findMustUUWithGAMS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.38185725967749634}}
{"text": "function [varargout]=cmaperise(varargin)\n\n% function [Cmapped,indMap]=cmaperise(C,cmap,clim)\n%-------------------------------------------------------------------------\n% This function creates RGB colors for the data C using the colormap cmap\n% and the limits clim. \n%\n%\n% Change log:\n% 2019/06/25 Added variable input handling\n%-------------------------------------------------------------------------\n\n%% Parse input \n\nswitch nargin\n case 1\n C=varargin{1};\n cmap=[];\n clim=[];\n case 2\n C=varargin{1};\n cmap=varargin{2};\n clim=[]; \n case 3\n C=varargin{1};\n cmap=varargin{2};\n clim=varargin{3};\nend\n\nif isempty(cmap)\n cmap=viridis(250);\nend\n\nif isempty(clim)\n clim=[min(C(:)) max(C(:))]; \n if diff(clim)1)=1;\n\np(isnan(p))=0; %Force nan data to 0\n\nIND_cmap=round((p*(size(cmap,1)-1))+1);\nCmapped=cmap(IND_cmap,:);\n\n%%\nvarargout{1}=Cmapped;\nif nargout==2\n varargout{2}=IND_cmap;\nend\n\nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/cmaperise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.3818183045785905}}
{"text": "% easy11 Creates a stereographic plot of GPS satellite orbits\n% from an epehemerides or almanac file. The plot is as\n% seen from the position (phi, lambda). All (parts of)\n% orbits with elevation angle lower than a given\n% cut-off angle (mask) are omitted.\n% As input we use the ephemerides in our basic RINEX\n% navigation file. It only contains nine ephemerides. The\n% result shows two windows with a considerable amount\n% of visible satellites. This is like the actual situation in the\n% early 1990es. Then you could have a window of about\n% one hour at say 5--6 am and this repeated 12 hours later.\n%\n% An additional plot is created showing number\n% of visible satellites and when they are visible.\n% Finally a stem plot depicts the number of\n% satelliets visible for how long\n%\n% Alternatively, if you want to include all GPS satellites,\n% we need an almanac file which can be downloaded from\n% http://www.navcen.uscg.gov/?pageName=gpsAlmanacs\n\n%Kai Borre 26-08-2008\n%Copyright (c) by Kai Borre\n%$Revision: 1.1 $ $Date: 2009/04/05 $\n% Total revision January 10, 2016\n\n% RINEX version 3.03\n\nset(0,'DefaultTextFontName','Times');\nset(0,'DefaultAxesFontName','Times');\nset(0,'DefaultTextFontSize',12);\n\n% If you want to use a RINEX ephemeris file uncomment\n% line 37 and comment line 41 out.\n\n% the following five assignments are mandatory\n%%rinexe('log_24h.15n','eph.dat');\n% in case you want to include all GPS satellites in the constellation,\n% we need an almanac. This is read and converted to the usual\n% eph format by the following call\nrinexa('current.alm','eph.dat');\n\nephemerides = 'eph.dat';\nmask = 10;\nphi = [57 12 43];\nlambda = [50 10 39];\n\n%reading ephemerides\nfide = fopen(ephemerides,'r');\nEph = fread(fide,inf,'double');\nm = length(Eph);\neph = reshape(Eph,21,m/21);\n\n% transformation of given location (phi,lambda,h) to (X,Y,Z)\nPhi = dms2rad(phi(1),phi(2),phi(3));\nPhi = Phi*180/pi;\nLambda = dms2rad(lambda(1),lambda(2),lambda(3));\nLambda = Lambda*180/pi;\n[M(1,1),M(2,1),M(3,1)] = frgeod(6378137,298.257222101,Phi,Lambda,0);\n\n% Computation of (azimuth, elevation) for each satellite\n% for each 15 min.s. We use only one ephemeris for each PRN.\n% Anyway, the plot is only for visual use\n[prns, ind] = unique(eph(1,:));\nsatrows = length(ind);\n az = ones(satrows,96)*inf; % satrows is number of PRN and 96 quaters of an hour in 24 hours\nel = ones(satrows,96)*inf;\n\nstart_time = max(eph(21,:));\nfor sat = ind'\n j = 0;\n for time = start_time:900:start_time+86400\n S = satpos(time,eph(:,sat)); %sat\n j = j+1;\n [azimuth,elevation,distance] = topocent(M,S-M);\n az(sat,j) = azimuth; % sat runs over PRN, j runs over sow\n el(sat,j) = elevation;\n end\nend\n% We assume that there are satrows PRNs\nXX = zeros(satrows,40)*inf; % a matrix of NaNs to store plot data\nYY = XX;\n\nfigure(1);\n% polarhg draws coordinate lines of a polar plot. We add\n% circles with radii 30 and 60 degrees\npolarhg([30 60])\nhold on\nfor k = ind' % 1:32\n % if az(k,1) == 0, break, end % continue\n AZ = az(k,:);\n EL = el(k,:);\n % remove data below the cut-off angle\n AZ(find(EL <= mask)) = nan;\n EL(find(EL <= mask)) = nan;\n % conversion from polar to rectangular coordinates\n xx = (90-EL).*cos(AZ*pi/180);\n yy = (90-EL).*sin(AZ*pi/180);\n XX(k,1:length(xx)) = xx;\n YY(k,1:length(yy)) = yy;\nend % k\n%the first coord. moves text vertically (increasing values up),\n% the second coord. moves text horizontally (increasing values right)\ntext(135,-95,{['Skyplot for the position (\\phi, \\lambda) = (' ...\n num2str(round(Phi)) '\\circ, ' num2str(round(Lambda)) '\\circ)']})\ntext(115,-45,{['Elevation mask ' num2str(mask) '\\circ' ]}) %120\ntext(-120,-120,['All PRNs except ' num2str(setdiff(1:32,prns)) ])\nplot(XX',YY','linewidth',2)\nhold off\nset(gca,'Fontsize',9);\n\nprint('easy111','-dpdf')\n\n\n% preparation for visibility plot %%%\n\n% we choose a resolution of 5 min.s,\n% ie. 24 hours times 12 = 288 which becomes the range of j\nsatsum = zeros(1,288);\nvisible = zeros(2*(size(prns,2)+1),288);\n\nfor sat = ind'\n %Az = [];\n %El = [];\n i = eph(1,sat);\n for j = 1:288\n time = 300*(j-1); % in s, 0