{"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 mask\n % Az = [Az az];\n % El = [El el];\n satsum(j) = satsum(j)+1;\n visible(2*i,j) = 1;\n end\n end\nend\n\nfigure(2);\nset(gca,'Fontsize',16);\narea(satsum)\nset(gca,'XTick',1:71:288)\nset(gca,'XTickLabel',{'0','6','12','18','24'})\nxlabel('GPS Time [hours]')\nylabel('# of Visible Satellites')\ntitle(['Elevation Mask ' num2str(mask) '\\circ'])\ncolormap summer\n\nprint -dpdf easy112\n\nfigure(3);\nset(gca,'Fontsize',16);\nimagesc(flipud(visible));\ncolormap(autumn(5))\nset(gca,'XTick',1:71:288)\nset(gca,'XTickLabel',{'0','6','12','18','24'})\nset(gca,'YTick',-3:16:(2*(size(prns,2)+1)))\nset(gca,'YTickLabel',{'2','8','16','24','32'});\nxlabel('GPS Time [hours]')\nylabel('PRNs')\ntitle('Yellow Lines Indicate Visible Satellites')\ncolormap winter\n\nprint -dpdf easy113\n\nfigure(4);\nset(gca,'Fontsize',16);\nan = sum(visible,1);\n% we assume the total # of PRNs always is between 1 and 20\ntotal = zeros(1,20);\nfor i = 1:288\n j = an(i);\n if j == 0, j = j+1; total(j) = 0.01; continue, end\n total(j) = total(j)+1;\nend\n% the adder total adds per 5 minutes, division by 12 changes to per hour\nbar(1:20,total/12); % 10-> 32\ntitle('Number of Visible Satellites')\nylabel('Hours')\n\nprint -dpdf easy114\n\n%%%%%%%%%%%%%%%%%%%%% end easy11.m %%%%%%%%%%%%%%\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/easy11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.38181170637377504}} {"text": "% MSH_EVALUATE_ELEMENT_LIST: evaluate the parameterization in a given list of elements.\n%\n% msh_elems = msh_evaluate_element_list (msh, elements)\n%\n% INPUTS:\n%\n% msh: mesh object (see msh_cartesian)\n% element_list: numbering of the elements where the evaluations are performed.\n%\n% OUTPUT:\n%\n% msh_elems: structure containing the quadrature rule in the given elements of the physical domain, which contains the following fields\n%\n% FIELD_NAME (SIZE) DESCRIPTION\n% npatch (scalar) number of patches\n% ndim (scalar) dimension of the parametric space\n% rdim (scalar) dimension of the physical space\n% nel (scalar) number of elements in the list\n% elem_list (1 x nel) numbering of the elements in the list\n% nqn (scalar) number of quadrature points per element (must be the same for every patch)\n% nqn_dir (1 x ndim) number of quadrature points in each direction (must be the same for every patch)\n% nel_per_patch (1 x npatch) number of selected elements on each patch\n% elem_list_of_patch (1 x npatch cell-array) selected elements on the patch, with local numbering\n% nel_dir_of_patch (1 x npatch cell-array) the total number of elements in each direction, for each patch\n% quad_weights, geo_map, geo_map_jac, deo_map_der2, jacdet, element_size (see msh_evaluate_col for details)\n%\n% The function only works if the number of quadrature points is the same for all the patches and all directions.\n%\n% Copyright (C) 2015 Rafael Vazquez\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\nfunction msh_col = msh_evaluate_element_list (msh, elem_list, varargin)\n\n elem_list = elem_list(:)';\n\n msh_col.npatch = msh.npatch;\n msh_col.ndim = msh.ndim;\n msh_col.rdim = msh.rdim;\n\n msh_col.nel = numel (elem_list);\n msh_col.elem_list = elem_list;\n\n if (isempty (elem_list)), return, end\n \n fields = {'quad_weights', 'geo_map', 'geo_map_jac', 'geo_map_der2', 'jacdet', 'element_size'};\n cat_position = [2 3 4 5 2 2];\n for ii = 1:numel (fields)\n msh_col.(fields{ii}) = [];\n end\n \n Nelem = cumsum ([0, msh.nel_per_patch]);\n \n indices = cell (1, msh.npatch);\n for iptc = 1:msh.npatch\n [~,indices{iptc},~] = intersect ((Nelem(iptc)+1):Nelem(iptc+1), elem_list);\n end\n active_patches = find (~cellfun (@isempty, indices));\n\n \n for iptc = active_patches\n msh_patch = msh_evaluate_element_list (msh.msh_patch{iptc}, indices{iptc});\n \n if (msh_patch.nqn_dir ~= msh.msh_patch{active_patches(1)}.nqn_dir)\n error ('msh_evaluate_element_list: for multipatch geometries, the number of quadrature points should be the same on each patch')\n end\n\n for ii = 1:numel (fields)\n if (isfield (msh_patch, fields{ii}))\n msh_col.(fields{ii}) = cat (cat_position(ii), msh_col.(fields{ii}), msh_patch.(fields{ii}));\n end\n end\n end\n \n msh_col.nel_per_patch = cellfun (@numel, indices);\n msh_col.elem_list_of_patch = indices;\n msh_col.nel_dir_of_patch = cell (1, msh.npatch);\n for iptc = 1:msh.npatch\n msh_col.nel_dir_of_patch{iptc} = msh.msh_patch{iptc}.nel_dir;\n end\n msh_col.nqn = msh.msh_patch{active_patches(1)}.nqn;\n msh_col.nqn_dir = msh.msh_patch{active_patches(1)}.nqn_dir;\n\nend", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/multipatch/@msh_multipatch/msh_evaluate_element_list.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3817316696439569}} {"text": "function varargout = sound_field_mono_wfs(X,Y,Z,xs,src,f,conf)\n%SOUND_FIELD_MONO_WFS sound field for WFS\n%\n% Usage: [P,x,y,z,x0] = sound_field_mono_wfs(X,Y,Z,xs,src,f,conf)\n%\n% Input parameters:\n% X - x-axis / m; single value or [xmin,xmax] or nD-array\n% Y - y-axis / m; single value or [ymin,ymax] or nD-array\n% Z - z-axis / m; single value or [zmin,zmax] or nD-array\n% xs - position of virtual source / m\n% src - source type of the virtual source\n% 'pw' - plane wave (xs is the direction of the\n% plane wave in this case)\n% 'ps' - point source\n% 'fs' - focused source\n% f - monochromatic frequency / Hz\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% P - simulated sound field\n% x - corresponding x values / m\n% y - corresponding y values / m\n% z - corresponding z values / m\n% x0 - active secondary sources / m\n%\n% SOUND_FIELD_MONO_WFS(X,Y,Z,xs,src,f,conf) simulates a monochromatic sound\n% field for the given source type (src) synthesized with wave field synthesis\n% for the frequency f.\n%\n% To plot the result use:\n% plot_sound_field(P,X,Y,Z,x0,conf);\n% or simple call the function without output argument:\n% sound_field_mono_wfs(X,Y,Z,xs,src,f,conf)\n%\n% See also: plot_sound_field, sound_field_imp_wfs, driving_function_mono_wfs\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 7;\nnargmax = 7;\nnarginchk(nargmin,nargmax);\nisargxs(xs);\nisargpositivescalar(f);\nisargchar(src);\nisargstruct(conf);\n\n\n%% ===== Configuration ==================================================\nif strcmp('2D',conf.dimension)\n greens_function = 'ls';\nelse\n greens_function = 'ps';\nend\n\n\n%% ===== Computation ====================================================\n% Get the position of the loudspeakers and its activity\nx0 = secondary_source_positions(conf);\nx0 = secondary_source_selection(x0,xs,src);\nx0 = secondary_source_tapering(x0,conf);\n% Driving function\nD = driving_function_mono_wfs(x0,xs,src,f,conf);\n% Wave field\n[varargout{1:min(nargout,4)}] = ...\n sound_field_mono(X,Y,Z,x0,greens_function,D,f,conf);\n% Return secondary sources if desired\nif nargout==5, varargout{5}=x0; end\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_monochromatic/sound_field_mono_wfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.38165818377423877}} {"text": "function [y,z]=amen_sum(X, c, tol, varargin)\n%Approximate the linear combination of TT tensors via the AMEn iteration\n% [y,z]=amen_sum(X, v, tol, varargin)\n% Attempts to approximate the y(j) = sum_i X{i}*c(i,j)\n% with accuracy TOL using the AMEn+ALS iteration.\n%\n% 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 y0 - initial approximation to y [rand rank-2]\n% o nswp - maximal number of sweeps [20]\n% o verb - verbosity level, 0-silent, 1-sweep info, 2-block info [1]\n% o kickrank - compression rank of the error, \n% i.e. enrichment size [3]\n% o init_qr - perform QR of the input (save some time in ts, etc) [true]\n% o renorm - Orthog. and truncation methods: direct (svd,qr) or gram\n% (apply svd to the gram matrix, faster for m>>n) [direct]\n% o fkick - Perform solution enrichment during forward sweeps [false]\n% (rather questionable yet; false makes error higher, but \"better\n% structured\": it does not explode in e.g. subsequent matvecs)\n% o z0 - initial approximation to the error Ax-y [rand rank-kickrank]\n% o can - whether the input is in CP format [false]\n% o multrank - shall we try to grow ranks multiplicatively by adding\n% the previous iterand [false]\n%\n%\n%********\n% For description of adaptive ALS please see\n% Sergey V. Dolgov, Dmitry V. Savostyanov,\n% Alternating minimal energy methods for linear systems in higher dimensions. \n% Part I: SPD systems, http://arxiv.org/abs/1301.6068,\n% Part II: Faster algorithm and application to nonsymmetric systems, http://arxiv.org/abs/1304.1222\n%\n% Use {sergey.v.dolgov, dmitry.savostyanov}@gmail.com for feedback\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% Special case: amen_sum called from another amen package\nif (~isempty(varargin))\n v1 = varargin{1};\n if (isa(v1, 'cell'))\n varargin=v1;\n end;\nend;\n\n% Default valuse\nnswp = 20;\nkickrank = 4;\nkickrank2 = 0;\nverb = 1;\ny = [];\nz = [];\ninit_qr = true;\nrenorm = 'direct';\n% renorm = 'gram';\nfkick = false;\nrmax = Inf;\nmultrank = false;\n\ncan = false; % Whether the input is the canonical format\n\n% Read parameters from input sequence\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'y0'\n y=varargin{i+1};\n case 'z0'\n z=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'kickrank'\n kickrank=varargin{i+1};\n case 'kickrank2'\n kickrank2=varargin{i+1}; \n case 'init_qr'\n init_qr = varargin{i+1};\n case 'renorm'\n renorm = varargin{i+1};\n case 'fkick'\n fkick = varargin{i+1};\n case 'rmax'\n rmax = varargin{i+1};\n case 'can'\n can = varargin{i+1};\n case 'multrank'\n multrank = varargin{i+1}; \n \n otherwise\n warning('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\n% Convert input to canonical or TT cell array\nN = size(c,1);\nM = size(c,2);\nXin = X;\n\nif (can)\n N = 1;\n % X itself is already given in the required format\n d = numel(X);\n R = size(X{1}, 2); \n nrms = ones(d,1);\n n = zeros(d,1);\n for i=1:d\n n(i) = size(X{i}, 1);\n end;\n vectype = 1;\nelse\n R = 1;\n for j=1:N\n if (isa(Xin{j}, 'tt_tensor'))\n if (j==1)\n d = Xin{j}.d;\n n = Xin{j}.n;\n X = cell(d,N);\n \n % A storage for norms.\n % Z may be kept normalized, but for y we will have y_real = y*prod(nrms).\n % The same for all x. But note that we keep only the _scale_ for all x vecs.\n nrms = ones(d,1);\n end;\n X(:,j) = core2cell(Xin{j});\n vectype = 1; % tt_tensor\n else\n if (j==1)\n d = numel(Xin{j});\n n = zeros(d,1);\n for i=1:d\n n(i) = size(Xin{j}{i}, 2);\n end;\n X = cell(d,N);\n end;\n X(:,j) = Xin{j};\n vectype = 0; % cell\n end;\n end;\nend;\n\n% Initial guess\nif (isempty(y))\n init_qr = false;\n [y,ry] = gen_rand(n,d,2);\nelse\n if (isa(y, 'tt_tensor'))\n y = core2cell(y);\n end;\n ry = ones(d+1,1);\n for i=1:d\n ry(i+1) = size(y{i}, 3);\n end;\nend;\n\n% Enrichment vector\nif (kickrank+kickrank2>0)\n if (isempty(z))\n [z,rz] = gen_rand(n,d,kickrank+kickrank2);\n init_qr_z = false;\n else\n init_qr_z = true;\n if (isa(z, 'tt_tensor'))\n z = core2cell(z);\n end;\n rz = ones(d+1,1);\n for i=1:d\n rz(i+1) = size(z{i}, 3);\n end;\n end;\n \n phizx = cell(d+1,N);\n for j=1:N\n phizx{1,j}=ones(1,R); phizx{d+1,j}=ones(R,1);\n end;\n phizy = cell(d+1,1); phizy{1}=1; phizy{d+1}=1;\nend;\n\nphiyx = cell(d+1,N);\nfor j=1:N\n phiyx{1,j}=ones(1,R); phiyx{d+1,j}=ones(R,1);\nend;\n\n% Initial ort\nfor i=1:d-1\n if (init_qr)\n cr = reshape(y{i}, ry(i)*n(i), ry(i+1));\n if (strcmp(renorm, 'gram'))&&(ry(i)*n(i)>5*ry(i+1))\n [cr,~,R]=svdgram(cr);\n else\n [cr,R]=qr(cr, 0);\n end; \n nrmr = norm(R, 'fro');\n if (nrmr>0)\n R = R/nrmr;\n end;\n cr2 = reshape(y{i+1}, ry(i+1), n(i+1)*ry(i+2));\n cr2 = R*cr2;\n ry(i+1) = size(cr, 2);\n y{i} = reshape(cr, ry(i), n(i), ry(i+1));\n y{i+1} = reshape(cr2, ry(i+1), n(i+1), ry(i+2));\n end;\n % We will extract the norms of Y'X\n [phiyx(i+1,:),nrms(i)] = compute_next_Phi(phiyx(i,:), y{i}, X(i,:), 'lr', can);\n \n if (kickrank+kickrank2>0)\n if (init_qr_z)\n cr = reshape(z{i}, rz(i)*n(i), rz(i+1));\n if (strcmp(renorm, 'gram'))&&(rz(i)*n(i)>5*rz(i+1))\n [cr,~,R]=svdgram(cr);\n else\n [cr,R]=qr(cr, 0);\n end;\n nrmr = norm(R, 'fro');\n if (nrmr>0)\n R = R/nrmr;\n end;\n cr2 = reshape(z{i+1}, rz(i+1), n(i+1)*rz(i+2));\n cr2 = R*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 end;\n \n % But we have to renorm Z'X/|Y'X| to keep Z in the same\n % scale. Hope it will not make |Z'X| too small\n phizx(i+1,:) = compute_next_Phi(phizx(i,:), z{i}, X(i,:), 'lr', can, nrms(i));\n % Z'Y is actually an orthogonal matrix and does not require renorm\n phizy(i+1) = compute_next_Phi(phizy(i), z{i}, y(i), 'lr');\n end;\nend;\n\ni = d;\ndir = -1;\nswp = 1;\nmax_dx = 0;\ny{d} = reshape(y{d}, ry(d)*n(d), ry(d+1));\ny{d} = y{d}(:,1:min(ry(d+1), M));\ny{d} = [y{d}, zeros(ry(d)*n(d), M-ry(d+1))];\ny{d} = reshape(y{d}, ry(d), n(d), 1, M);\nry(d+1) = 1;\n\nwhile (swp<=nswp)\n % Project the sum\n cry = proj_sum(phiyx(i,:), X(i,:), phiyx(i+1,:), c);\n % It will survive in the terminal block. All we need.\n nrms(i) = norm(cry, 'fro');\n % The main goal is to keep y{i} of norm 1\n if (nrms(i)>0)\n cry = cry/nrms(i);\n else\n nrms(i)=1;\n end;\n \n % Check stopping criteria\n y{i} = reshape(y{i}, ry(i)*n(i)*ry(i+1), M);\n dx = norm(cry-y{i}, 'fro')/norm(cry, 'fro');\n max_dx = max(max_dx, dx);\n \n % Truncation and enrichment\n if ((dir>0)&&(irmax)\n u = u(:,1:rmax);\n v = v(:,1:rmax);\n end;\n r = size(u,2);\n else\n [u,s,v]=svd(cry, 'econ');\n s = diag(s);\n r = my_chop2(s, tol*norm(s)/sqrt(d));\n r = min(r,rmax);\n u = u(:,1:r);\n v = conj(v(:,1:r))*diag(s(1:r));\n end; \n if (M==1)&&(multrank)\n % Remove auxiliary previous solution\n v = reshape(v, ry(i+1), 2, r);\n v = v(:,1,:);\n v = reshape(v, ry(i+1), r);\n end;\n \n % Prepare enrichment, if needed\n if (kickrank+kickrank2>0)\n cry = u*v.';\n cry = reshape(cry, ry(i)*n(i)*ry(i+1), M);\n % For updating z\n crys = cry.';\n crys = reshape(crys, M*ry(i)*n(i), ry(i+1));\n crys = crys*phizy{i+1};\n crys = reshape(crys, M, ry(i)*n(i)*rz(i+1));\n crys = crys.';\n cryz = reshape(crys, ry(i), n(i)*rz(i+1)*M);\n cryz = phizy{i}*cryz;\n cryz = reshape(cryz, rz(i)*n(i)*rz(i+1), M);\n \n crz = proj_sum(phizx(i,:), X(i,:), phizx(i+1,:), c);\n crz = crz/nrms(i) - cryz;\n nrmz = norm(crz, 'fro');\n crz = reshape(crz, rz(i)*n(i), rz(i+1)*M);\n [crz,~,~]=svd(crz, 'econ');\n crz = crz(:, 1:min(size(crz,2), kickrank));\n if (kickrank2>0)\n crz = [crz, randn(rz(i)*n(i), kickrank2)];\n [crz,~]=qr(crz,0);\n end;\n % For adding into solution\n if (fkick)\n crs = proj_sum(phiyx(i,:), X(i,:), phizx(i+1,:), c);\n crs = crs/nrms(i) - crys;\n crs = reshape(crs, ry(i)*n(i), rz(i+1)*M);\n [crs,~,~]=svd(crs, 'econ');\n crs = crs(:, 1:min(size(crs,2), kickrank));\n u = [u,crs];\n if (strcmp(renorm, 'gram'))&&(ry(i)*n(i)>5*(ry(i+1)+rz(i+1)))\n [u,~,R]=svdgram(u);\n else\n [u,R]=qr(u, 0);\n end;\n v = [v, zeros(ry(i+1)*M, size(crs,2))];\n v = v*R.';\n r = size(u, 2);\n end;\n end;\n y{i} = reshape(u, ry(i), n(i), r);\n \n cr2 = reshape(y{i+1}, ry(i+1), n(i+1)*ry(i+2));\n v = reshape(v, ry(i+1), M*r);\n cr2 = v.'*cr2;\n cr2 = reshape(cr2, M, r*n(i+1)*ry(i+2));\n y{i+1} = reshape(cr2.', r, n(i+1), ry(i+2), M);\n \n ry(i+1) = r;\n \n [phiyx(i+1,:), nrms(i)] = compute_next_Phi(phiyx(i,:), y{i}, X(i,:), 'lr', can);\n \n if (kickrank+kickrank2>0)\n rz(i+1) = size(crz, 2);\n z{i} = reshape(crz, rz(i), n(i), rz(i+1));\n % z{i+1} will be recomputed from scratch in the next step\n phizx(i+1,:) = compute_next_Phi(phizx(i,:), z{i}, X(i,:), 'lr', can, nrms(i));\n phizy(i+1) = compute_next_Phi(phizy(i), z{i}, y(i), 'lr');\n end;\n elseif ((dir<0)&&(i>1))\n cry = reshape(cry.', M*ry(i), n(i)*ry(i+1));\n if (M==1)&&(multrank)\n % Try to accelerate the rank growth\n cry = [cry; reshape(y{i}, ry(i), n(i)*ry(i+1))];\n end;\n [u,s,v]=svd(cry, 'econ');\n s = diag(s);\n r = my_chop2(s, tol*norm(s)/sqrt(d));\n r = min(r,rmax);\n u = u(:,1:r)*diag(s(1:r));\n v = conj(v(:,1:r));\n \n if (M==1)&&(multrank)\n % Remove auxiliary previous solution\n u = reshape(u, ry(i), 2, r);\n u = u(:,1,:);\n u = reshape(u, ry(i), r);\n end; \n \n % Prepare enrichment, if needed\n if (kickrank+kickrank2>0)\n cry = u*v.';\n cry = reshape(cry, M, ry(i)*n(i)*ry(i+1));\n % For updating z\n crys = cry.';\n crys = reshape(crys, ry(i), n(i)*ry(i+1)*M);\n crys = phizy{i}*crys;\n crys = reshape(crys, rz(i)*n(i)*ry(i+1), M);\n cryz = reshape(crys.', M*rz(i)*n(i), ry(i+1));\n cryz = cryz*phizy{i+1};\n cryz = reshape(cryz, M, rz(i)*n(i)*rz(i+1));\n cryz = cryz.';\n crz = proj_sum(phizx(i,:), X(i,:), phizx(i+1,:), c);\n crz = crz/nrms(i) - cryz;\n nrmz = norm(crz, 'fro');\n crz = reshape(crz.', M*rz(i), n(i)*rz(i+1));\n [~,~,crz]=svd(crz, 'econ');\n crz = crz(:, 1:min(size(crz,2), kickrank));\n if (kickrank2>0)\n crz = [crz, randn(n(i)*rz(i+1), kickrank2)];\n [crz,~]=qr(crz,0);\n end; \n crz = crz';\n % To add into solution\n crs = proj_sum(phizx(i,:), X(i,:), phiyx(i+1,:), c);\n crs = crs/nrms(i) - crys;\n crs = reshape(crs.', M*rz(i), n(i)*ry(i+1));\n [~,~,crs]=svd(crs, 'econ');\n crs = crs(:, 1:min(size(crs,2), kickrank));\n v = [v,conj(crs)];\n if (strcmp(renorm, 'gram'))&&(ry(i+1)*n(i)>5*(ry(i)+rz(i)))\n [v,~,R]=svdgram(v);\n else\n [v,R]=qr(v, 0);\n end;\n u = [u, zeros(M*ry(i), size(crs,2))];\n u = u*R.';\n r = size(v, 2);\n end;\n y{i} = reshape(v.', r, n(i), ry(i+1));\n \n cr2 = reshape(y{i-1}, ry(i-1)*n(i-1), ry(i));\n u = reshape(u, M, ry(i)*r);\n u = u.';\n u = reshape(u, ry(i), r*M);\n cr2 = cr2*u;\n cr2 = reshape(cr2, ry(i-1), n(i-1), r, M);\n y{i-1} = cr2;\n \n ry(i) = r;\n \n [phiyx(i,:), nrms(i)] = compute_next_Phi(phiyx(i+1,:), y{i}, X(i,:), 'rl', can);\n \n if (kickrank+kickrank2>0)\n rz(i) = size(crz, 1);\n z{i} = reshape(crz, rz(i), n(i), rz(i+1));\n % z{i+1} will be recomputed from scratch in the next step\n phizx(i,:) = compute_next_Phi(phizx(i+1,:), z{i}, X(i,:), 'rl', can, nrms(i));\n phizy(i) = compute_next_Phi(phizy(i+1), z{i}, y(i), 'rl');\n end;\n else\n y{i} = reshape(y{i}, ry(i), n(i), ry(i+1), M);\n end;\n \n if (verb>1)\n fprintf('amen-sum: swp=[%d,%d], dx=%3.3e, r=%d, |y|=%3.3e, |z|=%3.3e\\n', swp, i, dx, r, norm(cry, 'fro'), nrmz);\n end;\n \n % Stopping or reversing\n if ((dir>0)&&(i==d))||((dir<0)&&(i==1))\n if (verb>0)\n fprintf('amen-sum: swp=%d{%d}, max_dx=%3.3e, max_r=%d\\n', swp, (1-dir)/2, max_dx, max(ry));\n end;\n if ((max_dx0)\n break;\n end;\n max_dx = 0;\n if (dir>0); swp = swp+1; end;\n dir = -dir;\n else\n i = i+dir;\n end;\nend;\n\ny{d} = reshape(cry, ry(d), n(d), M);\n\n% Distribute norms equally...\nnrms = exp(sum(log(nrms))/d);\n% ... and plug them into y\nfor i=1:d\n y{i} = y{i}*nrms;\nend;\n\nif (vectype==1)\n y = cell2core(tt_tensor, y);\n z = cell2core(tt_tensor, z);\nend;\n\nend\n\n\nfunction [Phi,nrm] = compute_next_Phi(Phi_prev, x, Y, direction, can, extnrm)\n% Performs the recurrent Phi (or Psi) matrix computation\n% Phi = Phi_prev * (x'y).\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\n% Phi2: ry2, rx2\n\nif (nargin<5)||(isempty(can))\n can = false;\nend;\nif (nargin<6)\n extnrm = [];\nend;\n\nrx1 = size(x,1); n = size(x,2); rx2 = size(x,3);\nN = numel(Y);\nif (can) % We are working with the canonical format\n Phi = cell(1,1);\n R = size(Y{1},2);\n % Phi1: rx1, R\n % Phi2: R, rx2\n \n if (strcmp(direction, 'lr'))\n %lr: Phi1\n x = reshape(x, rx1, n*rx2);\n Phi{1} = x'*Phi_prev{1};\n Phi{1} = reshape(Phi{1}, n*rx2, R);\n Y = repmat(Y{1}, rx2, 1); % equalize the sizes for Hadamard product\n Phi{1} = Phi{1}.*Y;\n Phi{1} = reshape(Phi{1}, n, rx2*R);\n Phi{1} = sum(Phi{1}, 1);\n Phi{1} = reshape(Phi{1}, rx2, R);\n if (nargout>1)\n % Extract the scale to prevent overload\n nrm = norm(Phi{1}, 'fro');\n if (nrm>0)\n Phi{1} = Phi{1}/nrm;\n else\n nrm=1;\n end;\n elseif (~isempty(extnrm))\n % Override the normalization by the external one\n Phi{1} = Phi{1}/extnrm;\n end;\n else\n %rl: Phi2\n x = reshape(x, rx1*n, rx2);\n Phi{1} = Phi_prev{1}*x';\n Phi{1} = reshape(Phi{1}, R, rx1*n);\n Y = Y{1}.';\n Y = repmat(Y,rx1,1); % equalize the sizes for Hadamard product\n Y = reshape(Y, R, rx1*n);\n Phi{1} = Phi{1}.*Y;\n Phi{1} = reshape(Phi{1}, R*rx1, n);\n Phi{1} = sum(Phi{1}, 2);\n Phi{1} = reshape(Phi{1}, R, rx1);\n if (nargout>1)\n % Extract the scale to prevent overload\n nrm = norm(Phi{1}, 'fro');\n if (nrm>0)\n Phi{1} = Phi{1}/nrm;\n else\n nrm=1;\n end;\n elseif (~isempty(extnrm))\n % Override the normalization by the external one\n Phi{1} = Phi{1}/extnrm;\n end;\n end;\nelse % a set of TT-tensors\n Phi = cell(1,N);\n if (strcmp(direction, 'lr'))\n %lr: Phi1\n x = reshape(x, rx1, n*rx2);\n if (nargout>1)\n nrm = 0;\n end;\n for i=1:N\n y = Y{i};\n ry1 = size(y,1); ry2 = size(y,3);\n Phi{i} = x'*Phi_prev{i};\n Phi{i} = reshape(Phi{i}, n, rx2*ry1);\n Phi{i} = Phi{i}.';\n Phi{i} = reshape(Phi{i}, rx2, ry1*n);\n y = reshape(y, ry1*n, ry2);\n Phi{i} = Phi{i}*y;\n Phi{i} = reshape(Phi{i}, rx2, ry2);\n if (nargout>1)\n nrm = max(nrm, norm(Phi{i}, 'fro'));\n end;\n end;\n if (nargout>1)\n % Extract the scale to prevent overload\n if (nrm>0)\n for i=1:N\n Phi{i} = Phi{i}/nrm;\n end;\n else\n nrm=1;\n end;\n elseif (~isempty(extnrm))\n % Override the normalization\n for i=1:N\n Phi{i} = Phi{i}/extnrm;\n end;\n end;\n else\n %rl: Phi2\n x = reshape(x, rx1, n*rx2);\n if (nargout>1)\n nrm = 0;\n end;\n for i=1:N\n y = Y{i};\n ry1 = size(y,1); ry2 = size(y,3);\n y = reshape(y, ry1*n, ry2);\n Phi{i} = y*Phi_prev{i};\n Phi{i} = reshape(Phi{i}, ry1, n*rx2);\n Phi{i} = Phi{i}*x';\n Phi{i} = reshape(Phi{i}, ry1, rx1);\n if (nargout>1)\n nrm = max(nrm, norm(Phi{i}, 'fro'));\n end;\n end;\n if (nargout>1)\n % Extract the scale to prevent overload\n if (nrm>0)\n for i=1:N\n Phi{i} = Phi{i}/nrm;\n end;\n else\n nrm=1;\n end;\n elseif (~isempty(extnrm))\n % Override the normalization\n for i=1:N\n Phi{i} = Phi{i}/extnrm;\n end;\n end;\n end;\nend;\n\nend\n\n\nfunction [x,r]=gen_rand(n,d,r)\n% Generate an orthogonal random vector\nif (numel(r)==1)\n r = [1; r*ones(d-1,1); 1];\nend;\nx = cell(d,1);\nfor i=1:d\n cr = randn(r(i)*n(i), r(i+1));\n [cr,~]=qr(cr,0);\n r(i+1) = size(cr,2);\n x{i} = reshape(cr, r(i), n(i), r(i+1));\nend;\nend\n\nfunction [y]=proj_sum(Phi1, X, Phi2, c)\nN = size(c,1);\nM = size(c,2);\n\nry1 = size(Phi1{1},1);\nry2 = size(Phi2{1},2);\n\nif (numel(X)==1) % Canonical format\n X = X{1}; \n n = size(X,1);\n Phi1 = repmat(Phi1{1}, n, 1); % size ry1*n, R\n X = reshape(X, 1, n*N);\n X = repmat(X, ry1, 1);\n X = reshape(X, ry1*n, N);\n y = X.*Phi1;\n c = repmat(c, ry2, 1); % size N*ry2, M\n c = reshape(c, N, ry2*M);\n Phi2 = repmat(Phi2{1}, 1, M); % size N, ry2*M\n Phi2 = Phi2.*c;\n y = y*Phi2;\n y = reshape(y, ry1*n*ry2, M);\n if (issparse(y))\n y = full(y);\n end;\nelse\n n = size(X{1}, 2);\n y = zeros(ry1*n*ry2, M);\n for j=1:N\n rx1 = size(X{j},1); rx2 = size(X{j},3);\n cry = reshape(X{j}, rx1, n*rx2);\n cry = Phi1{j}*cry;\n cry = reshape(cry, ry1*n, rx2);\n cry = cry*Phi2{j};\n cry = reshape(cry, ry1*n*ry2, 1);\n cry = cry*c(j,:);\n y = y+cry;\n end;\nend;\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/core/amen_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3811631823282696}} {"text": "\nclassdef inversion_recovery < AbstractModel\n%inversion_recovery: Compute a T1 map using Inversion Recovery data\n%\n% Assumptions:\n% (1) Gold standard for T1 mapping\n% (2) Infinite TR\n%\n% Inputs:\n% IRData Inversion Recovery data (4D)\n% (Mask) Binary mask to accelerate the fitting (OPTIONAL)\n%\n% Outputs:\n% T1 transverse relaxation time [ms]\n% b arbitrary fit parameter (S=a + b*exp(-TI/T1))\n% a arbitrary fit parameter (S=a + b*exp(-TI/T1))\n% idx index of last polarity restored datapoint (only used for magnitude data)\n% res Fitting residual\n%\n%\n% Protocol:\n%\tIRData [TI1 TI2...TIn] inversion times [ms]\n% TimingTable [TR] repetition time [ms]\n%\n% Options:\n% method Method to use in order to fit the data, based on whether complex or only magnitude data acquired.\n% 'complex' Complex dataset.\n% 'magnitude' Magnitude dataset.\n%\n%\n% fitModel T1 fitting moddel.\n% 'Barral' Fitting equation: a+bexp(-TI/T1)\n% 'General' Fitting equation: c(1-2exp(-TI/T1)+exp(-TR/T1))\n%\n% Example of command line usage (see also showdemo inversion_recovery_batch):\n% Model = inversion_recovery; % Create class from model\n% Model.Prot.IRData.Mat=[350.0000; 500.0000; 650.0000; 800.0000; 950.0000; 1100.0000; 1250.0000; 1400.0000; 1700.0000];\n% data = struct; % Create data structure\n% data.MET2data ='IRData.mat'; % Load data\n% data.Mask = 'Mask.mat';\n% FitResults = FitData(data,Model); %fit data\n% FitResultsSave_mat(FitResults);\n%\n% For more examples: qMRusage(inversion_recovery)\n%\n% Author: Ilana Leppert, 2017\n%\n% References:\n% Please cite the following if you use this module:\n% A robust methodology for in vivo T1 mapping. Barral JK, Gudmundson E, Stikov N, Etezadi-Amoli M, Stoica P, Nishimura DG. Magn Reson Med. 2010 Oct;64(4):1057-67. doi: 10.1002/mrm.22497.\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/cmg9z/download?version=3';\nend\n\n\tproperties\n MRIinputs = {'IRData','Mask'}; % input data required\n xnames = {'T1','rb','ra'}; % name of the fitted parameters\n voxelwise = 1; % voxel by voxel fitting?\n\n % fitting options\n st = [ 600 -1000 500 ]; % starting point\n lb = [ 0.0001 -10000 0.0001 ]; % lower bound\n ub = [ 5000 0 10000 ]; % upper bound\n fx = [ 0 0 0 ]; % fix parameters\n\n % Protocol\n Prot = struct('IRData', struct('Format',{'TI(ms)'},'Mat',[350 500 650 800 950 1100 1250 1400 1700]'),...\n 'TimingTable', struct('Format',{{'TR(ms)'}},'Mat',2500)); %default protocol\n % Model options\n buttons = {'method',{'Magnitude','Complex'}, 'fitModel',{'Barral','General'}}; %selection 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,'T1',600,'M0',1000,'TR',3000,'FAinv',180,'FAexcite',90,'Update input variables','pushbutton'};%'FArefocus',180\n Sim_Optimize_Protocol_buttons = {'# of volumes',5,'Population size',100,'# of migrations',100};\n\n end\n\nmethods (Hidden=true)\n% Hidden methods goes here.\nend\n\n methods\n % -------------CONSTRUCTOR-------------------------------------------------------------------------\n function obj = inversion_recovery()\n obj.options = button2opts(obj.buttons);\n end\n\n function obj = UpdateFields(obj)\n obj.Prot.IRData.Mat = sort(obj.Prot.IRData.Mat);\n end\n function xnew = SimOpt(obj,x,Opt)\n [ra,rb] = ComputeRaRb(obj,x,Opt);\n xnew = [Opt.T1 rb ra];\n\n end\n\n % -------------IR EQUATION-------------------------------------------------------------------------\n function Smodel = equation(obj, x)\n % Generates an IR signal based on fit parameters\n x = mat2struct(x,obj.xnames); % if x is a structure, convert to vector\n\n % equation\n Smodel = x.ra + x.rb * exp(-obj.Prot.IRData.Mat./x.T1);\n if (strcmp(obj.options.method, 'Magnitude'))\n Smodel = abs(Smodel);\n end\n end\n\n % -------------EXPLICIT IR EQUATION-------------------------------------------------------------------------\n function [ra,rb] = ComputeRaRb(obj,x,Opt)\n\n % Some sanity checks\n [ErrMsg]=[];\n\n for brkloop=1:1\n if Opt.TR < max(obj.Prot.IRData.Mat) %TR can't be less than max TI\n txt=['The TR (' num2str(Opt.TR) ') cannot be less than max TI (' num2str(max(obj.Prot.IRData.Mat)),')'];\n ErrMsg = txt; break\n end\n if Opt.T1 < 0 || Opt.T1 > 10000\n txt='Choose a reasonable value for T1 (0-10000 s)';\n ErrMsg = txt; break\n end\n if Opt.FAinv < 120 || Opt.FAinv > 220\n txt='Choose a reasonable value for the inversion FA (120-220 deg)';\n ErrMsg = txt; break\n end\n if Opt.FAexcite < 50 || Opt.FAexcite > 120\n txt='Choose a reasonable value for the excitation FA (50-120 deg)';\n ErrMsg = txt; break\n end\n end\n if ~isempty(ErrMsg)\n if moxunit_util_platform_is_octave\n errordlg(ErrMsg,'Input Error');\n else\n Mode = struct('WindowStyle','modal','Interpreter','tex');\n errordlg(ErrMsg,'Input Error', Mode);\n error(ErrMsg);\n end\n end\n\n % equation for GRE-IR\n ra = Opt.M0 * (1-cos(Opt.FAinv*pi/180)*exp(-Opt.TR/Opt.T1))/(1-cos(Opt.FAinv*pi/180)*cos(Opt.FAexcite*pi/180)*exp(-Opt.TR/Opt.T1));\n rb = -Opt.M0 * (1-cos(Opt.FAinv*pi/180))/(1-cos(Opt.FAinv*pi/180)*cos(Opt.FAexcite*pi/180)*exp(-Opt.TR/Opt.T1));\n %Smodel = ra + rb * exp(-obj.Prot.IRData.Mat./x.T1);\n %if (strcmp(obj.options.method, 'Magnitude'))\n % Smodel = abs(Smodel);\n %end\n end\n\n % -------------DATA FITTING-------------------------------------------------------------------------\n function FitResults = fit(obj,data)\n % Fits the data\n %\n \n data = data.IRData;\n \n switch obj.options.fitModel\n case 'Barral'\n [T1,rb,ra,res,idx] = fitT1_IR(data,obj.Prot.IRData.Mat,obj.options.method);\n FitResults.T1 = T1;\n FitResults.rb = rb;\n FitResults.ra = ra;\n FitResults.res = res;\n if (strcmp(obj.options.method, 'Magnitude'))\n FitResults.idx = idx;\n end\n case 'General'\n approxFlag = 3; % Selects the equation c(1-2exp(-TI/T1)+exp(TR/T1))\n\n params.TI = obj.Prot.IRData.Mat';\n params.TR = obj.Prot.TimingTable.Mat;\n \n if strcmp(obj.options.method, 'Magnitude')\n % Make sure data vector is a column vector\n data = data(:);\n\n % Find the min of the data (which is nearest to\n % signal null to flip\n [~, minInd] = min(data);\n \n % Signal inversion algorithm to fir the T1 curve\n for ii = 1:2\n % Fit the data by inverting the sign of the\n % datapoints up until the TI where signal is\n % null, then also without that point. The\n % fit with the smallest residual is our best\n % guess for up to where to flip the sign of the\n % signal.\n if ii == 1\n % First, we set all elements up to and including\n % the smallest element to minus\n dataTmp = data.*[-ones(minInd,1); ones(length(data) - minInd,1)];\n elseif ii == 2\n % Second, we set all elements up to (not including)\n % the smallest element to minus\n dataTmp = data.*[-ones(minInd-1,1); ones(length(data) - (minInd-1),1)];\n end\n [fitVals{ii}, resnorm(ii)] = inversion_recovery.fit_lm(dataTmp, params, approxFlag);\n end\n [~,ind] = min(resnorm); % Index of the minimum residual will be which signal fit results to choose.\n FitResults.T1 = fitVals{ind}.T1;\n FitResults.ra = fitVals{ind}.ra;\n FitResults.rb = fitVals{ind}.rb;\n FitResults.res = resnorm(ind);\n FitResults.idx = ind;\n elseif strcmp(obj.options.method, 'Complex')\n params.dataType = 'complex';\n [fitVals, resnorm] = inversion_recovery.fit_lm(data(:), params, 3);\n FitResults.T1 = fitVals.T1;\n FitResults.ra = fitVals.ra;\n FitResults.rb = fitVals.rb;\n FitResults.res = resnorm;\n end\n end\n end\n\n function plotModel(obj, FitResults, data)\n % Plots the fit\n %\n % :param FitResults: [struct] Fitting parameters\n % :param data: [struct] input data\n if nargin<2 || isempty(FitResults), FitResults = obj.st; end\n if exist('data','var')\n data = data.IRData;\n % plot\n plot(obj.Prot.IRData.Mat,data,'.','MarkerSize',15)\n hold on\n if (strcmp(obj.options.method, 'Magnitude'))\n % plot the polarity restored data points\n data_rest = -1.*data(1:FitResults.idx);\n plot(obj.Prot.IRData.Mat(1:FitResults.idx),data_rest,'o','MarkerSize',5,'MarkerEdgeColor','b','MarkerFaceColor',[1 0 0])\n end\n end\n\n % compute model\n obj.Prot.IRData.Mat = linspace(min(obj.Prot.IRData.Mat),max(obj.Prot.IRData.Mat),100);\n Smodel = equation(obj, FitResults);\n\n % plot fitting curve\n plot(obj.Prot.IRData.Mat,Smodel,'Linewidth',3)\n hold off\n xlabel('Inversion Time [ms]','FontSize',15);\n ylabel('Signal','FontSize',15);\n legend('data', 'polarity restored', 'fit','Location','best')\n set(gca,'FontSize',15)\n end\n\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\n Smodel = equation(obj, x);\n sigma = max(abs(Smodel))/Opt.SNR;\n if (strcmp(obj.options.method, 'Magnitude'))\n data.IRData = ricernd(Smodel,sigma);\n else\n data.IRData = random('normal',Smodel,sigma);\n end\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 % SimRndGUI\n SimRndResults = SimRnd(obj, RndParam, Opt);\n end\n\n% function schemeLEADER = Sim_Optimize_Protocol(obj,xvalues,Opt)\n% % schemeLEADER = Sim_Optimize_Protocol(obj,xvalues,nV,popSize,migrations)\n% % schemeLEADER = Sim_Optimize_Protocol(obj,obj.st,30,100,100)\n% % Optimize Inversion times\n% nV = Opt.Nofvolumes;\n% popSize = Opt.Populationsize;\n% migrations = Opt.Nofmigrations;\n%\n% sigma = .05;\n% TImax = 5000;\n% TImin = 50;\n% GenerateRandFunction = @() rand(nV,1)*(TImax-TImin)+TImin; % do not sort TI values... or you might fall in a local minima\n% CheckProtInBoundFunc = @(Prot) min(max(50,Prot),TImax);\n% % Optimize Protocol\n% [retVal] = soma_all_to_one(@(Prot) mean(SimCRLB(obj,Prot,xvalues,sigma)), GenerateRandFunction, CheckProtInBoundFunc, migrations, popSize, nV, obj.Prot.IRData.Mat(:,1));\n%\n% % Generate Rest\n% schemeLEADER = retVal.schemeLEADER;\n%\n% fprintf('SOMA HAS FINISHED \\n')\n%\n% end\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, seqFlag, approxFlag)\n %ANALYTICAL_SOLUTION Analytical equations for the longitudinal magnetization of\n %steady-state inversion recovery experiments with either a gradient echo\n %(GRE-IR) or spin-echo (SE-IR) readouts.\n % Reference: Barral, J. K., Gudmundson, E. , Stikov, N. , Etezadi?Amoli,\n % M. , Stoica, P. and Nishimura, D. G. (2010), A robust methodology for\n % in vivo T1 mapping. Magn. Reson. Med., 64: 1057-1067.\n % doi:10.1002/mrm.22497\n %\n % params: struct with the required parameters for the sequence and\n % approximation. See below for list.\n %\n % seqFlag: String. Either 'GRE-IR' or 'SE-IR'\n % approxFlag: Integer between 1 and 4.\n % 1: General equation (no approximation).\n % 2: Ideal 180 degree pulse approximation of case 1.\n % 3: Ideal 90 degree pulse approximation of case 2, and readout term\n % absorbed into constant.\n % 4: Long TR (TR >> T1) approximation of case 3.\n %\n % **PARAMS PROPERTIES**\n % All times in ms, all angles in degrees.\n % 'GRE-IR'\n % case 1: T1, TR, TI, EXC_FA, INV_FA, constant (optional)\n % case 2: T1, TR, TI, EXC_FA, constant (optional)\n % case 3: T1, TR, TI, constant (optional)\n % case 4: T1, TI, constant (optional)\n %\n % 'SE-IR'\n % case 1: Same as 'GRE-IR' case + SE_FA, TE\n % case 2: Same as 'GRE-IR' case + TE\n % case 3: Same as 'GRE-IR' case + TE\n % case 4: Same as 'GRE-IR' case\n %\n\n Mz = ir_equations(params, seqFlag, approxFlag);\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 % INV_FA: Inversion pulse flip angle in degrees.\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 % 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 time TI (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.INV_FA);\n beta = deg2rad(params.EXC_FA);\n TI = params.TI;\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, '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 TI's\n %\n\n for ii = 1:length(TI)\n\n [Msig(ii), Mz(ii)] = ir_blochsim( ...\n alpha, ...\n beta, ...\n TI(ii), ...\n T1, ...\n T2, ...\n TE, ...\n TR, ...\n crushFlag, ...\n partialDephasing, ...\n df, ...\n Nex, ...\n inc ...\n );\n\n end\n\n end\n\n function [fitVals, resnorm] = fit_lm(data, params, approxFlag)\n % FIT_LM Levenberg-Marquardt fitting of GRE-IR data.\n %\n % data: Array for a single voxel (length = #TI)\n % params: Properties TI and TR (except for approxFlag = 4,\n % where only TI is needed)\n % approxFlag: Same flags numbering & equations as for the\n % analytical_solution class method.\n\n switch approxFlag\n case 1\n TI = params.TI;\n TR = params.TR;\n\n % [constant, T1, EXC_FA, INV_FA]\n x0 = [1, 1000, 90, 180];\n\n options.Algorithm = 'levenberg-marquardt';\n options.Display = 'off';\n\n [x, resnorm] = lsqnonlin(@(x)ir_loss_func_1(x, TR, TI, data), x0, [], [], options);\n\n fitVals.INV_FA = x(4);\n fitVals.EXC_FA = x(3);\n fitVals.T1 = x(2);\n fitVals.c = x(1);\n case 2\n TI = params.TI;\n TR = params.TR;\n\n % [constant, T1, EXC_FA]\n x0 = [1, 1000, 90];\n\n options.Algorithm = 'levenberg-marquardt';\n options.Display = 'off';\n\n [x, resnorm] = lsqnonlin(@(x)ir_loss_func_2(x, TR, TI, data), x0, [], [], options);\n\n fitVals.EXC_FA = x(3);\n fitVals.T1 = x(2);\n fitVals.c = x(1);\n\n case 3\n TI = params.TI;\n TR = params.TR;\n\n % Find the min of the data\n [~, minInd] = min(abs(data));\n\n T1est = -TI(minInd)/log(1/2); % Estimate from null (or min) of data and the equation in Case 4. Used as the first guess for the fitting point.\n\n if isfield(params, 'dataType') && strcmp(params.dataType,'complex')\n % Fit comlex data\n % [constant, T1]\n if max(abs(data)) > 0\n dataNorm = data/max(abs(data)); % Normalize the data to fit with the initial constant guess of 1.\n else\n dataNorm = data;\n end\n \n % Initial fit estimates\n % [Re(constant), Im(constant), T1)]\n x0 = [1, 0, T1est];\n\n options.Algorithm = 'trust-region-reflective';\n options.Display = 'off';\n \n % Bound the fitting variables to -2 to 2\n % (constant) and 0 to 5000 (T1 in ms).\n [x, resnorm] = lsqnonlin(@(x)ir_loss_func_3(x, TR, TI, dataNorm(:)', params.dataType), x0, [-2, -2, 0], [2, 2, 5000], options);\n \n fitVals.T1 = x(3);\n \n % ra and rb calculation from Equation 3\n if max(abs(data)) > 0\n fitVals.ra = (x(1)+1i*x(2))*max(abs(data)) * (1 + exp(-TR/fitVals.T1));\n fitVals.rb = -2*(x(1)+1i*x(2))*max(abs(data));\n else\n fitVals.ra = (x(1)+1i*x(2)) * (1 + exp(-TR/fitVals.T1));\n fitVals.rb = -2*(x(1)+1i*x(2));\n end\n else\n % Fit magnitude data\n % [constant, T1]\n x0 = [1, T1est];\n if max(abs(data)) > 0\n dataNorm = data/max(abs(data)); % Normalize the data to fit with the initial constant guess of 1.\n else\n dataNorm = data;\n end\n\n options.Algorithm = 'trust-region-reflective';\n options.Display = 'off';\n\n % Bound the fitting variables to -2 to 2\n % (constant) and 0 to 5000 (T1 in ms).\n [x, resnorm] = lsqnonlin(@(x)ir_loss_func_3(x, TR, TI, dataNorm(:)'), x0, [0, 0], [2, 5000], options);\n\n fitVals.T1 = x(2);\n \n % ra and rb calculation from Equation 3\n if max(abs(data)) > 0\n fitVals.ra = x(1)*max(abs(data)) * (1 + exp(-TR/fitVals.T1));\n fitVals.rb = -2*x(1)*max(abs(data));\n else\n fitVals.ra = x(2) * (1 + exp(-TR/fitVals.T1));\n fitVals.rb = -2*x(2);\n end\n\n end\n\n\n case 4\n TI = params.TI;\n % [constant, T1]\n x0 = [1, 1000];\n\n options.Algorithm = 'levenberg-marquardt';\n options.Display = 'off';\n\n [x, resnorm] = lsqnonlin(@(x)ir_loss_func_4(x, TI, data), x0, [], [], options);\n\n fitVals.T1 = x(2);\n fitVals.c = x(1);\n end\n\n end\n\n end\n\n methods(Access = protected)\n function obj = qMRpatch(obj,loadedStruct, version)\n obj = qMRpatch@AbstractModel(obj,loadedStruct, version);\n % 2.0.10\n if checkanteriorver(version,[2 0 10])\n % Update buttons for simulation\n snrValue = obj.Sim_Single_Voxel_Curve_buttons{2};\n obj.Sim_Single_Voxel_Curve_buttons = {'SNR' snrValue 'T1' 600 'M0' 1000 'TR' 3000 'FAinv' 180 'FAexcite' 90 'Update input variables' 'pushbutton'};\n end\n if checkanteriorver(version,[2 4 1])\n % Update buttons for simulation\n obj.Prot = struct('IRData', struct('Format',{'TI(ms)'},'Mat',[350 500 650 800 950 1100 1250 1400 1700]'),...\n 'TimingTable', struct('Format',{{'TR(ms)'}},'Mat',2500)); %default protocol\n % Model options\n obj.buttons = {'method',{'Magnitude','Complex'}, 'fitModel',{'Barral','General'}}; %selection buttons\n obj.options = button2opts(obj.buttons);\n end\n end\n end\n\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/inversion_recovery.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3808575866370755}} {"text": "function [B,L] = ordered_outline(F)\n % ORDERED_OUTLINE Find outline (boundary) edges of mesh\n %\n % [B,L] = outline(F)\n %\n % Input:\n % F #F by 3 face list of indices\n % Outputs:\n % B #B by 1 list of outline edges \n % L #loops+1 by 1 list of boundary loop start indices into B, the last\n % entries is (by tradition) always the numel of B + 1\n %\n % Example:\n % V = [0 0; 1 0; 1 1 ; 0 1; 4 0; 4 4; 0 4];\n % F = [1 2 3; 1 3 4; 5 6 7];\n % [B,L] = ordered_outline(F);\n % hold on\n % for l = 1:(numel(L)-1)\n % plot(V([B(L(l):(L(l+1)-1)) B(L(l))],1),V([B(L(l):(L(l+1)-1)) B(L(l))],2));\n % end\n % hold off\n %\n % See also: outline\n %\n\n if size(F,2) == 2\n O = F;\n else\n O = outline(F);\n end\n % determine uniqueness of indices \n [u,m,n] = unique(O(:),'rows');\n % determine counts for each unique edge\n counts = accumarray(n(:), 1);\n % all counts should be 2\n assert(all(counts == 2));\n\n % number of outline edges\n no = size(O,1);\n\n % list of boundary \n B = [];\n L = [];\n unseen = true(no,1);\n while any(unseen)\n L = [L numel(B)+1];\n % find first unseen index\n f = find(unseen,1);\n % append start vertex to boundary\n next = O(f,1);\n % keep track of start\n start = next;\n unseen(f) = false;\n B = [B next];\n next = O(f,2);\n % loop until back at start\n while next ~= start\n B = [B next];\n % try to find next as source\n f = find(unseen & O(:,1) == next);\n if isempty(f)\n % try to find next as dest\n f = find(unseen & O(:,2) == next);\n assert(~isempty(f));\n next = O(f,1);\n else\n next = O(f,2);\n end\n unseen(f) = false;\n end\n end\n L = [L numel(B)+1];\n\nend\n\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/ordered_outline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.38069233003885883}} {"text": "%============================================================================\n% Copyright (C) 2015, Heikki Hyyti\n%\n% Permission is hereby granted, free of charge, to any person obtaining a\n% copy of this software and associated documentation files (the \"Software\"),\n% to deal in the Software without restriction, including without limitation\n% the rights to use, copy, modify, merge, publish, distribute, sublicense,\n% and/or sell copies of the Software, and to permit persons to whom the\n% Software is furnished to do so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in\n% all copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n% DEALINGS IN THE SOFTWARE.\n%============================================================================\n\nclassdef DCM_IMU < handle\n% DCM_IMU Implementation of Hyyti's IMU algorithm\n%\n% If you use the algorithm in any scientific context, please cite: \n% Heikki Hyyti and Arto Visala, \"A DCM Based Attitude Estimation Algorithm for Low-Cost MEMS IMUs,\"\n% International Journal of Navigation and Observation, vol. 2015, Article ID 503814, 18 pages, 2015. \n% http://dx.doi.org/10.1155/2015/503814 \n%\n% Date Author Notes\n% 1/12/2015 Heikki Hyyti Initial release\n\n %% Public properties\n properties (Access = public)\n g0 = 9.8189; % gravitation around Helsinki, Finland (change according to your area)\n state = [0 0 1 0 0 0]'; % States are lowest row of rotation matrix and gyroscope x y and z biases\n % (C_31, C_32, C_33, w_b1, w_b2, w_b3)\n q_dcm2 = 0.1^2; % estimated variance of dcm states (gyro variance per second)\n q_gyro_bias2 = 0.0001^2; % very small number to make bias change slowly\n r_acc2 = 0.5^2; % variance of calibrated accelerometer (g-component)\n r_a2 = 10^2; % large variance for some unknown acceleration (acc = a + g)\n q_dcm2_init = 1^2; % initial variance of dcm states (for attitude estimation)\n q_gyro_bias2_init = 0.1^2; % initial variance of bias states (for bias estimator)\n a = zeros(3,1); % estimated non-gravitational accelerations\n yaw = 0; % Yaw angle around z axis (in ZYX convention)\n pitch = 0; % Pitch angle around y axis\n roll = 0; % Roll angle around x axis\n P = []; % estimate covariance (these are initialized in constructor below)\n H = []; % observation model (static)\n Q = []; % proces noise covariance (static part)\n first_row = [1 0 0]'; % first row of of the rotation matrix (for yaw angle estimate)\n end\n\n %% Public methods\n methods (Access = public)\n function obj = DCM_IMU(varargin)\n updateP = true;\n for i = 1:2:nargin\n if strcmp(varargin{i}, 'Gravity'), obj.g0 = varargin{i+1};\n elseif strcmp(varargin{i}, 'State'), obj.state = varargin{i+1};\n elseif strcmp(varargin{i}, 'Covariance'), obj.P = varargin{i+1}; updateP = false;\n elseif strcmp(varargin{i}, 'DCMVariance'), obj.q_dcm2 = varargin{i+1};\n elseif strcmp(varargin{i}, 'BiasVariance'), obj.q_gyro_bias2 = varargin{i+1};\n elseif strcmp(varargin{i}, 'InitialDCMVariance'), obj.q_dcm2_init = varargin{i+1};\n elseif strcmp(varargin{i}, 'InitialBiasVariance'), obj.q_gyro_bias2_init = varargin{i+1}; \n elseif strcmp(varargin{i}, 'MeasurementVariance'), obj.r_acc2 = varargin{i+1};\n elseif strcmp(varargin{i}, 'MeasurementVarianceVariableGain'), obj.r_a2 = varargin{i+1};\n else error('Invalid argument');\n end\n end;\n \n if (updateP), obj.P = [obj.q_dcm2_init*eye(3), zeros(3,3); zeros(3,3), obj.q_gyro_bias2_init*eye(3)]; end;\n obj.H = [eye(3)*obj.g0, zeros(3,3)];\n obj.Q = [obj.q_dcm2*eye(3), zeros(3,3); zeros(3,3) obj.q_gyro_bias2*eye(3)];\n end\n function obj = UpdateIMU(obj, Gyroscope, Accelerometer, SamplePeriod)\n x = obj.state;\n x_last = x;\n Q_ = SamplePeriod^2 * obj.Q; %Process noise covariance with time dependent noise\n \n % control input (angular velocities from gyroscopes)\n if (size(Gyroscope,1) == 3), u = Gyroscope;\n else u = Gyroscope';\n end\n \n % \"rotation operators\"\n C3X = [0 -x(3) x(2); x(3) 0 -x(1); -x(2) x(1) 0];\n UX = [0 -(u(3)-x(6)) u(2)-x(5); \n u(3)-x(6) 0 -(u(1)-x(4)); \n -(u(2)-x(5)) u(1)-x(4) 0];\n\n % Model generation\n A = [zeros(3,3) -SamplePeriod*C3X; zeros(3,6)];\n B = [SamplePeriod*C3X; zeros(3,3)];\n F = eye(6) + [-SamplePeriod*UX, -SamplePeriod*C3X; zeros(3,6)];\n\n % Kalman a priori prediction\n x_predict = x + A*x + B*u;\n P_predict = F * obj.P * F' + Q_;\n\n % measurements/observations (acceleromeres)\n if (size(Accelerometer,1) == 3), z = Accelerometer;\n else z = Accelerometer';\n end \n \n % recompute R using the error between acceleration and the model of g \n % (estimate of the magnitude of a0 in a = a0 + g)\n a_predict = z - x_predict(1:3)*obj.g0;\n a_len = sqrt(a_predict'*a_predict);\n R = (a_len*obj.r_a2 + obj.r_acc2)*eye(3);\n\n % Kalman innovation\n y = z - obj.H*x_predict;\n S = obj.H * P_predict * obj.H' + R;\n\n % Kalman gain\n K = P_predict * obj.H' / S;\n\n % update a posteriori\n x = x_predict + K * y;\n\n % update a posteriori covariance\n IKH = eye(6) - K*obj.H;\n obj.P = IKH * P_predict * IKH' + K * R * K'; % for using any K\n\n % normalization of x & P (divide by DCM vector length)\n dcm_vector_length = sqrt(x(1)^2 + x(2)^2 + x(3)^2);\n J_33 = [x(2)^2 + x(3)^2, -x(1)*x(2), -x(1)*x(3); ...\n -x(1)*x(2), x(1)^2 + x(3)^2, -x(2)*x(3); ...\n -x(1)*x(3), -x(2)*x(3), x(1)^2 + x(2)^2]; \n J = [ J_33 / (dcm_vector_length^3), zeros(3,3); zeros(3,3), eye(3)];\n\n % Laplace approximation of normalization function for x to P, J = Jacobian(f,x)\n % P_new = E[J*(x-x0)*(x-x0)'*J'] = J*E[(x-x0)*(x-x0)']*J' = J*P*J'\n obj.P = J*obj.P*J';\n x(1:3) = x(1:3) ./ dcm_vector_length;\n obj.state = x;\n\n \n % compute Euler angles (not exactly a part of the extended Kalman filter)\n % yaw integration through full rotation matrix\n u_nb = u - x(4:6);\n if (true)\n % Fill rotation matrix from angular values\n \n % cy = cos(obj.yaw); %old angles (last state before integration)\n % sy = sin(obj.yaw);\n % cp = cos(obj.pitch);\n % sp = sin(obj.pitch);\n % cr = cos(obj.roll);\n % sr = sin(obj.roll);\n \n % % compute needed parts of rotation matrix R\n % R11 = cy*cp;\n % R12 = cy*sp*sr-sy*cr;\n % R13 = cy*sp*cr+sy*sr;\n % R21 = sy*cp;\n % R22 = sy*sp*sr+cy*cr;\n % R23 = sy*sp*cr-cy*sr;\n \n % compute needed parts of rotation matrix R using state x and yaw\n cy = cos(obj.yaw); %old yaw angle (last state before integration)\n sy = sin(obj.yaw);\n d = sqrt(x_last(2)^2 + x_last(3)^2);\n d_inv = 1 / d;\n\n % compute needed parts of rotation matrix R (state and angle based version, equivalent with the commented version above)\n R11 = cy * d;\n R12 = -(x_last(3)*sy + x_last(1)*x_last(2)*cy) * d_inv;\n R13 = (x_last(2)*sy - x_last(1)*x_last(3)*cy) * d_inv;\n R21 = sy * d;\n R22 = (x_last(3)*cy - x_last(1)*x_last(2)*sy) * d_inv;\n R23 = -(x_last(2)*cy + x_last(1)*x_last(3)*sy) * d_inv;\n\n % update needed parts of R for yaw computation\n R11_new = R11 + SamplePeriod*(u_nb(3)*R12 - u_nb(2)*R13);\n R21_new = R21 + SamplePeriod*(u_nb(3)*R22 - u_nb(2)*R23);\n\n obj.yaw = atan2(R21_new,R11_new);\n else\n % alternative method estimating the whole rotation matrix\n % integrate full rotation matrix (using first row estimate in memory)\n x1 = obj.first_row + SamplePeriod*UX'*obj.first_row; %rotate x1 by x1 x u_nb\n x2 = C3X * x1; %second row x2 = (state x x1)\n x2 = x2 ./ sqrt(x2(1)^2 + x2(2)^2 + x2(3)^2); % normalize length of the second row\n x1 = C3X' * x2; %recalculate first row x1 = (x2 * state) (ensure perpendicularity)\n obj.first_row = x1 ./ sqrt(x1(1)^2 + x1(2)^2 + x1(3)^2); % normalize length\n obj.yaw = atan2(x2(1),obj.first_row(1));\n end\n \n %compute new pitch and roll angles from a posteriori states\n obj.pitch = asin(-x(1));\n obj.roll = atan2(x(2),x(3)); \n \n % save the estimated non-gravitational acceleration\n obj.a = z - x(1:3)*obj.g0; % acceleration estimate (g reduced) \n end\n end\nend\n", "meta": {"author": "hhyyti", "repo": "dcm-imu", "sha": "762992befcc87be972f9d07c01d039889b545f23", "save_path": "github-repos/MATLAB/hhyyti-dcm-imu", "path": "github-repos/MATLAB/hhyyti-dcm-imu/dcm-imu-762992befcc87be972f9d07c01d039889b545f23/@DCM_IMU/DCM_IMU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3805871183176711}} {"text": "function [y,D,nz] = ksvddenoise(params,msgdelta)\n%KSVDDENOISE K-SVD denoising.\n% [Y,D] = KSVDDENOISE(PARAMS) denoises the specified (possibly\n% multi-dimensional) signal using K-SVD denoising. Y is the denoised\n% signal and D is the trained dictionary produced by K-SVD.\n%\n% [Y,D] = KSVDDENOISE(PARAMS,MSGDELTA) specifies the frequency of message\n% printing during the process. MSGDELTA should be a positive number\n% representing the interval in seconds between messages. A zero or\n% negative value cancels all messages. Default is MSGDELTA=5.\n%\n% [Y,D,NZ] = KSVDDENOISE(...) also returns the average number of non-zero\n% coefficients in the representations of the denoised blocks.\n%\n%\n% Required fields in PARAMS:\n% --------------------------\n%\n% 'x' - Noisy signal.\n% The signal to denoise (can be multi-dimensional). Should be of type\n% double, and (for PSNR computations) with values within [0,1] (to\n% specify a different range, see parameter 'maxval' below).\n%\n% 'blocksize' - Size of block.\n% Indicates the size of the blocks to operate on. Should be either an\n% array of the form [N1 N2 ... Np], where p is the number of\n% dimensions of x, or simply a scalar N, representing the square block\n% [N N ... N]. See parameter 'stepsize' below to specify the amount of\n% overlap between the blocks.\n%\n% 'dictsize' - Size of dictionary to train.\n% Specifies the number of dictionary atoms to train by K-SVD.\n%\n% 'psnr' / 'sigma' - Noise power.\n% Specifies the noise power in dB (psnr) or the noise standard\n% deviation (sigma), used to determine the target error for\n% sparse-coding each block. If both fields are present, sigma is used\n% unless the field 'noisemode' is specified (below). When specifying\n% the noise power in psnr, make sure to set the 'maxval' parameter\n% as well (below) if the signal values are not within [0,1].\n%\n% 'trainnum' - Number of training blocks.\n% Specifies the number of training blocks to extract from the noisy\n% signal for K-SVD training.\n%\n%\n% Optional fields in PARAMS:\n% --------------------------\n%\n% 'initdict' - Initial dictionary.\n% Specifies the initial dictionary for the K-SVD training. Should be\n% either a matrix of size NxL where N=(N1*N2*...*Np), the string\n% 'odct' to specify the overcomplete DCT dictionary, or the string\n% 'data' to initialize using random signal blocks. When a matrix is\n% specified for 'initdict', L must be >= dictsize, and in this case\n% the dictionary is initialized using the first dictsize columns from\n% initdict. By default, initdict='odct'.\n%\n% 'stepsize' - Interval between neighboring blocks.\n% Specifies the interval (in pixels/voxels) between neighboring blocks\n% to denoise in the OMP denoising step. By default, all overlapping\n% blocks are denoised and averaged. This can be changed by specifying\n% an alternate stepsize, as an array of the form [S1 S2 ... Sp] (where\n% p is the number of dimensions of x). This sets the distance between\n% neighboring blocks to be Si in the i-th dimension. Stepsize can also\n% be a scalar S, corresponding to the step size [S S ... S]. Each Si\n% must be >= 1, and, to ensure coverage of the entire noisy signal,\n% size(x,i)-Ni should be a multiple of Si for all i. The default\n% stepsize is 1.\n%\n% 'iternum' - Number of K-SVD iterations.\n% Specifies the number of K-SVD training iterations to perform. If not\n% specified, the default is 10.\n%\n% 'maxval' - Maximal intensity value.\n% Specifies the range of the signal values. Used to determine the\n% noise standard deviation when the noise power is specified in psnr.\n% By default, the signal values are assumed to be within [0,1]. When\n% 'maxval' is specified, this range changes to [0,maxval].\n%\n% 'memusage' - Memory usage.\n% This parameter controls memory usage of the function. 'memusage'\n% should be one of the strings 'high', 'normal' (default) or 'low'.\n% When 'memusage' is specified, both KSVD and OMPDENOISE are invoked\n% using their corresponding memusage setting. Additionallly, when set\n% to 'low', the use of the functions OMPDENOISE2 and OMPDENOISE3 to\n% accelerate denoising of 2-D and 3-D signals is disabled, reverting\n% to the function OMPDENOISE. Note that the 'low' setting will\n% significantly increase runtime.\n%\n%\n% Optional fields in PARAMS - advanced:\n% -------------------------------------\n%\n% 'noisemode' - Noise power mode.\n% Specifies whether the 'psnr' or 'sigma' fields should be used to\n% determine the noise power. This is useful when both fields are\n% present in PARAMS. 'noisemode' should be one of the string 'psnr' or\n% 'sigma'. If it is not present, and both fields are specified,\n% 'sigma' is used.\n%\n% 'gain' - Noise gain.\n% A positive value (usually near 1) controlling the target error for\n% sparse-coding each block. When gain=1, the target error is precisely\n% the value derived from the psnr/sigma fields. When gain is different\n% from 1, the target error is multiplied by this value. The default\n% value is gain = 1.15.\n%\n% 'lambda' - Weight of the input signal.\n% Specifies the relative weight attributed to the noisy input signal\n% in determining the output. The default value is 0.1*(maxval/sigma),\n% where sigma is the standard deviation of the noise. See function\n% OMPDENOISE for more information.\n%\n% 'maxatoms' - Maximal number of atoms.\n% This parameter can be used to specify a hard limit on the number of\n% atoms used to sparse-code each block. Default value is\n% prod(blocksize)/2, i.e. half the number of samples in a block. See\n% function OMP2 for more information.\n%\n% 'exact' - Exact K-SVD update.\n% Specifies whether the exact or approximate dictionary update should\n% be used in the K-SVD training. By default, the approximate\n% computation is used. However, specifying a nonzero value for 'exact'\n% causes the exact computation to be used instead. See function KSVD\n% for more information.\n%\n%\n% Summary of all fields in PARAMS:\n% --------------------------------\n%\n% Required:\n% 'x' signal to denoise\n% 'blocksize' size of block to process\n% 'dictsize' size of dictionary to train\n% 'psnr' / 'sigma' noise power in dB / standard deviation\n% 'trainnum' number of training signals\n%\n% Optional (default values in parenthesis):\n% 'initdict' initial dictionary ('odct')\n% 'stepsize' distance between neighboring blocks (1)\n% 'iternum' number of training iterations (10)\n% 'maxval' maximal intensity value (1)\n% 'memusage' 'low, 'normal' or 'high' ('normal')\n% 'noisemode' 'psnr' or 'sigma' ('sigma')\n% 'gain' noise gain (1.15)\n% 'lambda' weight of input signal (0.1*maxval/sigma)\n% 'maxatoms' max # of atoms per block (prod(blocksize)/2)\n% 'exact' exact update instead of approximate (0)\n%\n%\n% References:\n% [1] M. Elad and M. Aharon, \"Image Denoising via Sparse and Redundant\n% representations over Learned Dictionaries\", the IEEE Trans. on Image\n% Processing, Vol. 15, no. 12, pp. 3736-3745, December 2006.\n%\n% See also KSVD, OMPDENOISE, OMP2.\n\n\n% Ron Rubinstein\n% Computer Science Department\n% Technion, Haifa 32000 Israel\n% ronrubin@cs\n%\n% August 2009\n\n\n%%%%% parse input parameters %%%%%\naddpath('ompbox');\n\nx = params.x;\nblocksize = params.blocksize;\ntrainnum = params.trainnum;\ndictsize = params.dictsize;\n\np = ndims(x);\nif (p==2 && any(size(x)==1) && length(blocksize)==1)\n p = 1;\nend\n\n\n% blocksize %\nif (numel(blocksize)==1)\n blocksize = ones(1,p)*blocksize;\nend\n\n\n% maxval %\nif (isfield(params,'maxval'))\n maxval = params.maxval;\nelse\n maxval = 1;\n params.maxval = maxval;\nend\n\n\n% gain %\nif (isfield(params,'gain'))\n gain = params.gain;\nelse\n gain = 1.15;\n params.gain = gain;\nend\n\n\n% msgdelta %\nif (nargin<2)\n msgdelta = 5;\nend\n\nverbose = 't';\nif (msgdelta <= 0)\n verbose='';\n msgdelta = -1;\nend\n\n\n% initial dictionary %\n\nif (~isfield(params,'initdict'))\n params.initdict = 'odct';\nend\n\nif (isfield(params,'initdict') && ischar(params.initdict))\n if (strcmpi(params.initdict,'odct'))\n params.initdict = odctndict(blocksize,dictsize,p);\n elseif (strcmpi(params.initdict,'data'))\n params = rmfield(params,'initdict'); % causes initialization using random examples\n else\n error('Invalid initial dictionary specified.');\n end\nend\n\nif (isfield(params,'initdict'))\n params.initdict = params.initdict(:,1:dictsize);\nend\n\n\n% noise mode %\nif (isfield(params,'noisemode'))\n switch lower(params.noisemode)\n case 'psnr'\n sigma = maxval / 10^(params.psnr/20);\n case 'sigma'\n sigma = params.sigma;\n otherwise\n error('Invalid noise mode specified');\n end\nelseif (isfield(params,'sigma'))\n sigma = params.sigma;\nelseif (isfield(params,'psnr'))\n sigma = maxval / 10^(params.psnr/20);\nelse\n error('Noise strength not specified');\nend\n\nparams.Edata = sqrt(prod(blocksize)) * sigma * gain; % target error for omp\nparams.codemode = 'error';\n\nparams.sigma = sigma;\nparams.noisemode = 'sigma';\n\n\n% make sure test data is not present in params\nif (isfield(params,'testdata'))\n params = rmfield(params,'testdata');\nend\n\n\n%%%% create training data %%%\n\nids = cell(p,1);\nif (p==1)\n ids{1} = reggrid(length(x)-blocksize+1, trainnum, 'eqdist');\nelse\n [ids{:}] = reggrid(size(x)-blocksize+1, trainnum, 'eqdist');\nend\nparams.data = sampgrid(x,blocksize,ids{:});\nparams.data = remove_dc(params.data,'columns');\n\n\n%%%%% KSVD training %%%%%\n\nif (msgdelta>0)\n disp('KSVD training...');\nend\nD = ksvd(params,verbose,msgdelta);\n\n\n%%%%% denoise the signal %%%%%\n\nif (~isfield(params,'lambda'))\n params.lambda = maxval/(10*sigma);\nend\n\nparams.dict = D;\n\nif (msgdelta>0)\n disp('OMP denoising...');\nend\n\n% call the appropriate ompdenoise function\nif (p>3 || (isfield(params,'memusage') && strcmpi(params.memusage,'low')))\n [y,nz] = ompdenoise(params,msgdelta);\nelseif (p==1)\n [y,nz] = ompdenoise1(params,msgdelta);\nelseif (p==2)\n [y,nz] = ompdenoise2(params,msgdelta);\nelse\n [y,nz] = ompdenoise3(params,msgdelta);\nend\n\nreturn;\n\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/sparsefusion/ksvdbox/ksvddenoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3805604056417288}} {"text": "function [dataout] = ft_denoise_dssp(cfg, datain)\n\n% FT_DENOISE_DSSP implements a dual signal subspace projection algorithm\n% to suppress interference outside a predefined source region of\n% interest. It is based on: Sekihara et al. J. Neural Eng. 2016 13(3), and\n% Sekihara et al. J. Neural Eng. 2018 15(3).\n%\n% Use as\n% dataout = ft_denoise_dssp(cfg, datain)\n% where cfg is a configuration structure that contains\n% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details\n% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')\n% cfg.sourcemodel = structure, source model with precomputed leadfields, see FT_PREPARE_LEADFIELD\n% cfg.dssp = structure with parameters that determine the behavior of the algorithm\n% cfg.dssp.n_space = 'all', or scalar. Number of dimensions for the\n% initial spatial projection.\n% cfg.dssp.n_in = 'all', or scalar. Number of dimensions of the\n% subspace describing the field inside the ROI.\n% cfg.dssp.n_out = 'all', or scalar. Number of dimensions of the\n% subspace describing the field outside the ROI.\n% cfg.dssp.n_intersect = scalar (default = 0.9). Number of dimensions (if\n% value is an integer>=1), or threshold for the\n% included eigenvalues (if value<1), determining\n% the dimensionality of the intersection.\n%\n% See also FT_DENOISE_PCA, FT_DENOISE_SYNTHETIC, FT_DENOISE_TSR\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin = nargin;\nft_nargout = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble debug\nft_preamble loadvar datain\nft_preamble provenance datain\nft_preamble trackconfig\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n % do not continue function execution in case the outputfile is present and the user indicated to keep it\n return\nend\n\n% check the input data\ndatain = ft_checkdata(datain, 'datatype', {'raw'}); % FIXME how about timelock and freq?\n\ncfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed', {'grid', 'sourcemodel'});\n\n% get the options\ncfg.trials = ft_getopt(cfg, 'trials', 'all', 1);\ncfg.channel = ft_getopt(cfg, 'channel', 'all');\ncfg.sourcemodel = ft_getopt(cfg, 'sourcemodel');\ncfg.dssp = ft_getopt(cfg, 'dssp'); % sub-structure to hold the parameters\ncfg.dssp.n_space = ft_getopt(cfg.dssp, 'n_space', 'all'); % number of spatial components to retain from the Gram matrix\ncfg.dssp.n_in = ft_getopt(cfg.dssp, 'n_in', 'all'); % dimensionality of the Bin subspace to be used for the computation of the intersection\ncfg.dssp.n_out = ft_getopt(cfg.dssp, 'n_out', 'all'); % dimensionality of the Bout subspace to be used for the computation of the intersection\ncfg.dssp.n_intersect = ft_getopt(cfg.dssp, 'n_intersect', 0.9); % dimensionality of the intersection\ncfg.output = ft_getopt(cfg, 'output', 'original');\n\n% select channels and trials of interest, by default this will select all channels and trials\ntmpcfg = keepfields(cfg, {'trials', 'channel', 'showcallinfo'});\ndatain = ft_selectdata(tmpcfg, datain);\n% restore the provenance information\n[cfg, datain] = rollback_provenance(cfg, datain);\n\n% match the input data's channels with the labels in the leadfield\nsourcemodel = cfg.sourcemodel;\nif ~isfield(sourcemodel, 'leadfield')\n ft_error('cfg.sourcemodel needs to contain leadfields');\nend\n[indx1, indx2] = match_str(datain.label, sourcemodel.label);\nif ~isequal(indx1(:),(1:numel(datain.label))')\n ft_error('unsupported mismatch between data channels and leadfields');\nend\nif islogical(sourcemodel.inside)\n inside = find(sourcemodel.inside);\nelse\n inside = sourcemodel.inside;\nend\nfor k = inside(:)'\n sourcemodel.leadfield{k} = sourcemodel.leadfield{k}(indx2,:);\nend\n\n% compute the Gram-matrix of the supplied forward model\nlf = cat(2, sourcemodel.leadfield{:});\nG = lf*lf';\n\ndat = cat(2,datain.trial{:});\n[dum, Ae, N, Nspace, Sout, Sin, Sspace, S] = dssp(dat, G, cfg.dssp.n_in, cfg.dssp.n_out, cfg.dssp.n_space, cfg.dssp.n_intersect);\ndatAe = dat*Ae; % the projection is a right multiplication\n% with a matrix (eye(size(Ae,1))-Ae*Ae'), since Ae*Ae' can become quite\n% sizeable, it's computed slightly differently here.\n\n% put some diagnostic information in the output cfg.\ncfg.dssp.S_space = Sspace;\ncfg.dssp.n_space = Nspace;\ncfg.dssp.S_out = Sout;\ncfg.dssp.S_in = Sin;\ncfg.dssp.S_intersect = S;\ncfg.dssp.n_intersect = N;\n\n% compute the cleaned data and put in a cell-array\nnsmp = cellfun(@numel, datain.time);\ncsmp = cumsum([0 nsmp]);\ntrial = cell(size(datain.trial));\nswitch cfg.output\n case 'original'\n for k = 1:numel(datain.trial)\n trial{k} = datain.trial{k} - datAe*Ae((csmp(k)+1):csmp(k+1),:)';\n end\n case 'complement'\n for k = 1:numel(datain.trial)\n trial{k} = datAe*Ae((csmp(k)+1):csmp(k+1),:)';\n end\n otherwise\n ft_error(sprintf('cfg.output = ''%s'' is not implemented',cfg.output));\nend\n\n% create the output argument\ndataout = keepfields(datain, {'label','time','fsample','trialinfo','sampleinfo','grad', 'elec', 'opto'}); % grad can be kept and does not need to be balanced, since the cleaned data is a mixture over time, not space.\ndataout.trial = trial;\n\nft_postamble debug\nft_postamble trackconfig\nft_postamble previous datain\nft_postamble provenance dataout\nft_postamble history dataout\nft_postamble savevar dataout\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions for the computation of the projection matrix\n% kindly provided by Kensuke, and adjusted a bit by Jan-Mathijs\nfunction [Bclean, Ae, Nee, Nspace, Sout, Sin, Sspace, S] = dssp(B, G, Nin, Nout, Nspace, Nee)\n\n% Nc: number of sensors\n% Nt: number of time points\n% inputs\n% B(Nc,Nt): interference overlapped sensor data\n% G(Nc,Nc): Gram matrix of voxel lead field\n% Nout and Nin: dimensions of the two row spaces\n% recom_Nspace: recommended value for the dimension of the pseudo-signal subspace\n% outputs\n% Bclean(Nc,Nt): cleaned sensor data\n% Nee: dimension of the intersection\n% Nspace: dimension of the pseudo-signal subspace\n% ------------------------------------------------------------\n% programmed by K. Sekihara, Signal Analysis Inc.\n% All right reserved by Signal Analysis Inc.\n% -------------------------------------------------------------\n%\n% The code below is modified by Jan-Mathijs, no functional changes\n% merely cosmetics\n\n% eigen decomposition of the Gram matrix, matrix describing the spatial\n% components\n[U,S] = eig(G);\nSspace = abs(diag(S));\n\n[Sspace, iorder] = sort(-Sspace);\nSspace = -Sspace;\nU(:,:) = U(:,iorder);\n\nif isempty(Nspace)\n ttext = 'enter the spatial dimension: ';\n Nspace = input(ttext);\nelseif ischar(Nspace) && isequal(Nspace, 'interactive')\n figure, plot(log10(Sspace),'-o');\n Nspace = input('enter spatial dimension of the ROI subspace: ');\nelseif ischar(Nspace) && isequal(Nspace, 'all')\n Nspace = find(Sspace./Sspace(1)>1e5*eps, 1, 'last');\nend\nfprintf('Using %d spatial dimensions\\n', Nspace);\n\n% spatial subspace projector\nUs = U(:,1:Nspace);\nUSUS = Us*Us';\n\n% Bin and Bout creations\nBin = USUS * B;\nBout = (eye(size(USUS))-USUS) * B;\n\n% create the temporal subspace projector and apply it to the data\n%[AeAe, Nee] = CSP01(Bin, Bout, Nout, Nin, Nee);\n%Bclean = B*(eye(size(AeAe))-AeAe);\n\n[Ae, Nee, Sout, Sin, S] = CSP01(Bin, Bout, Nin, Nout, Nee);\nBclean = B - (B*Ae)*Ae'; % avoid computation of Ae*Ae'\n\n\nfunction [Ae, Nee, Sout, Sin, S] = CSP01(Bin, Bout, Nin, Nout, Nee)\n%\n% interference rejection by removing the common temporal subspace of the two subspaces\n% K. Sekihara, March 28, 2012\n% Golub and Van Loan, Matrix computations, The Johns Hopkins University Press, 1996\n%\n% Nc: number of channels\n% Nt: number of time points\n% inputs\n% Bout(1:Nc,1:Nt): interference data\n% Bin(1:Nc,1:Nt): signal plus interference data\n% ypost(1:Nc,1:Nt): denoised data\n% Nout: dimension of the interference subspace\n% Nin: dimension of the signal plus interference subspace\n% Nee: dimension of the intersection of the two subspaces\n% outputs\n% Ae = matrix from which the projector onto the intersection can\n% be obtained:\n% AeAe: projector onto the intersection, which is equal to the\n% interference subspace.\n% Nee: dimension of the intersection\n% ------------------------------------------------------------\n% programmed by K. Sekihara, Signal Analysis Inc.\n% All right reserved by Signal Analysis Inc.\n% -------------------------------------------------------------\n%\n\n[dum,Sout,Vout] = svd(Bout,'econ');\n[dum,Sin, Vin] = svd(Bin, 'econ');\nSout = diag(Sout);\nSin = diag(Sin);\n\nif isempty(Nout)\n ttext = 'enter the spatial dimension for the outside field: ';\n Nout = input(ttext);\nelseif ischar(Nout) && isequal(Nout, 'interactive')\n figure, plot(Sout,'-o');\n Nout = input('enter dimension of the outside field: ');\nelseif ischar(Nout) && isequal(Nout, 'all')\n Nout = find(Sout./Sout(1)>1e5*eps, 1, 'last');\nend\nfprintf('Using %d spatial dimensions for the outside field\\n', Nout);\n\nif isempty(Nin)\n ttext = 'enter the spatial dimension for the inside field: ';\n Nin = input(ttext);\nelseif ischar(Nin) && isequal(Nin, 'interactive')\n figure, plot(log10(Sin),'-o');\n Nin = input('enter dimension of the inside field: ');\nelseif ischar(Nin) && isequal(Nin, 'all')\n Nin = find(Sin./Sin(1)>1e5*eps, 1, 'last');\nend\nfprintf('Using %d spatial dimensions for the inside field\\n', Nin);\n\nQout = Vout(:,1:Nout);\nQin = Vin(:, 1:Nin);\n\nC = Qin'*Qout;\n[U,S] = svd(C);\nS = diag(S);\nif (ischar(Nee) && strcmp(Nee, 'auto'))\n ft_error('automatic determination of intersection dimension is not supported');\nelseif ischar(Nee) && strcmp(Nee, 'interactive')\n figure, plot(S,'-o');\n Nee = input('enter dimension of the intersection: ');\nelseif Nee<1\n % treat a numeric value < 1 as a threshold\n Nee = find(S>Nee,1,'last');\n if isempty(Nee), Nee = 1; end\nend\nfprintf('Using %d dimensions for the interaction\\n', Nee);\n\nAe = Qin*U;\nAe = Ae(:,1:Nee);\n%AeAe = Ae*Ae';\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/ft_denoise_dssp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3805069753827569}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%% BREATHING FILTER DETECTION TASK ANALYSIS %%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% -------------------------------------------------------------------------\n% Author: Olivia Harrison\n% Created: 14/08/2018\n%\n% This software is free software: you can redistribute it and/or modify it \n% under the terms of the GNU General Public License as published by the \n% Free Software Foundation, either version 3 of the License, or (at your \n% option) any later version. This software is distributed in the hope that \n% it will be useful, but WITHOUT ANY WARRANTY; without even the implied \n% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n% GNU General Public License for more details: http://www.gnu.org/licenses/\n% -------------------------------------------------------------------------\n\n% This analysis script uses either Brian Maniscalco's single subect\n% analysis or Steve Fleming's Hierarchical Bayesian toolbox (for group\n% analysis) to calculate perceptual decision and metacognitive metrics, \n% specific to data produced by running the tapas_filter_detection_task.\n\n% IMPORTANT ANALYSIS NOTES:\n% 1) The code requires JAGS software to run, which can be found here:\n% http://mcmc-jags.sourceforge.net/\n% The code has been tested on JAGS 3.4.0; there are compatibility\n% issues between matjags and JAGS 4.X.\n% 2) The code requires the HMeta-d toolbox (provided as a submodule\n% from https://github.com/metacoglab/HMeta-d) to be on your path.\n% 3) This script is looking for specific results files that were output\n% from the tapas_filter_detection_task, which are located in the\n% FDT/results/ folder. The results are expected to contain a \n% results.filterThreshold.xx structure, where values for xx:\n% - results.filterThreshold.filterNum: a value to determine the\n% number of filters where trials were performed\n% - results.filterThreshold.filters: a vector with 1 meaning\n% filters were presented, 0 when filters were absent (dummy)\n% - results.filterThreshold.response: a vector with 1 meaning\n% response was 'yes', 0 when response was 'no'\n% - results.filterThreshold.confidence: a vector containing\n% confidence score (1-10) on each trial\n% If your results are formatted differently, refer directly to the\n% original scripts from the HMeta-d toolbox \n% (https://github.com/metacoglab/HMeta-d).\n\n% TO RUN THIS SCRIPT:\n% type tapas_filter_detection_analysis into the MATLAB terminal from the \n% main FDT folder, and follow the prompts.\n\n% ANALYSIS OPTIONS:\n% This script allows you to run either:\n% - A single subject analysis: A non-Bayesian estimation of meta-d',\n% fitting one subject at a time using a single point maximum\n% likelihood estimation (from the original Maniscalco & Lau 2012\n% paper, more info can be found here: \n% http://www.columbia.edu/~bsm2105/type2sdt/archive/index.html).\n% HOWEVER: Simulations have shown this analysis to be VERY unstable\n% when estimating meta-d' using 60 trials. It is STRONGLY encouraged\n% to utilise the hierarchical models, or collect many more trials \n% (200+ trials) for each subject to have a more reliable measure of\n% meta-d'.\n% - A group mean analysis: A hierarchical Bayesian analysis, whereby all\n% subjects are fit together and information from the group mean is\n% used as prior information for each subject. This hierarchical model\n% helps with much more accurate estimations of meta-d' with small\n% trial numbers, such as using 60 trials per subject.\n% - A group regression analysis: A hierarchical Bayesian regression\n% analysis that is an extension on the group mean analysis, whereby \n% subjects are fit together in one model, and the relationship between\n% single subject log(meta-d'/d') values and the covariate(s) is\n% estimated within the hierarchical model structure.\n% - A group difference analysis: A hierarchical Bayesian analysis,\n% whereby each group of subjects is fitted separately, and the groups\n% are then compared. Frequentist statistics (such as parametric\n% unpaired T-tests, or non-parametric Wilcoxon signed-rank tests) can\n% be used for all values that are not fitted using hierarchical\n% information, such as d', c, filter number, accuracy and average\n% confidence. As the group values for log(meta-d'/d') are calculated\n% using two separate hierarchical models, group differences are then\n% inferred via comparison of the resulting log(meta-d'/d')\n% distributions, and whether the 95% highest-density interval (HDI) of\n% the difference between the distributions spans zero. The HDI is the\n% shortest possible interval containing 95% of the MCMC samples, and\n% may not be symmetric. NOTE: If single subject values for\n% log(meta-d'/d') (or any related meta-d' metric) are required for\n% further analyses that span both groups (such as entry into general \n% linear models), it is recommended to fit all subjects together in\n% one regression model with a regressor denoting group identity.\n% - A session difference analysis (paired group difference): A\n% hierarchical Bayesian analysis, whereby two sessions / measures from\n% the same participants are fitted in a single model using a\n% multivariate normal distribution. This distribution allows for the\n% non-independence between sessions for each participant. NOTE:\n% Participants must be listed in the same order for analysis, and must\n% have data for both sessions / each measure.\n\n% NOTES ON NON-BAYESIAN SINGLE SUBJECT ANALYSIS FROM AUTHORS' WEBSITE \n% (columbia.edu/~bsm2105/type2sdt/archive/index.html):\n% This analysis is intended to quantify metacognitive sensitivity (i.e. the\n% efficacy with which confidence ratings discriminate between correct and\n% incorrect judgments) in a signal detection theory framework. A central\n% idea is that primary task performance can influence metacognitive\n% sensitivity, and it is informative to take this influence into account.\n% Description of the methodology can be found here: Maniscalco, B., & Lau, \n% H. (2012). A signal detection theoretic approach for estimating\n% metacognitive sensitivity from confidence ratings. Consciousness and\n% Cognition, 21(1), 422–430. doi:10.1016/j.concog.2011.09.021 \n% If you use these analysis files, please reference the Consciousness & \n% Cognition paper and website. Brian Maniscalco: brian@psych.columbia.edu\n\n% NOTES ON HIERARCHICAL TOOLBOX FROM ORIGINAL SCRIPTS (FOR GROUP ANALYSES):\n% This MATLAB toolbox implements the meta-d’ model (Maniscalco & Lau, 2012)\n% in a hierarchical Bayesian framework using Matlab and JAGS, a program for\n% conducting MCMC inference on arbitrary Bayesian models. A paper with more\n% details on the method and the advantages of estimating meta-d’ in a\n% hierarchal Bayesian framework is available here https://academic.oup.com/\n% nc/article/doi/10.1093/nc/nix007/3748261/HMeta-d-hierarchical-Bayesian-\n% estimation-of. For a more general introduction to Bayesian models of \n% cognition see Lee & Wagenmakers, Bayesian Cognitive Modeling: A Practical\n% Course http://bayesmodels.com/. This code is being released with a\n% permissive open-source license. You should feel free to use or adapt the\n% utility code as long as you follow the terms of the license provided. If\n% you use the toolbox in a publication we ask that you cite the following\n% paper: Fleming, S.M. (2017) HMeta-d: hierarchical Bayesian estimation of\n% metacognitive efficiency from confidence ratings, Neuroscience of\n% Consciousness, 3(1) nix007, https://doi.org/10.1093/nc/nix007. Copyright\n% (c) 2017, Stephen Fleming. For more information and/or licences, please \n% see the original code: https://github.com/metacoglab/HMeta-d.\n\n% KEY ANALYSIS OUTPUT VALUES:\n% The primary measures to come out of this analysis can be found in\n% analysis.{single/groupMean/groupDiff}.xx, and they are:\n% 1) xx = filterNum: Number of filters. Less filters means more sensitive\n% to changes in breathing.\n% 2) xx = d1: d prime, discriminability between filter and dummy trials.\n% Larger d' means more discriminability at specific filter number\n% 3) xx = c1: Decision criterion, or where the decision boundary exists.\n% Negative criterion values mean bias towards 'yes' (lower, more \n% liberal criterion), while positive values mean bias towards \n% 'no' response (higher, more strngent criterion).\n% 4) xx = meta_d: A measure of metacognition, or 'type 2' sensitivity.\n% This reflects how much information, in signal-to-noise units,\n% is available for metacognition (see Maniscalco & Lau, 2012).\n% NB: ISSUES WITH THIS ESTIMATION (AND ALL RELATED ESTIMATIONS)\n% IF USING SINGLE SUBJECT ANALYSES, AS DESCRIBED ABOVE.\n% 5) xx = Mratio: Meta-d' to d' ratio, as a measure of metacognitive\n% 'efficiency' (see Rouault et al., 2018).\n% 6) xx = log_Mratio: log(meta_d/d1), reported in papers to help with\n% normalisation of data (see Rouault et al., 2018).\n% 7) xx = avgConfidence: A second measure of metacognition, thought to be\n% independent from meta-d'. NB: Average confidence should only be\n% compared between two groups if there is no difference in d'\n% between the groups (i.e. task difficulty was comparable).\n\n% ADDITIONAL GROUP DIFFERENCE OUTPUT VALUES:\n% If the analysis is a two-group or two-session (paired) difference, the \n% following will also be calculated for the non-hierarchical measures \n% (test = groupDiff or sessionDiff; xx = filterNum, d1, c1 and \n% avgConfidence):\n% 1) analysis.test.xx.h = Results of null hypothesis test, where h =\n% 1 for rejection of the null, and h = 0 for no rejection.\n% 2) analysis.test.xx.p = The p-value for the statistical test.\n% 3) analysis.test.xx.stats = Further statistics (such as tstats,\n% number of samples, degrees of freedom) associated with the test.\n% 4) analysis.test.xx.ci = Confidence interval of the difference,\n% calculated only when T-test is specified.\n% The highest density interval (HDI) for the difference in log(meta-d'/d') \n% between the groups / sessions will be calculated and recorded, as \n% frequentist statistics cannot be used here. A summary Figure for each of \n% these metrics will be created and saved in the FDT/analysis/ folder.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SET UP THE ANALYSIS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction tapas_filter_detection_analysis()\n\n% Check folder location is main FDT folder\n[~,dir_name] = fileparts(pwd);\nif ~strcmp(dir_name,'FDT')\n error('Not currently in main FDT folder. Please move to FDT folder and try again.');\nend\n\n% Add relevant paths\naddpath('analysis');\n\n% Display setup on screen\nfprintf('\\n________________________________________\\n\\n SET UP ANALYSIS FOR FILTER TASK\\n________________________________________\\n');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CHOOSE THE TYPE OF ANALYSIS TO RUN AND SPECIFY FILES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ntry\n analysis.type = input('Type of analysis (single or group) = ', 's'); % Ask for type of analysis to be run\ncatch\n fprintf('\\nOption does not exist, please try again.\\n');\n return\nend\n\ntry\n if strcmp(analysis.type,'single') == 1 % If single subject analysis specified\n analysis.PPIDs = input('PPID = ', 's'); % Ask for PPID\n try\n analysis.data = load(fullfile('results', ['filter_task_results_', analysis.PPIDs, '.mat'])); % Load data\n analysis.ratings = analysis.data.results.setup.confidenceUpper - analysis.data.results.setup.confidenceLower + 1; % Calculate number of confidence rating bins\n catch\n fprintf('\\nInvalid PPID.\\n');\n return\n end\n elseif strcmp(analysis.type,'group') == 1 % If group analysis specified\n analysis.type = input('Type of analysis (mean, diff, paired or regress) = ', 's'); % Ask for type of group analysis to be run\n if strcmp(analysis.type,'mean') == 1 % If group mean analysis specified\n analysis.PPIDs = input('Input group PPIDs (e.g. {''001'', ''002'', ''003'',...}) = '); % Ask for PPIDs\n analysis.groupsize(1) = length(analysis.PPIDs);\n for n = 1:length(analysis.PPIDs)\n PPID = char(analysis.PPIDs(n));\n try\n analysis.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data\n catch\n fprintf('\\nInvalid PPIDs.\\n');\n return\n end\n end\n analysis.ratings = analysis.data(1).results.setup.confidenceUpper - analysis.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins\n elseif strcmp(analysis.type,'diff') == 1 % If two group difference analysis specified\n analysis.PPIDs.group1 = input('Input group 1 PPIDs (e.g. {''001'', ''002'', ''003'',...}) = '); % Ask for PPIDs\n analysis.PPIDs.group2 = input('Input group 2 PPIDs (e.g. {''004'', ''005'', ''006'',...}) = '); % Ask for PPIDs\n analysis.groupDiff.test = input('Type 1 variable tests (ttest or wilcoxon) = ', 's'); % Ask for parametric or non-parmetric test options for type 1 variables (d', c etc.)\n analysis.groupsize(1) = length(analysis.PPIDs.group1);\n analysis.groupsize(2) = length(analysis.PPIDs.group2);\n for n = 1:analysis.groupsize(1)\n PPID = char(analysis.PPIDs.group1(n));\n try\n analysis.group1.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data\n catch\n fprintf('\\nInvalid PPIDs for group 1.\\n');\n return\n end\n end\n for n = 1:analysis.groupsize(2)\n PPID = char(analysis.PPIDs.group2(n));\n try\n analysis.group2.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data\n catch\n fprintf('\\nInvalid PPIDs for group 2.\\n');\n return\n end\n end\n analysis.ratings = analysis.group1.data(1).results.setup.confidenceUpper - analysis.group1.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins\n elseif strcmp(analysis.type,'paired') == 1 % If paired difference analysis specified\n fprintf('\\nNOTE: PPIDs from each session need to be paired and in the same order\\n');\n analysis.PPIDs.session1 = input('Input session 1 PPIDs (e.g. {''001a'', ''002a'', ''003a'',...}) = '); % Ask for PPIDs\n analysis.PPIDs.session2 = input('Input session 2 PPIDs (e.g. {''001b'', ''002b'', ''003b'',...}) = '); % Ask for PPIDs\n analysis.sessionDiff.test = input('Type 1 variable tests (ttest or wilcoxon) = ', 's'); % Ask for parametric or non-parmetric test options for type 1 variables (d', c etc.)\n analysis.sessionSize(1) = length(analysis.PPIDs.session1);\n analysis.sessionSize(2) = length(analysis.PPIDs.session2);\n if analysis.sessionSize(1) ~= analysis.sessionSize(2)\n error('Number of PPIDs in each session does not match!');\n end\n for n = 1:analysis.sessionSize(1)\n PPID = char(analysis.PPIDs.session1(n));\n try\n analysis.session1.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data\n catch\n fprintf('\\nInvalid PPIDs for session 1.\\n');\n return\n end\n end\n for n = 1:analysis.sessionSize(2)\n PPID = char(analysis.PPIDs.session2(n));\n try\n analysis.session2.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data\n catch\n fprintf('\\nInvalid PPIDs for session 2.\\n');\n return\n end\n end\n analysis.ratings = analysis.session1.data(1).results.setup.confidenceUpper - analysis.session1.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins\n elseif strcmp(analysis.type,'regress') == 1 % If regression analysis specified\n analysis.PPIDs = input('Input group PPIDs (e.g. {''001'', ''002'', ''003'',...}) = '); % Ask for PPIDs\n analysis.groupsize(1) = length(analysis.PPIDs);\n for n = 1:length(analysis.PPIDs)\n PPID = char(analysis.PPIDs(n));\n try\n analysis.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data\n catch\n fprintf('\\nInvalid PPIDs.\\n');\n return\n end\n end\n analysis.ratings = analysis.data(1).results.setup.confidenceUpper - analysis.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins\n fprintf('\\nNote: Covariate text file required to be placed in results folder\\n--> Scores need to be in the SAME ORDER as PPID input order.\\n');\n analysis.covariate.fileName = input('Input covariate file name (e.g. covariate_example.txt) = ', 's'); % Ask for covariate file name\n try\n analysis.covariate.data = load(fullfile('results', analysis.covariate.fileName)); % Load data\n catch\n fprintf('\\nCovariate file cannot be found in results folder.\\n');\n return\n end\n [a,b] = size(analysis.covariate.data);\n if a > b % Re-shape vector if needed\n analysis.covariate.data = analysis.covariate.data';\n end\n end\n end\ncatch\n fprintf('\\nInvalid.\\n');\n return\nend\n\n% Save results\nif strcmp(analysis.type,'single') == 1\n resultsFile = fullfile('analysis', ['filter_task_analysis_', analysis.type, analysis.PPIDs]); % Create figure file name\nelse\n resultsFile = fullfile('analysis', ['filter_task_analysis_', analysis.type]); % Create figure file name\nend\nsave(resultsFile, 'analysis'); % Save results\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUN TRIALS2COUNTS SCRIPT\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(analysis.type,'single') == 1 || strcmp(analysis.type,'mean') == 1 || strcmp(analysis.type,'regress') == 1\n \n % Run trials2counts script for single subject or whole group\n for n = 1:length(analysis.data)\n stimID = analysis.data(n).results.thresholdTrials.filters;\n response = analysis.data(n).results.thresholdTrials.response;\n rating = analysis.data(n).results.thresholdTrials.confidence;\n [analysis.trials2counts.nR_S1{n}, analysis.trials2counts.nR_S2{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding\n end\n \nelseif strcmp(analysis.type,'diff') == 1\n \n % Run trials2counts script for group 1\n for n = 1:length(analysis.group1.data)\n stimID = analysis.group1.data(n).results.thresholdTrials.filters;\n response = analysis.group1.data(n).results.thresholdTrials.response;\n rating = analysis.group1.data(n).results.thresholdTrials.confidence;\n [analysis.group1.trials2counts.nR_S1{n}, analysis.group1.trials2counts.nR_S2{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding\n end\n % Run trials2counts script for group 2\n for n = 1:length(analysis.group2.data)\n stimID = analysis.group2.data(n).results.thresholdTrials.filters;\n response = analysis.group2.data(n).results.thresholdTrials.response;\n rating = analysis.group2.data(n).results.thresholdTrials.confidence;\n [analysis.group2.trials2counts.nR_S1{n}, analysis.group2.trials2counts.nR_S2{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding\n end\n \nelseif strcmp(analysis.type,'paired') == 1\n \n % Run trials2counts script for session 1\n for n = 1:length(analysis.session1.data)\n stimID = analysis.session1.data(n).results.thresholdTrials.filters;\n response = analysis.session1.data(n).results.thresholdTrials.response;\n rating = analysis.session1.data(n).results.thresholdTrials.confidence;\n [analysis.trials2counts.nR_S1(1).counts{n}, analysis.trials2counts.nR_S2(1).counts{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding\n end\n % Run trials2counts script for session 2\n for n = 1:length(analysis.session2.data)\n stimID = analysis.session2.data(n).results.thresholdTrials.filters;\n response = analysis.session2.data(n).results.thresholdTrials.response;\n rating = analysis.session2.data(n).results.thresholdTrials.confidence;\n [analysis.trials2counts.nR_S1(2).counts{n}, analysis.trials2counts.nR_S2(2).counts{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding\n end\n \nend\n\n% Save results\nsave(resultsFile, 'analysis');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUN SINGLE SUBJECT ANALYSIS IF SPECIFIED\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(analysis.type,'single') == 1 % If single subject analysis specified\n \n % Pad ratings so that zero counts do not interfere with fit\n analysis.trials2counts.nR_S1_padded = analysis.trials2counts.nR_S1{1} + 1/(2*10);\n analysis.trials2counts.nR_S2_padded = analysis.trials2counts.nR_S2{1} + 1/(2*10);\n \n % Fit data\n analysis.single.fit = fit_meta_d_MLE(analysis.trials2counts.nR_S1_padded, analysis.trials2counts.nR_S2_padded);\n \n % Pull out key variables\n analysis.single.filterNum = mean(analysis.data.results.thresholdTrials.filterNum);\n analysis.single.accuracy = analysis.data.results.thresholdTrials.accuracyTotal;\n analysis.single.d1 = analysis.single.fit.d1;\n analysis.single.c1 = analysis.single.fit.c1;\n analysis.single.meta_d = analysis.single.fit.meta_d;\n analysis.single.Mratio = analysis.single.fit.M_ratio;\n analysis.single.fit.log_Mratio = log(analysis.single.fit.M_ratio);\n analysis.single.avgConfidence = mean(analysis.data(1).results.thresholdTrials.confidence);\n \n % Save results\n save(resultsFile, 'analysis'); % Save results\n \n % Display completion message on screen\n fprintf('\\n________________________________________\\n\\n COMPLETED SINGLE SUBJECT ANALYSIS\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n fprintf('\\n MRATIO = %.2f\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n', analysis.single.Mratio);\n fprintf('\\n RESULTS CAN BE FOUND IN: \\n FDT/analysis/\\n________________________________________\\n');\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUN GROUP MEAN ANALYSIS IF SPECIFIED\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(analysis.type,'mean') == 1 % If group mean analysis specified\n \n % Specify parameters\n analysis.groupMean.mcmc_params = fit_meta_d_params;\n\n % Fit group data all at once\n analysis.groupMean.fit = fit_meta_d_mcmc_group(analysis.trials2counts.nR_S1, analysis.trials2counts.nR_S2, analysis.groupMean.mcmc_params);\n \n % Calculate log of Mratio for single subjects values\n for n = 1:length(analysis.groupMean.fit.Mratio)\n analysis.groupMean.log_Mratio.singleSubject(n) = log(analysis.groupMean.fit.Mratio(n));\n end\n \n % Pull out group mean values\n analysis.groupMean.d1.groupMean = mean(analysis.groupMean.fit.d1);\n analysis.groupMean.d1.singleSubject = analysis.groupMean.fit.d1;\n analysis.groupMean.c1.groupMean = mean(analysis.groupMean.fit.c1);\n analysis.groupMean.c1.singleSubject = analysis.groupMean.fit.c1;\n analysis.groupMean.meta_d.groupMean = mean(analysis.groupMean.fit.meta_d);\n analysis.groupMean.meta_d.singleSubject = analysis.groupMean.fit.meta_d;\n analysis.groupMean.Mratio.groupMean = exp(analysis.groupMean.fit.mu_logMratio);\n analysis.groupMean.Mratio.singleSubject = analysis.groupMean.fit.Mratio;\n analysis.groupMean.Mratio.hdi = calc_HDI(exp(analysis.groupMean.fit.mcmc.samples.mu_logMratio(:)));\n analysis.groupMean.log_Mratio.groupMean = analysis.groupMean.fit.mu_logMratio;\n analysis.groupMean.log_Mratio.hdi = calc_HDI(analysis.groupMean.fit.mcmc.samples.mu_logMratio(:));\n \n % Calculate average confidence, add filter number and accuracy to analysis results\n for n = 1:length(analysis.data)\n analysis.groupMean.avgConfidence.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.confidence);\n analysis.groupMean.filterNum.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.filterNum);\n analysis.groupMean.accuracy.singleSubject(n) = analysis.data(n).results.thresholdTrials.accuracyTotal;\n end\n analysis.groupMean.avgConfidence.groupMean = mean(analysis.groupMean.avgConfidence.singleSubject);\n analysis.groupMean.filterNum.groupMean = mean(analysis.groupMean.filterNum.singleSubject);\n analysis.groupMean.accuracy.groupMean = mean(analysis.groupMean.accuracy.singleSubject);\n \n % Save results\n save(resultsFile, 'analysis'); % Save results\n \n % Display completion message on screen\n fprintf('\\n________________________________________\\n\\n COMPLETED GROUP MEAN ANALYSIS\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n fprintf('\\n GROUP MRATIO = %.2f (HDI: %.2f to %.2f)\\n', analysis.groupMean.Mratio.groupMean, analysis.groupMean.Mratio.hdi(1), analysis.groupMean.Mratio.hdi(2));\n if (analysis.groupMean.Mratio.hdi(1) > 0 && analysis.groupMean.Mratio.hdi(2) > 0) || (analysis.groupMean.Mratio.hdi(1) < 0 && analysis.groupMean.Mratio.hdi(2) < 0)\n fprintf(' HDI DOES NOT SPAN ZERO: MRATIO SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n else\n fprintf(' HDI SPANS ZERO: MRATIO NOT SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n end\n fprintf('\\n RESULTS CAN BE FOUND IN: \\n FDT/analysis/\\n________________________________________\\n');\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUN GROUP DIFFERENCE ANALYSIS (UNPAIRED) IF SPECIFIED\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(analysis.type,'diff') == 1 % If group difference analysis specified\n \n % For two-group difference analysis: Print message about groups being fit separately --> no t-tests possible on meta-d' metrics\n fprintf('\\nNOTE: Groups are fit using separate hierarchical models.\\nFrequentist statistics (such as t-tests) are not possible on any metrics involving meta-d''.\\nFrequentist statistics will still be applied to all type 1 metrics and average confidence values.\\n');\n \n % Specify parameters\n analysis.groupDiff.mcmc_params = fit_meta_d_params;\n \n % Fit each group using a separate hierarchical Bayesian model\n analysis.group1.fit = fit_meta_d_mcmc_group(analysis.group1.trials2counts.nR_S1, analysis.group1.trials2counts.nR_S2, analysis.groupDiff.mcmc_params);\n analysis.group2.fit = fit_meta_d_mcmc_group(analysis.group2.trials2counts.nR_S1, analysis.group2.trials2counts.nR_S2, analysis.groupDiff.mcmc_params);\n \n % Compute HDI of difference for log(meta-d'/d')\n analysis.group1.logMratio.groupMean = analysis.group1.fit.mu_logMratio;\n analysis.group1.logMratio.singleSubject = log(analysis.group1.fit.Mratio);\n analysis.group1.Mratio.groupMean = exp(analysis.group1.fit.mu_logMratio);\n analysis.group1.Mratio.singleSubject = analysis.group1.fit.Mratio;\n analysis.group2.logMratio.groupMean = analysis.group2.fit.mu_logMratio;\n analysis.group2.logMratio.singleSubject = log(analysis.group2.fit.Mratio);\n analysis.group2.Mratio.groupMean = exp(analysis.group2.fit.mu_logMratio);\n analysis.group2.Mratio.singleSubject = analysis.group2.fit.Mratio;\n analysis.groupDiff.log_Mratio.sampleDiff = analysis.group1.fit.mcmc.samples.mu_logMratio - analysis.group2.fit.mcmc.samples.mu_logMratio;\n analysis.groupDiff.log_Mratio.mean = analysis.group1.fit.mu_logMratio - analysis.group2.fit.mu_logMratio;\n analysis.groupDiff.log_Mratio.hdi = calc_HDI(analysis.groupDiff.log_Mratio.sampleDiff(:));\n analysis.groupDiff.Mratio.mean = exp(analysis.group1.fit.mu_logMratio) - exp(analysis.group2.fit.mu_logMratio);\n analysis.groupDiff.Mratio.hdi = calc_HDI((exp(analysis.group1.fit.mcmc.samples.mu_logMratio(:)) - exp(analysis.group2.fit.mcmc.samples.mu_logMratio(:))));\n\n % Pull out group mean values for all non-hierarchical metrics\n analysis.group1.d1.groupMean = mean(analysis.group1.fit.d1);\n analysis.group1.d1.singleSubject = analysis.group1.fit.d1;\n analysis.group1.c1.groupMean = mean(analysis.group1.fit.c1);\n analysis.group1.c1.singleSubject = analysis.group1.fit.c1;\n analysis.group2.d1.groupMean = mean(analysis.group2.fit.d1);\n analysis.group2.d1.singleSubject = analysis.group2.fit.d1;\n analysis.group2.c1.groupMean = mean(analysis.group2.fit.c1);\n analysis.group2.c1.singleSubject = analysis.group2.fit.c1;\n \n % Calculate average confidence, add filter number and accuracy to results for group 1\n for n = 1:length(analysis.group1.data)\n analysis.group1.avgConfidence.singleSubject(n) = mean(analysis.group1.data(n).results.thresholdTrials.confidence);\n analysis.group1.filterNum.singleSubject(n) = mean(analysis.group1.data(n).results.thresholdTrials.filterNum);\n analysis.group1.accuracy.singleSubject(n) = analysis.group1.data(n).results.thresholdTrials.accuracyTotal;\n end\n analysis.group1.avgConfidence.groupMean = mean(analysis.group1.avgConfidence.singleSubject);\n analysis.group1.filterNum.groupMean = mean(analysis.group1.filterNum.singleSubject);\n analysis.group1.accuracy.groupMean = mean(analysis.group1.accuracy.singleSubject);\n \n % Calculate average confidence, add filter number and accuracy to results for group 2\n for n = 1:length(analysis.group2.data)\n analysis.group2.avgConfidence.singleSubject(n) = mean(analysis.group2.data(n).results.thresholdTrials.confidence);\n analysis.group2.filterNum.singleSubject(n) = mean(analysis.group2.data(n).results.thresholdTrials.filterNum);\n analysis.group2.accuracy.singleSubject(n) = analysis.group2.data(n).results.thresholdTrials.accuracyTotal;\n end\n analysis.group2.avgConfidence.groupMean = mean(analysis.group2.avgConfidence.singleSubject);\n analysis.group2.filterNum.groupMean = mean(analysis.group2.filterNum.singleSubject);\n analysis.group2.accuracy.groupMean = mean(analysis.group2.accuracy.singleSubject);\n \n % Calculate group difference values for all non-hierarchical metrics\n analysis.groupDiff.filterNum.meanDiff = analysis.group1.filterNum.groupMean - analysis.group2.filterNum.groupMean;\n analysis.groupDiff.accuracy.meanDiff = analysis.group1.accuracy.groupMean - analysis.group2.accuracy.groupMean;\n analysis.groupDiff.d1.meanDiff = analysis.group1.d1.groupMean - analysis.group2.d1.groupMean;\n analysis.groupDiff.c1.meanDiff = analysis.group1.c1.groupMean - analysis.group2.c1.groupMean;\n analysis.groupDiff.avgConfidence.meanDiff = analysis.group1.avgConfidence.groupMean - analysis.group2.avgConfidence.groupMean;\n\n % Run specified statistical test on all non-hierarchical metrics\n if strcmp(analysis.groupDiff.test,'wilcoxon') == 1\n analysis.groupDiff.testType = 'Wilcoxon rank sum test';\n [analysis.groupDiff.filterNum.p,analysis.groupDiff.filterNum.h,analysis.groupDiff.filterNum.stats] = ranksum(analysis.group1.filterNum.singleSubject,analysis.group2.filterNum.singleSubject);\n [analysis.groupDiff.accuracy.p,analysis.groupDiff.accuracy.h,analysis.groupDiff.accuracy.stats] = ranksum(analysis.group1.accuracy.singleSubject,analysis.group2.accuracy.singleSubject);\n [analysis.groupDiff.d1.p,analysis.groupDiff.d1.h,analysis.groupDiff.d1.stats] = ranksum(analysis.group1.d1.singleSubject,analysis.group2.d1.singleSubject);\n [analysis.groupDiff.c1.p,analysis.groupDiff.c1.h,analysis.groupDiff.c1.stats] = ranksum(analysis.group1.c1.singleSubject,analysis.group2.c1.singleSubject);\n [analysis.groupDiff.avgConfidence.p,analysis.groupDiff.avgConfidence.h,analysis.groupDiff.avgConfidence.stats] = ranksum(analysis.group1.avgConfidence.singleSubject,analysis.group2.avgConfidence.singleSubject);\n elseif strcmp(analysis.groupDiff.test,'ttest') == 1\n analysis.groupDiff.testType = 'Unpaired T-test';\n [analysis.groupDiff.filterNum.h,analysis.groupDiff.filterNum.p,analysis.groupDiff.filterNum.ci,analysis.groupDiff.filterNum.stats] = ttest2(analysis.group1.filterNum.singleSubject,analysis.group2.filterNum.singleSubject);\n [analysis.groupDiff.accuracy.h,analysis.groupDiff.accuracy.p,analysis.groupDiff.accuracy.ci,analysis.groupDiff.accuracy.stats] = ttest2(analysis.group1.accuracy.singleSubject,analysis.group2.accuracy.singleSubject);\n [analysis.groupDiff.d1.h,analysis.groupDiff.d1.p,analysis.groupDiff.d1.ci,analysis.groupDiff.d1.stats] = ttest2(analysis.group1.d1.singleSubject,analysis.group2.d1.singleSubject);\n [analysis.groupDiff.c1.h,analysis.groupDiff.c1.p,analysis.groupDiff.c1.ci,analysis.groupDiff.c1.stats] = ttest2(analysis.group1.c1.singleSubject,analysis.group2.c1.singleSubject);\n [analysis.groupDiff.avgConfidence.h,analysis.groupDiff.avgConfidence.p,analysis.groupDiff.avgConfidence.ci,analysis.groupDiff.avgConfidence.stats] = ttest2(analysis.group1.avgConfidence.singleSubject,analysis.group2.avgConfidence.singleSubject);\n end\n \n % Save results\n save(resultsFile, 'analysis'); % Save results\n\n % Create Figure to display results\n figure\n set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 0.6 0.6]);\n labels = ['Group 1'; 'Group 2'];\n % Plot Type 1 metrics on top line\n ax1 = subplot(2,4,1);\n bar(ax1, [analysis.group1.filterNum.groupMean; analysis.group2.filterNum.groupMean]);\n hold on\n errorbar(ax1, [analysis.group1.filterNum.groupMean; analysis.group2.filterNum.groupMean], [std(analysis.group1.filterNum.singleSubject), std(analysis.group2.filterNum.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.groupDiff.filterNum.h == 0\n title('FILTER NUMBER: NON-SIG DIFF')\n elseif analysis.groupDiff.filterNum.h > 0\n title('FILTER NUMBER: SIG DIFF')\n end\n hold off\n ax2 = subplot(2,4,2);\n bar(ax2, [analysis.group1.accuracy.groupMean; analysis.group2.accuracy.groupMean]);\n hold on\n errorbar(ax2, [analysis.group1.accuracy.groupMean; analysis.group2.accuracy.groupMean], [std(analysis.group1.accuracy.singleSubject), std(analysis.group2.accuracy.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.groupDiff.accuracy.h == 0\n title('ACCURACY: NON-SIG DIFF')\n elseif analysis.groupDiff.accuracy.h > 0\n title('ACCURACY: SIG DIFF')\n end\n ax3 = subplot(2,4,3);\n bar(ax3, [analysis.group1.d1.groupMean; analysis.group2.d1.groupMean]);\n hold on\n errorbar(ax3, [analysis.group1.d1.groupMean; analysis.group2.d1.groupMean], [std(analysis.group1.d1.singleSubject), std(analysis.group2.d1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.groupDiff.d1.h == 0\n title('d'': NON-SIG DIFF')\n elseif analysis.groupDiff.d1.h > 0\n title('d'': SIG DIFF')\n end\n hold off\n ax4 = subplot(2,4,4);\n bar(ax4, [analysis.group1.c1.groupMean; analysis.group2.c1.groupMean]);\n hold on\n errorbar(ax4, [analysis.group1.c1.groupMean; analysis.group2.c1.groupMean], [std(analysis.group1.c1.singleSubject), std(analysis.group2.c1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.groupDiff.c1.h == 0\n title('CRITERION: NON-SIG DIFF')\n elseif analysis.groupDiff.c1.h > 0\n title('CRITERION: SIG DIFF')\n end\n hold off\n % Plot group Mratio and the difference\n ax5 = subplot(2,4,5);\n histogram(ax5, exp(analysis.group1.fit.mcmc.samples.mu_logMratio))\n xlim([0 2])\n xlabel('MRatio');\n ylabel('Sample count');\n hold on\n histogram(ax5, exp(analysis.group2.fit.mcmc.samples.mu_logMratio))\n hold off\n lgd = legend('Group 1', 'Group 2', 'Location', 'northeast');\n lgd.FontSize = 10;\n if (analysis.groupDiff.Mratio.hdi(1) > 0 && analysis.groupDiff.Mratio.hdi(2) > 0) || (analysis.groupDiff.Mratio.hdi(1) < 0 && analysis.groupDiff.Mratio.hdi(2) < 0)\n title('MRATIO: SIG DIFF')\n else\n title('MRATIO: NON-SIG DIFF')\n end\n ax6 = subplot(2,4,6);\n histogram(ax6, analysis.group1.fit.mcmc.samples.mu_logMratio)\n xlabel('log(MRatio)');\n ylabel('Sample count');\n hold on\n histogram(ax6, analysis.group2.fit.mcmc.samples.mu_logMratio)\n hold off\n lgd = legend('Group 1', 'Group 2', 'Location', 'northwest');\n lgd.FontSize = 10;\n if (analysis.groupDiff.log_Mratio.hdi(1) > 0 && analysis.groupDiff.log_Mratio.hdi(2) > 0) || (analysis.groupDiff.log_Mratio.hdi(1) < 0 && analysis.groupDiff.log_Mratio.hdi(2) < 0)\n title('LOG(MRATIO): SIG DIFF')\n else\n title('LOG(MRATIO): NON-SIG DIFF')\n end\n ax7 = subplot(2,4,7);\n histogram(ax7, analysis.groupDiff.log_Mratio.sampleDiff)\n xlabel('log(MRatio)');\n ylabel('Sample count');\n if (analysis.groupDiff.log_Mratio.hdi(1) > 0 && analysis.groupDiff.log_Mratio.hdi(2) > 0) || (analysis.groupDiff.log_Mratio.hdi(1) < 0 && analysis.groupDiff.log_Mratio.hdi(2) < 0)\n title('LOG(MRATIO) DIFF: SIG DIFF')\n else\n title('LOG(MRATIO) DIFF: NON-SIG DIFF')\n end\n hold on\n ln2 = line([analysis.groupDiff.log_Mratio.hdi(1) analysis.groupDiff.log_Mratio.hdi(1)], [0 1800]);\n ln2.Color = 'r';\n ln2.LineWidth = 1.5;\n ln2.LineStyle = '--';\n ln2 = line([analysis.groupDiff.log_Mratio.hdi(2) analysis.groupDiff.log_Mratio.hdi(2)], [0 1800]);\n ln2.Color = 'r';\n ln2.LineWidth = 1.5;\n ln2.LineStyle = '--';\n hold off\n % Plot average confidence\n ax8 = subplot(2,4,8);\n bar(ax8, [analysis.group1.avgConfidence.groupMean; analysis.group2.avgConfidence.groupMean]);\n hold on\n errorbar(ax8, [analysis.group1.avgConfidence.groupMean; analysis.group2.avgConfidence.groupMean], [std(analysis.group1.avgConfidence.singleSubject), std(analysis.group2.avgConfidence.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.groupDiff.avgConfidence.h == 0\n title('CONFIDENCE: NON-SIG DIFF')\n elseif analysis.groupDiff.avgConfidence.h > 0\n title('CONFIDENCE: SIG DIFF')\n end\n hold off\n\n % Print figure\n figureFile = fullfile('analysis', ['filter_task_analysis_', analysis.type]); % Create figure file name\n print(figureFile, '-dtiff');\n\n % Display completion message on screen\n fprintf('\\n________________________________________\\n\\n COMPLETED GROUP DIFFERENCE ANALYSIS\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n fprintf('\\n DIFF MRATIO = %.2f (HDI: %.2f to %.2f)\\n', analysis.groupDiff.Mratio.mean, analysis.groupDiff.Mratio.hdi(1), analysis.groupDiff.Mratio.hdi(2));\n if (analysis.groupDiff.Mratio.hdi(1) > 0 && analysis.groupDiff.Mratio.hdi(2) > 0) || (analysis.groupDiff.Mratio.hdi(1) < 0 && analysis.groupDiff.Mratio.hdi(2) < 0)\n fprintf('HDI DOES NOT SPAN ZERO: MRATIO DIFF SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n else\n fprintf(' HDI SPANS ZERO: MRATIO DIFF NOT SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n end\n fprintf('\\n RESULTS CAN BE FOUND IN: \\n FDT/analysis/\\n________________________________________\\n');\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUN SESSION DIFFERENCE ANALYSIS (PAIRED) IF SPECIFIED\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(analysis.type,'paired') == 1 % If session difference analysis specified\n \n % For two-session difference analysis: Print message about groups being fit together --> t-tests possible on meta-d' metrics\n fprintf('\\nNOTE: Groups are fit using one hierarchical model.\\nFrequentist statistics (such as t-tests) are possible on any metrics involving meta-d''.\\nFrequentist statistics are applied to all type 1 metrics and average confidence values.\\n');\n \n % Specify parameters\n analysis.sessionDiff.mcmc_params = fit_meta_d_params;\n \n % Fit each group using a separate hierarchical Bayesian model\n analysis.sessionDiff.fit = fit_meta_d_mcmc_groupCorr(analysis.trials2counts.nR_S1, analysis.trials2counts.nR_S2, analysis.sessionDiff.mcmc_params);\n \n % Compute HDI of difference for log(meta-d'/d')\n analysis.session1.logMratio.sessionMean = analysis.sessionDiff.fit.mu_logMratio(1);\n analysis.session1.logMratio.singleSubject = log(analysis.sessionDiff.fit.Mratio(:,1));\n analysis.session1.Mratio.sessionMean = exp(analysis.sessionDiff.fit.mu_logMratio(1));\n analysis.session1.Mratio.singleSubject = analysis.sessionDiff.fit.Mratio(:,1);\n analysis.session2.logMratio.sessionMean = analysis.sessionDiff.fit.mu_logMratio(2);\n analysis.session2.logMratio.singleSubject = log(analysis.sessionDiff.fit.Mratio(:,2));\n analysis.session2.Mratio.sessionMean = exp(analysis.sessionDiff.fit.mu_logMratio(2));\n analysis.session2.Mratio.singleSubject = analysis.sessionDiff.fit.Mratio(:,2);\n analysis.sessionDiff.log_Mratio.sampleDiff = analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1) - analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2);\n analysis.sessionDiff.log_Mratio.mean = analysis.session1.logMratio.sessionMean - analysis.session2.logMratio.sessionMean;\n analysis.sessionDiff.log_Mratio.hdi = calc_HDI(analysis.sessionDiff.log_Mratio.sampleDiff(:));\n analysis.sessionDiff.Mratio.mean = exp(analysis.session1.logMratio.sessionMean) - exp(analysis.session2.logMratio.sessionMean);\n analysis.sessionDiff.Mratio.hdi = calc_HDI((exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1)) - exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2))));\n\n % Pull out session mean values for all non-hierarchical metrics\n analysis.session1.d1.sessionMean = mean(analysis.sessionDiff.fit.d1(:,1));\n analysis.session1.d1.singleSubject = analysis.sessionDiff.fit.d1(:,1);\n analysis.session1.c1.sessionMean = mean(analysis.sessionDiff.fit.c1(:,1));\n analysis.session1.c1.singleSubject = analysis.sessionDiff.fit.c1(:,1);\n analysis.session2.d1.sessionMean = mean(analysis.sessionDiff.fit.d1(:,2));\n analysis.session2.d1.singleSubject = analysis.sessionDiff.fit.d1(:,2);\n analysis.session2.c1.sessionMean = mean(analysis.sessionDiff.fit.c1(:,2));\n analysis.session2.c1.singleSubject = analysis.sessionDiff.fit.c1(:,2);\n \n % Calculate average confidence, add filter number and accuracy to results for session 1\n for n = 1:length(analysis.session1.data)\n analysis.session1.avgConfidence.singleSubject(n) = mean(analysis.session1.data(n).results.thresholdTrials.confidence);\n analysis.session1.filterNum.singleSubject(n) = mean(analysis.session1.data(n).results.thresholdTrials.filterNum);\n analysis.session1.accuracy.singleSubject(n) = analysis.session1.data(n).results.thresholdTrials.accuracyTotal;\n end\n analysis.session1.avgConfidence.sessionMean = mean(analysis.session1.avgConfidence.singleSubject);\n analysis.session1.filterNum.sessionMean = mean(analysis.session1.filterNum.singleSubject);\n analysis.session1.accuracy.sessionMean = mean(analysis.session1.accuracy.singleSubject);\n \n % Calculate average confidence, add filter number and accuracy to results for session 2\n for n = 1:length(analysis.session2.data)\n analysis.session2.avgConfidence.singleSubject(n) = mean(analysis.session2.data(n).results.thresholdTrials.confidence);\n analysis.session2.filterNum.singleSubject(n) = mean(analysis.session2.data(n).results.thresholdTrials.filterNum);\n analysis.session2.accuracy.singleSubject(n) = analysis.session2.data(n).results.thresholdTrials.accuracyTotal;\n end\n analysis.session2.avgConfidence.sessionMean = mean(analysis.session2.avgConfidence.singleSubject);\n analysis.session2.filterNum.sessionMean = mean(analysis.session2.filterNum.singleSubject);\n analysis.session2.accuracy.sessionMean = mean(analysis.session2.accuracy.singleSubject);\n \n % Calculate session difference values for all non-hierarchical metrics\n analysis.sessionDiff.filterNum.meanDiff = analysis.session1.filterNum.sessionMean - analysis.session2.filterNum.sessionMean;\n analysis.sessionDiff.accuracy.meanDiff = analysis.session1.accuracy.sessionMean - analysis.session2.accuracy.sessionMean;\n analysis.sessionDiff.d1.meanDiff = analysis.session1.d1.sessionMean - analysis.session2.d1.sessionMean;\n analysis.sessionDiff.c1.meanDiff = analysis.session1.c1.sessionMean - analysis.session2.c1.sessionMean;\n analysis.sessionDiff.avgConfidence.meanDiff = analysis.session1.avgConfidence.sessionMean - analysis.session2.avgConfidence.sessionMean;\n\n % Run specified statistical test on all non-hierarchical metrics\n if strcmp(analysis.sessionDiff.test,'wilcoxon') == 1\n analysis.sessionDiff.testType = 'Wilcoxon signed rank test';\n [analysis.sessionDiff.filterNum.p,analysis.sessionDiff.filterNum.h,analysis.sessionDiff.filterNum.stats] = signrank(analysis.session1.filterNum.singleSubject,analysis.session2.filterNum.singleSubject);\n [analysis.sessionDiff.accuracy.p,analysis.sessionDiff.accuracy.h,analysis.sessionDiff.accuracy.stats] = signrank(analysis.session1.accuracy.singleSubject,analysis.session2.accuracy.singleSubject);\n [analysis.sessionDiff.d1.p,analysis.sessionDiff.d1.h,analysis.sessionDiff.d1.stats] = signrank(analysis.session1.d1.singleSubject,analysis.session2.d1.singleSubject);\n [analysis.sessionDiff.c1.p,analysis.sessionDiff.c1.h,analysis.sessionDiff.c1.stats] = signrank(analysis.session1.c1.singleSubject,analysis.session2.c1.singleSubject);\n [analysis.sessionDiff.avgConfidence.p,analysis.sessionDiff.avgConfidence.h,analysis.sessionDiff.avgConfidence.stats] = signrank(analysis.session1.avgConfidence.singleSubject,analysis.session2.avgConfidence.singleSubject);\n elseif strcmp(analysis.sessionDiff.test,'ttest') == 1\n analysis.sessionDiff.testType = 'Paired T-test';\n [analysis.sessionDiff.filterNum.h,analysis.sessionDiff.filterNum.p,analysis.sessionDiff.filterNum.ci,analysis.sessionDiff.filterNum.stats] = ttest(analysis.session1.filterNum.singleSubject,analysis.session2.filterNum.singleSubject);\n [analysis.sessionDiff.accuracy.h,analysis.sessionDiff.accuracy.p,analysis.sessionDiff.accuracy.ci,analysis.sessionDiff.accuracy.stats] = ttest(analysis.session1.accuracy.singleSubject,analysis.session2.accuracy.singleSubject);\n [analysis.sessionDiff.d1.h,analysis.sessionDiff.d1.p,analysis.sessionDiff.d1.ci,analysis.sessionDiff.d1.stats] = ttest(analysis.session1.d1.singleSubject,analysis.session2.d1.singleSubject);\n [analysis.sessionDiff.c1.h,analysis.sessionDiff.c1.p,analysis.sessionDiff.c1.ci,analysis.sessionDiff.c1.stats] = ttest(analysis.session1.c1.singleSubject,analysis.session2.c1.singleSubject);\n [analysis.sessionDiff.avgConfidence.h,analysis.sessionDiff.avgConfidence.p,analysis.sessionDiff.avgConfidence.ci,analysis.sessionDiff.avgConfidence.stats] = ttest(analysis.session1.avgConfidence.singleSubject,analysis.session2.avgConfidence.singleSubject);\n end\n \n % Save results\n save(resultsFile, 'analysis'); % Save results\n\n % Create Figure to display results\n figure\n set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 0.6 0.6]);\n labels = ['Session 1'; 'Session 2'];\n % Plot Type 1 metrics on top line\n ax1 = subplot(2,4,1);\n bar(ax1, [analysis.session1.filterNum.sessionMean; analysis.session2.filterNum.sessionMean]);\n hold on\n errorbar(ax1, [analysis.session1.filterNum.sessionMean; analysis.session2.filterNum.sessionMean], [std(analysis.session1.filterNum.singleSubject), std(analysis.session2.filterNum.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.sessionDiff.filterNum.h == 0\n title('FILTER NUMBER: NON-SIG DIFF')\n elseif analysis.sessionDiff.filterNum.h > 0\n title('FILTER NUMBER: SIG DIFF')\n end\n hold off\n ax2 = subplot(2,4,2);\n bar(ax2, [analysis.session1.accuracy.sessionMean; analysis.session2.accuracy.sessionMean]);\n hold on\n errorbar(ax2, [analysis.session1.accuracy.sessionMean; analysis.session2.accuracy.sessionMean], [std(analysis.session1.accuracy.singleSubject), std(analysis.session2.accuracy.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.sessionDiff.accuracy.h == 0\n title('ACCURACY: NON-SIG DIFF')\n elseif analysis.sessionDiff.accuracy.h > 0\n title('ACCURACY: SIG DIFF')\n end\n ax3 = subplot(2,4,3);\n bar(ax3, [analysis.session1.d1.sessionMean; analysis.session2.d1.sessionMean]);\n hold on\n errorbar(ax3, [analysis.session1.d1.sessionMean; analysis.session2.d1.sessionMean], [std(analysis.session1.d1.singleSubject), std(analysis.session2.d1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.sessionDiff.d1.h == 0\n title('d'': NON-SIG DIFF')\n elseif analysis.sessionDiff.d1.h > 0\n title('d'': SIG DIFF')\n end\n hold off\n ax4 = subplot(2,4,4);\n bar(ax4, [analysis.session1.c1.sessionMean; analysis.session2.c1.sessionMean]);\n hold on\n errorbar(ax4, [analysis.session1.c1.sessionMean; analysis.session2.c1.sessionMean], [std(analysis.session1.c1.singleSubject), std(analysis.session2.c1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.sessionDiff.c1.h == 0\n title('CRITERION: NON-SIG DIFF')\n elseif analysis.sessionDiff.c1.h > 0\n title('CRITERION: SIG DIFF')\n end\n hold off\n % Plot session Mratio and the difference\n ax5 = subplot(2,4,5);\n histogram(ax5, exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1)))\n xlim([0 2])\n xlabel('MRatio');\n ylabel('Sample count');\n hold on\n histogram(ax5, exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2)))\n hold off\n lgd = legend('Session 1', 'Session 2', 'Location', 'northeast');\n lgd.FontSize = 10;\n if (analysis.sessionDiff.Mratio.hdi(1) > 0 && analysis.sessionDiff.Mratio.hdi(2) > 0) || (analysis.sessionDiff.Mratio.hdi(1) < 0 && analysis.sessionDiff.Mratio.hdi(2) < 0)\n title('MRATIO: SIG DIFF')\n else\n title('MRATIO: NON-SIG DIFF')\n end\n ax6 = subplot(2,4,6);\n histogram(ax6, analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1))\n xlabel('log(MRatio)');\n ylabel('Sample count');\n hold on\n histogram(ax6, analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2))\n hold off\n lgd = legend('Session 1', 'Session 2', 'Location', 'northwest');\n lgd.FontSize = 10;\n if (analysis.sessionDiff.log_Mratio.hdi(1) > 0 && analysis.sessionDiff.log_Mratio.hdi(2) > 0) || (analysis.sessionDiff.log_Mratio.hdi(1) < 0 && analysis.sessionDiff.log_Mratio.hdi(2) < 0)\n title('LOG(MRATIO): SIG DIFF')\n else\n title('LOG(MRATIO): NON-SIG DIFF')\n end\n ax7 = subplot(2,4,7);\n histogram(ax7, analysis.sessionDiff.log_Mratio.sampleDiff)\n xlabel('log(MRatio)');\n ylabel('Sample count');\n if (analysis.sessionDiff.log_Mratio.hdi(1) > 0 && analysis.sessionDiff.log_Mratio.hdi(2) > 0) || (analysis.sessionDiff.log_Mratio.hdi(1) < 0 && analysis.sessionDiff.log_Mratio.hdi(2) < 0)\n title('LOG(MRATIO) DIFF: SIG DIFF')\n else\n title('LOG(MRATIO) DIFF: NON-SIG DIFF')\n end\n hold on\n ln2 = line([analysis.sessionDiff.log_Mratio.hdi(1) analysis.sessionDiff.log_Mratio.hdi(1)], [0 1800]);\n ln2.Color = 'r';\n ln2.LineWidth = 1.5;\n ln2.LineStyle = '--';\n ln2 = line([analysis.sessionDiff.log_Mratio.hdi(2) analysis.sessionDiff.log_Mratio.hdi(2)], [0 1800]);\n ln2.Color = 'r';\n ln2.LineWidth = 1.5;\n ln2.LineStyle = '--';\n hold off\n % Plot average confidence\n ax8 = subplot(2,4,8);\n bar(ax8, [analysis.session1.avgConfidence.sessionMean; analysis.session2.avgConfidence.sessionMean]);\n hold on\n errorbar(ax8, [analysis.session1.avgConfidence.sessionMean; analysis.session2.avgConfidence.sessionMean], [std(analysis.session1.avgConfidence.singleSubject), std(analysis.session2.avgConfidence.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');\n set(gca,'XTickLabel',labels);\n set(gca,'XTickLabelRotation',90)\n if analysis.sessionDiff.avgConfidence.h == 0\n title('CONFIDENCE: NON-SIG DIFF')\n elseif analysis.sessionDiff.avgConfidence.h > 0\n title('CONFIDENCE: SIG DIFF')\n end\n hold off\n\n % Print figure\n figureFile = fullfile('analysis', ['filter_task_analysis_', analysis.type]); % Create figure file name\n print(figureFile, '-dtiff');\n\n % Display completion message on screen\n fprintf('\\n________________________________________\\n\\n COMPLETED SESSION DIFFERENCE ANALYSIS\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n fprintf('\\n DIFF MRATIO = %.2f (HDI: %.2f to %.2f)\\n', analysis.sessionDiff.Mratio.mean, analysis.sessionDiff.Mratio.hdi(1), analysis.sessionDiff.Mratio.hdi(2));\n if (analysis.sessionDiff.Mratio.hdi(1) > 0 && analysis.sessionDiff.Mratio.hdi(2) > 0) || (analysis.sessionDiff.Mratio.hdi(1) < 0 && analysis.sessionDiff.Mratio.hdi(2) < 0)\n fprintf('HDI DOES NOT SPAN ZERO: MRATIO DIFF SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n else\n fprintf(' HDI SPANS ZERO: MRATIO DIFF NOT SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n end\n fprintf('\\n RESULTS CAN BE FOUND IN: \\n FDT/analysis/\\n________________________________________\\n');\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUN GROUP REGRESSION ANALYSIS IF SPECIFIED\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(analysis.type,'regress') == 1 % If group regression analysis specified\n \n % Specify parameters\n analysis.groupRegression.mcmc_params = fit_meta_d_params;\n \n % Standardise covariate\n analysis.groupRegression.cov = zscore(analysis.covariate.data);\n\n % Fit group data all at once\n analysis.groupRegression.fit = fit_meta_d_mcmc_regression(analysis.trials2counts.nR_S1, analysis.trials2counts.nR_S2, analysis.groupRegression.cov, analysis.groupRegression.mcmc_params);\n \n % Calculate log of Mratio for single subjects values\n for n = 1:length(analysis.groupRegression.fit.Mratio)\n analysis.groupRegression.log_Mratio.singleSubject(n) = log(analysis.groupRegression.fit.Mratio(n));\n end\n \n % Pull out group and single subject values\n analysis.groupRegression.d1.groupMean = mean(analysis.groupRegression.fit.d1);\n analysis.groupRegression.d1.singleSubject = analysis.groupRegression.fit.d1;\n analysis.groupRegression.c1.groupMean = mean(analysis.groupRegression.fit.c1);\n analysis.groupRegression.c1.singleSubject = analysis.groupRegression.fit.c1;\n analysis.groupRegression.meta_d.groupMean = mean(analysis.groupRegression.fit.meta_d);\n analysis.groupRegression.meta_d.singleSubject = analysis.groupRegression.fit.meta_d;\n analysis.groupRegression.Mratio.groupMean = exp(analysis.groupRegression.fit.mu_logMratio);\n analysis.groupRegression.Mratio.singleSubject = analysis.groupRegression.fit.Mratio;\n analysis.groupRegression.Mratio.hdi = calc_HDI(exp(analysis.groupRegression.fit.mcmc.samples.mu_logMratio(:)));\n analysis.groupRegression.log_Mratio.groupMean = analysis.groupRegression.fit.mu_logMratio;\n analysis.groupRegression.log_Mratio.hdi = calc_HDI(analysis.groupRegression.fit.mcmc.samples.mu_logMratio(:));\n analysis.groupRegression.beta1.groupMean = analysis.groupRegression.fit.mu_beta1;\n analysis.groupRegression.beta1.hdi = calc_HDI(analysis.groupRegression.fit.mcmc.samples.mu_beta1(:));\n \n % Calculate average confidence, add filter number and accuracy to analysis results\n for n = 1:length(analysis.data)\n analysis.groupRegression.avgConfidence.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.confidence);\n analysis.groupRegression.filterNum.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.filterNum);\n analysis.groupRegression.accuracy.singleSubject(n) = analysis.data(n).results.thresholdTrials.accuracyTotal;\n end\n analysis.groupRegression.avgConfidence.groupMean = mean(analysis.groupRegression.avgConfidence.singleSubject);\n analysis.groupRegression.filterNum.groupMean = mean(analysis.groupRegression.filterNum.singleSubject);\n analysis.groupRegression.accuracy.groupMean = mean(analysis.groupRegression.accuracy.singleSubject);\n \n % Save results\n save(resultsFile, 'analysis'); % Save results\n \n % Display completion message on screen plus results\n fprintf('\\n________________________________________\\n\\n COMPLETED GROUP REGRESSION ANALYSIS\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n fprintf('\\n GROUP MRATIO = %.2f (HDI: %.2f to %.2f)\\n', analysis.groupRegression.Mratio.groupMean, analysis.groupRegression.Mratio.hdi(1), analysis.groupRegression.Mratio.hdi(2));\n if analysis.groupRegression.Mratio.hdi(1) > 0\n fprintf(' HDI DOES NOT SPAN ZERO: MRATIO SIG.\\n');\n else\n fprintf(' HDI SPANS ZERO: MRATIO NOT SIG.\\n');\n end\n fprintf('\\n GROUP BETA = %.2f (HDI: %.2f to %.2f)\\n', analysis.groupRegression.beta1.groupMean, analysis.groupRegression.beta1.hdi(1), analysis.groupRegression.beta1.hdi(2));\n if analysis.groupRegression.beta1.hdi(1) > 0\n fprintf(' HDI DOES NOT SPAN ZERO: BETA SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n else\n fprintf(' HDI SPANS ZERO: BETA NOT SIG.\\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\\n');\n end\n fprintf('\\n RESULTS CAN BE FOUND IN: \\n FDT/analysis/\\n________________________________________\\n');\n \nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/task/FDT/scripts/tapas_filter_detection_analysis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3804062807457142}} {"text": "function [model,output] = normalizeExponentialCone(model)\n\n% N.B: YALMIP Definition % x2*exp(x1/x2) <= x3\n\n% Temporarily extract the data in a more standard name min c'*y, b + Ay >= 0\noutput.problem = 0;\nif ~isempty(model.evalMap)\n\n % Temporarily extract the data in a more standard name min c'*y, b + Ay >= 0 \n data.A = model.F_struc(:,2:end); \n data.b = full(model.F_struc(:,1));\n data.c = full(model.c);\n cones = model.K;\n % Clear away the SDP cone to easier add new rows. Will be put back in\n % place later\n data.A(end-sum(model.K.s.^2)+1:end,:)=[];\n data.b(end-sum(model.K.s.^2)+1:end) = [];\n sdpData = model.F_struc(end-sum(model.K.s.^2)+1:end,:);\n \n % First check that we have only exponentials\n convexFunctions = [];\n concaveFunctions = [];\n vectorentropy = [];\n vectorkullback = [];\n vectorlogsumexp = [];\n for i = 1:length(model.evalMap)\n switch model.evalMap{i}.fcn\n case {'exp','pexp'}\n convexFunctions = [convexFunctions model.evalMap{i}.computes];\n case {'log','plog','slog'}\n concaveFunctions = [concaveFunctions model.evalMap{i}.computes];\n case 'entropy'\n concaveFunctions = [concaveFunctions model.evalMap{i}.computes];\n if length(model.evalMap{i}.variableIndex) > 1\n vectorentropy = [vectorentropy i];\n end\n case 'kullbackleibler'\n convexFunctions = [convexFunctions model.evalMap{i}.computes];\n if length(model.evalMap{i}.variableIndex) > 2\n vectorkullback = [vectorkullback i];\n end\n case 'logsumexp'\n convexFunctions = [convexFunctions model.evalMap{i}.computes];\n vectorlogsumexp = [vectorlogsumexp i];\n otherwise\n % Standard interface, return solver not applicable\n % This should not be able to happen as we check this\n % earlier\n output = createoutput([],[],[],-4,model.solver.tag,[],[],0);\n return\n end\n end\n % Check that all exp/log enter in a convex fashion\n if model.K.f > 0\n if nnz(data.A(1:model.K.f,convexFunctions))>0 || nnz(data.A(1:model.K.f,concaveFunctions))>0\n output = createoutput([],[],[],19,model.solver.tag,[],[],0);\n return\n end\n end\n % Check sign in objective on exp/log terms\n if any(data.c(convexFunctions) < 0) || any(data.c(concaveFunctions) > 0)\n output = createoutput([],[],[],19,model.solver.tag,[],[],0);\n return\n end\n % Check sign in elementwise inequalities on exp/log terms\n if model.K.l > 0\n if nnz(data.A(1+model.K.f:model.K.f+model.K.l,convexFunctions)>0) || nnz(data.A(1+model.K.f:model.K.f+model.K.l,concaveFunctions)<0)\n output = createoutput([],[],[],19,model.solver.tag,[],[],0);\n return\n end\n end\n % Check so there are no exp/log terms in quadratic or SDP cone\n if sum(model.K.q) + sum(model.K.s) > 0\n if nnz(data.A(1+model.K.f+model.K.l:end,convexFunctions))>0 || nnz(data.A(1+model.K.f+model.K.l:end,concaveFunctions))>0\n output = createoutput([],[],[],19,model.solver.tag,[],[],0);\n return\n end\n end\n % Scalarize entropy operator\n if ~isempty(vectorentropy)\n for i = vectorentropy(:)'\n involved = model.evalMap{i}.variableIndex;\n computes = model.evalMap{i}.computes;\n n = length(data.c);\n m = length(involved);\n data.A = [sparse(ones(1,m+1),[computes n+(1:m)],[-1 ones(1,m)],1,n+m);\n data.A spalloc(size(data.A,1),m,0)];\n data.b = [0;data.b];\n data.c = [data.c;zeros(m,1)];\n cones.f = cones.f + 1;\n % The original strucuture now just relates to the first new term\n model.evalMap{i}.computes = n+1;\n model.evalMap{i}.variableIndex = involved(1);\n % and then we add some\n for j = 2:length(involved)\n model.evalMap{end+1} = model.evalMap{i};\n model.evalMap{end}.variableIndex = involved(j);\n model.evalMap{end}.computes = n+j;\n end\n end\n end\n \n % Scalarize kullbackleibler operator\n if ~isempty(vectorkullback)\n for i = vectorkullback(:)'\n involved = model.evalMap{i}.variableIndex;\n computes = model.evalMap{i}.computes;\n n = length(data.c);\n m = length(involved)/2;\n data.A = [sparse(ones(1,m+1),[computes n+(1:m)],[-1 ones(1,m)],1,n+m);\n data.A spalloc(size(data.A,1),m,0)];\n data.b = [0;data.b];\n data.c = [data.c;zeros(m,1)];\n cones.f = cones.f + 1;\n % The original strucuture now just relates to the first new term\n model.evalMap{i}.computes = n+1;\n model.evalMap{i}.variableIndex = involved([1 m+1]);\n % and then we add some\n for j = 2:length(involved)/2\n model.evalMap{end+1} = model.evalMap{i};\n model.evalMap{end}.variableIndex = involved([j j+m]);\n model.evalMap{end}.computes = n+j;\n end\n end\n end\n \n % Scalarize logsumexp operator\n % write log(expx1+expx2..)<= z as exp(x1-z)+exp(x2-z)+...<=1\n if ~isempty(vectorlogsumexp)\n for i = vectorlogsumexp(:)'\n involved = model.evalMap{i}.variableIndex;\n computes = model.evalMap{i}.computes;\n % Orignal #variables\n n = length(data.c);\n % Number of terms in logsumexp\n m = length(involved);\n \n % exp(x1-z)+exp(x2-z)+...<=1\n data.A = [data.A(1:cones.f,:) spalloc(cones.f,m,0);\n spalloc(1,n,0) -ones(1,m);\n data.A(cones.f+1:end,:) spalloc(cones.l+sum(cones.q)+sum(cones.s),m,0)];\n data.b = [data.b(1:cones.f);\n 1;\n data.b(cones.f+1:end)];\n data.c = [data.c;zeros(m,1)];\n cones.l = cones.l + 1;\n \n % The original strucuture now just relates to the first new term\n model.evalMap{i}.computes = n+1;\n model.evalMap{i}.variableIndex = [involved(1) computes];\n model.evalMap{i}.fcn = 'expdiff';\n % and then we add some new\n for j = 2:length(involved)\n model.evalMap{end+1} = model.evalMap{i};\n model.evalMap{end}.variableIndex = [involved(j) computes];\n model.evalMap{end}.computes = n+j;\n end\n end\n end\n \n % Describe all exponential cones\n m = length(model.evalMap);\n cones.e = model.K.e + m; \n for i = 1:m\n switch model.evalMap{i}.fcn\n case 'exp'\n % 1*exp(xv/1) <= xc\n % y*exp(x/y) <= z. y new variable, xv the original variable, and xc the \"computed\"\n x = model.evalMap{i}.variableIndex;\n z = model.evalMap{i}.computes;\n data.A = [data.A;\n -sparse([1;3],[x z],-1,3,size(data.A,2))];\n data.b = [data.b;[0;1;0]];\n case 'pexp'\n % xv(1)*exp(xv(2)/xv(1)) <= xc\n x = model.evalMap{i}.variableIndex(2);\n y = model.evalMap{i}.variableIndex(1);\n z = model.evalMap{i}.computes;\n data.A = [data.A;\n -sparse([1;2;3],[x y z],[-1 -1 -1],3,size(data.A,2))];\n data.b = [data.b;[0;0;0]];\n case 'log'\n % log(xv) >= xc i.e. xv >= exp(xc/1)*1\n z = model.evalMap{i}.variableIndex;\n x = model.evalMap{i}.computes;\n data.A = [data.A;\n -sparse([1;3],[x z],-1,3,size(data.A,2))];\n data.b = [data.b;[0;1;0]];\n case 'plog'\n % xv(1)log(xv(2)/xv(1))>=xc i.e.\n % -xc >= -xv(1)log(xv(2)/xv(1))\n z = model.evalMap{i}.computes;\n y = model.evalMap{i}.variableIndex(1);\n x = model.evalMap{i}.variableIndex(2);\n data.A = [data.A;\n -sparse([1;2;3],[x y z],[1 -1 1],3,size(data.A,2))];\n data.b = [data.b;[0;0;0]];\n case 'slog'\n % log(1+xv) >= xc i.e. (1+xv) >= exp(xc/1)*1\n z = model.evalMap{i}.variableIndex;\n x = model.evalMap{i}.computes;\n data.A = [data.A;\n -sparse([1;3],[x z],-1,3,size(data.A,2))];\n data.b = [data.b;0;1;1];\n case 'entropy'\n % -xv*log(xv)>=xc i.e. 1 >= exp(xc/xv)*xv\n x = model.evalMap{i}.computes;\n y = model.evalMap{i}.variableIndex;\n data.A = [data.A;\n -sparse([1;2],[x y],[-1 -1],3,size(data.A,2))];\n data.b = [data.b;[0;0;1]];\n case 'kullbackleibler'\n % -xv1*log(xv1/xv2)>=-xc i.e. xv2 >= exp(-xc/xv1)*xv1\n x = model.evalMap{i}.computes;\n y = model.evalMap{i}.variableIndex(1);\n z = model.evalMap{i}.variableIndex(2);\n data.A = [data.A;\n -sparse([1;2;3],[x y z],[1 -1 -1],3,size(data.A,2))];\n data.b = [data.b;[0;0;0]];\n case 'expdiff'\n % exp(xv(1)-xv(2)) <= xc\n x = model.evalMap{i}.variableIndex;\n z = model.evalMap{i}.computes;\n data.A = [data.A;\n -sparse([1;1;3],[x(1) x(2) z],[-1 1 -1],3,size(data.A,2))];\n data.b = [data.b;[0;1;0]];\n otherwise\n end\n end\n model.F_struc = [data.b data.A];\n model.c = data.c;\n model.K = cones; \n % Put back the SDP cone in place\n if model.K.s(1)>0\n if size(sdpData,2) < size(model.F_struc,2)\n sdpDAta(end,size(model.F_struc,2)) = 0;\n end\n model.F_struc = [model.F_struc;sdpData];\n end\nend\nn = size(model.F_struc,2)-1;\nif n > length(model.lb)\n missing = n - length(model.lb);\n model.lb = [model.lb;-inf(missing,1)];\nend\nif size(model.F_struc,2)-1 > length(model.ub)\n missing = n - length(model.ub);\n model.ub = [model.ub;inf(missing,1)];\nend\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/normalizeExponentialCone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.38039537419950353}} {"text": "function F = coth(F, varargin)\n%COTH Hyperbolic cotangent of a CHEBFUN.\n% COTH(F) computes the hyperbolic cotangent of the CHEBFUN F.\n%\n% COTH(F, PREF) does the same but uses the CHEBFUNPREF object PREF when\n% computing the composition.\n%\n% See also ACOTH.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Call the compose method:\nF = compose(F, @coth, varargin{:});\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/@chebfun/coth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3802330471900902}} {"text": "function f = restrict(f, dom)\n% RESTRICT Restrict the domain of a CHEBFUN3.\n%\n% F = RESTRICT(F, DOM) returns a \n% - CHEBFUN3 on the domain DOM that approximates F on that domain if DOM \n% is a nondegenarate cuboid,\n% - CHEBFUN2 that approximates F on the domain if DOM is a plane, and\n% - CHEBFUN that approximates F on the domain if DOM is a line.\n% DOM should be a vector of length 6 specifying the underlying cuboid.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isa(dom, 'double') )\n if ( numel(dom) == 6 ) % Restrict to DOM. \n xlen = diff(dom(1:2));\n ylen = diff(dom(3:4));\n zlen = diff(dom(5:6));\n \n if ( ( xlen == 0 ) && ( ylen == 0) && ( zlen == 0 ) ) \n % DOM is a point.\n f = feval(f, dom(1), dom(3), dom(5));\n \n elseif ( ( xlen ~= 0 ) && ( ylen == 0 ) && ( zlen == 0 ) )\n % DOM is a vertical line (corresponding to a column).\n cols = restrict(f.cols, dom(1:2));\n rows = feval(f.rows, dom(3));\n tubes = feval(f.tubes, dom(5));\n core = chebfun3.txm(chebfun3.txm(f.core, rows, 2), tubes, 3);\n f = chebfun(cols*core);\n \n elseif ( ( xlen == 0 ) && ( ylen ~= 0 ) && ( zlen == 0 ) )\n % DOM is a horizontal line (corresponding to a row).\n cols = feval(f.cols, dom(1));\n rows = restrict(f.rows, dom(3:4));\n tubes = feval(f.tubes, dom(5));\n core = chebfun3.txm(chebfun3.txm(f.core, cols, 1), tubes, 3);\n f = chebfun(rows*core.');\n \n elseif ( ( xlen == 0 ) && ( ylen == 0 ) && ( zlen ~= 0 ) )\n % DOM is an oblique line (corresponding to a tube).\n cols = feval(f.cols, dom(1));\n rows = feval(f.rows, dom(3));\n tubes = restrict(f.tubes, dom(5:6));\n core = squeeze(chebfun3.txm(chebfun3.txm(f.core, cols, 1), ...\n rows, 2));\n f = chebfun(tubes*core);\n \n elseif ( ( xlen == 0 ) && ( ylen ~= 0 ) && ( zlen ~= 0 ) )\n % DOM is a horizontal plane (corresponding to a horizontal slice).\n cols = feval(f.cols, dom(1));\n rows = restrict(f.rows, dom(3:4));\n tubes = restrict(f.tubes, dom(5:6));\n core = squeeze(chebfun3.txm(f.core, cols, 1));\n f = chebfun2(tubes*core.'*rows.');\n \n elseif ( ( xlen ~= 0 ) && ( ylen == 0 ) && ( zlen ~= 0 ) )\n % DOM is a lateral plane (corresponding to a lateral slice).\n cols = restrict(f.cols, dom(1:2));\n rows = feval(f.rows, dom(3));\n tubes = restrict(f.tubes, dom(5:6));\n core = squeeze(chebfun3.txm(f.core, rows, 2));\n f = chebfun2(tubes*core.'*cols.');\n \n elseif ( ( xlen ~= 0 ) && ( ylen ~= 0 ) && ( zlen == 0 ) )\n % DOM is a frontal plane (corresponding to a frontal slice).\n cols = restrict(f.cols, dom(1:2));\n rows = restrict(f.rows, dom(3:4));\n tubes = feval(f.tubes,dom(5));\n core = chebfun3.txm(f.core, tubes, 3);\n f = chebfun2(rows*core.'*cols.');\n \n else\n % DOM is not degenerate\n f.cols = restrict(f.cols, dom(1:2));\n f.rows = restrict(f.rows, dom(3:4));\n f.tubes = restrict(f.tubes, dom(5:6));\n f.domain = dom;\n end\n else\n error('CHEBFUN:CHEBFUN3:restrict:domain', 'Domain not determined.');\n end\n \nelse\n error('CHEBFUN:CHEBFUN3:restrict:domain', 'Unrecognizable domain.');\nend\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/@chebfun3/restrict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3801654578357938}} {"text": "function f = constructor(f, op, varargin)\n%CONSTRUCTOR Main CHEBFUN3T constructor.\n% Classical full tensor approach for 3D functions. No low-rank technique\n% is involved here. This is experimental code, not for ordinary use.\n%\n% See also CHEBFUN3. \n\n% The 'trig' flag is NOT implemented.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Parse the inputs:\n[op, dom, pref, vectorize] = parseInputs(op, varargin{:});\n\n% Set preferences:\ntech = pref.tech();\ntpref = tech.techPref;\ngrid = tpref.minSamples;\nmaxSample = 363;\n% Since 363*363*363=(6916)^2, this is equivalent to working with a matrix \n% of size 6916 * 6916 which needs 380MB of memory.\npseudoLevel = pref.cheb3Prefs.chebfun3eps; \nprefStruct = pref.cheb2Prefs;\npassSampleTest = prefStruct.sampleTest;\n\n[xx, yy, zz] = ndgrid(dom(1:2), dom(3:4), dom(5:6));\nA = op(xx, yy, zz);\nif ( isscalar(A) )\n op = @(x,y,z) op(x,y,z) + 0*x + 0*y + 0*z;\nend\n\n%%\nisHappy = 0;\nm = grid; n = grid; p = grid;\nfor i=1:10\n %% Compute values at 3D chebpts\n out = tech.tensorGrid([m, n, p], dom);\n xx = out{1};\n yy = out{2};\n zz = out{3};\n F = op(xx,yy,zz);\n \n % Does the function blow up or evaluate to NaN?:\n vscale = max(abs(F(:)));\n if ( isinf(vscale) )\n error('CHEBFUN:CHEBFUN3T:constructor:inf', ...\n 'Function returned INF when evaluated');\n elseif ( any(isnan(F(:)) ) )\n error('CHEBFUN:CHEBFUN3T:constructor:nan', ...\n 'Function returned NaN when evaluated');\n end\n \n %% Call 3D vals2coeffs\n coeffs3D = chebfun3t.vals2coeffs(F);\n % happinessCheck\n [isHappyX, isHappyY, isHappyZ, cutoffX2, cutoffY2, cutoffZ2] = ...\n happinessCheck3D(coeffs3D, pref);\n isHappy = isHappyX & isHappyY & isHappyZ;\n \n %% PHASE II\n % This phase refines the grid ONLY in \"unhappy\" directions.\n % We don't refine here if ALL the directions are nonhappy (as mentioned \n % in the following). If, however, less than 3 directions are nonhappy, \n % we refine in those directions only.\n \n m2 = m; n2 = n; p2 = p;\n while (~isHappy)\n % We need to refine the grid. We refine in 2 different ways: If all\n % 3 directions are unhappy, the new grid is bigger in each\n % direction by a factor of sqrt(2). If 1 or 2 of the directions are\n % unhappy, we refine (only those unhappy directions) by a factor of\n % 2.\n \n if (~isHappyX && ~isHappyY && ~isHappyZ)\n % All directions are unhappy. To avoid getting an unncecessarily\n % big tensor, refine differently.\n break;\n end\n if (~isHappyX)\n m2 = gridRefinePhase2(m2, pref);\n end\n if (~isHappyY)\n n2 = gridRefinePhase2(n2, pref);\n end\n if (~isHappyZ)\n p2 = gridRefinePhase2(p2, pref);\n end\n out = tech.tensorGrid([m2, n2, p2], dom);\n xx = out{1};\n yy = out{2};\n zz = out{3};\n F = op(xx,yy,zz);\n coeffs3D = chebfun3t.vals2coeffs(F);\n [isHappyX, isHappyY, isHappyZ, cutoffX2, cutoffY2, cutoffZ2] = ...\n happinessCheck3D(coeffs3D,pref);\n isHappy = isHappyX & isHappyY & isHappyZ;\n end\n \n if ( isHappy )\n % Chop the tail:\n coeffs3D = coeffs3D(1:cutoffX2, 1:cutoffY2, 1:cutoffZ2);\n \n % Construct a CHEBFUN3T object:\n f.coeffs = coeffs3D;\n f.vscale = max(abs(F(:)));\n f.domain = dom;\n \n % Step 2: Apply a SAMPLETEST:\n [m2, n2, p2] = size(coeffs3D);\n if ( passSampleTest )\n tol2 = getTol3D(xx, yy, zz, F, length(xx), dom, pseudoLevel);\n pass = sampleTest(f, op, tol2, vectorize);\n if ( pass ) % :)\n break\n end \n end\n end\n m = gridRefinePhase1(m);\n n = gridRefinePhase1(n);\n p = gridRefinePhase1(p);\nend\n\n% Reached maximum allowed tensor size and still unhappy?\nif ( i == 10 && ~isHappy )\n % Throw a warning and construct from the latest unhappy approximation\n warning('CHEBFUN:CHEBFUN3T:constructor:notResolved', ...\n 'Unresolved with maximum CHEBFUN3T length: %u.', maxSample);\n f.coeffs = coeffs3D;\n f.vscale = max(abs(F(:)));\n f.domain = dom;\nend\n\nend\n\n%%\nfunction [isHappyX, isHappyY, isHappyZ, cutoffX2, cutoffY2, cutoffZ2] = ...\n happinessCheck3D(simple_3D_coeffs, pref)\n% An alternative technique: check whether all the rows, columns and tubes have been resolved.\n% Somewhat similar to Chebfun2 constructor (but with all the rows, cols and tubes instead of the pivot ones)\n\n% TODO: THIS DOES NOT PROPERLY WORK WITH TRIGs.\n\ncolChebtech = sum(chebfun3t.unfold(abs(simple_3D_coeffs), 1), 2);\nfCol = chebtech2({[], colChebtech});\n[isHappyX, cutoffX2] = happinessCheck(fCol, [], [], [], pref);\n \nrowChebtech = sum(chebfun3t.unfold(abs(simple_3D_coeffs), 2), 2);\nfRow = chebtech2({[], rowChebtech});\n[isHappyY, cutoffY2] = happinessCheck(fRow, [], [], [], pref);\n\ntubeChebtech = sum(chebfun3t.unfold(abs(simple_3D_coeffs), 3), 2);\nfTube = chebtech2({[], tubeChebtech});\n[isHappyZ, cutoffZ2] = happinessCheck(fTube, [], [], [], pref);\nend\n%%\nfunction grid = gridRefinePhase1(grid)\n% Grid refinement strategy in Phase 1. It does the same for all TECHS.\ngrid = floor(sqrt(2)^(floor(2*log2(grid)) + 1)) + 1;\nend\n\n%%\nfunction grid = gridRefinePhase2(grid, pref)\n% Grid refinement strategy for tech in Phase 2 \n\n% What tech am I based on?:\ntech = pref.tech();\n\n% What is the next grid size?\nif ( isa(tech, 'chebtech2') )\n % Double sampling on tensor grid:\n grid = 2*grid-1;\nelseif ( isa(tech, 'trigtech') )\n % Double sampling on tensor grid:\n grid = 2^(floor(log2(grid)+1));\nelseif ( isa(tech, 'chebtech1') )\n grid = 3 * grid;\nelse\n error('CHEBFUN:CHEBFUN3:constructor:gridRefinePhase2:techType', ...\n 'Technology is unrecognized.');\nend\n\nend\n%%\n\nfunction tol = getTol3D(xx, yy, zz, vals, grid, dom, pseudoLevel)\n%See https://github.com/chebfun/chebfun/issues/1491\n[m,n,p] = size(vals);\n% Remove some edge values so that df_dx, df_dy and df_dz have the same size. \ndf_dx = diff(vals(:,1:n-1,1:p-1),1,1) ./ diff(xx(:,1:n-1,1:p-1),1,1); % xx changes in the first mode.\ndf_dy = diff(vals(1:m-1,:,1:p-1),1,2) ./ diff(yy(1:m-1,:,1:p-1),1,2); % yy changes row-wise (2nd mode).\ndf_dz = diff(vals(1:m-1,1:n-1,:),1,3) ./ diff(zz(1:m-1,1:n-1,:),1,3); % zz changes tube-wise (3rd mode).\n\nJ = max(max(abs(df_dx),abs(df_dy)), abs(df_dz));\nJac_norm = max(J(:)); % An approximation for the norm of the Jacobian over the whole domain.\nvscale = max(abs(vals(:)));\ntol = grid^(4/5) * max( abs(dom(:) ) ) * max(Jac_norm, vscale) * pseudoLevel;\nend\n%%\nfunction [op, dom, pref, vectorize] = parseInputs(op, varargin)\nvectorize = 0;\npref = chebfunpref();\n\nif ( isa(op, 'char') ) % CHEBFUN3T( CHAR )\n op = str2op(op);\nend\n\nif nargin == 1\n dom = [-1 1 -1 1 -1 1];\nelseif ( ( (nargin == 2) && ~any(strcmpi(varargin{1}, {'trig', 'periodic'})) )) \n % DOMAIN is specified\n dom = varargin{1};\nelseif ( ( (nargin == 2) && any(strcmpi(varargin{1}, {'trig', 'periodic'})) )) \n % TECH is specified\n pref.tech = @trigtech; \n dom = [-1 1 -1 1 -1 1];\nelseif ( ( (nargin == 3) && any(strcmpi(varargin{2}, {'trig', 'periodic'})) ))\n % DOMAIN and TECH are specified\n dom = varargin{1};\n pref.tech = @trigtech;\nelseif ( ( (nargin == 3) && any(strcmpi(varargin{1}, {'trig', 'periodic'})) ))\n % TECH and DOMAIN are specified\n pref.tech = @trigtech;\n dom = varargin{3};\nelseif ( (nargin == 3) && strcmpi(varargin{1}, 'eps') )\n % EPS is specified\n pref.chebfuneps = varargin{2};\n dom = [-1 1 -1 1 -1 1];\nelseif ( (nargin == 4) && strcmpi(varargin{1}, 'eps') ...\n && any(strcmpi(varargin{3}, {'trig', 'periodic'})) )\n % EPS and TECH are specified\n pref.tech = @trigtech;\n pref.chebfuneps = varargin{3};\n dom = [-1 1 -1 1 -1 1];\nelseif ( (nargin == 4) && strcmpi(varargin{2}, 'eps') && ...\n any(strcmpi(varargin{1}, {'trig', 'periodic'})) )\n % TECH and EPS are specified\n pref.tech = @trigtech;\n pref.chebfuneps = varargin{3};\n dom = [-1 1 -1 1 -1 1];\nelseif ( (nargin == 4) && strcmpi(varargin{2}, 'eps') && ...\n ~any(strcmpi(varargin{1}, {'trig', 'periodic'})) )\n % DOMAIN and EPS are specified\n pref.chebfuneps = varargin{3};\n dom = varargin{1}; \nelseif ( (nargin == 4) && strcmpi(varargin{1}, 'eps') && ...\n ~any(strcmpi(varargin{3}, {'trig', 'periodic'})) )\n % EPS and DOMAIN are specified\n pref.chebfuneps = varargin{2};\n dom = varargin{3};\nelseif ( (nargin == 5) && any(strcmpi(varargin{2}, {'trig', 'periodic'}))...\n && strcmpi(varargin{3}, 'eps') )\n % DOMAIN, TECH and EPS are specified\n dom = varargin{1};\n pref.tech = @trigtech;\n pref.chebfuneps = varargin{4};\nelseif ( (nargin == 5) && strcmpi(varargin{2}, 'eps') ...\n && any(strcmpi(varargin{4}, {'trig', 'periodic'})) )\n % DOMAIN, EPS and TECH are specified\n dom = varargin{1};\n pref.chebfuneps = varargin{3};\n pref.tech = @trigtech;\nelseif ( (nargin == 5) && any(strcmpi(varargin{1}, {'trig', 'periodic'}))...\n && strcmpi(varargin{2}, 'eps') )\n % TECH, EPS and DOMAIN are specified\n pref.tech = @trigtech; \n pref.chebfuneps = varargin{3};\n dom = varargin{4};\nelseif ( (nargin == 5) && any(strcmpi(varargin{1}, {'trig', 'periodic'}))...\n && strcmpi(varargin{3}, 'eps') )\n % TECH, DOMAIN and EPS are specified\n pref.tech = @trigtech; \n dom = varargin{2}; \n pref.chebfuneps = varargin{4};\nelseif ( (nargin == 5) && any(strcmpi(varargin{4}, {'trig', 'periodic'}))...\n && strcmpi(varargin{1}, 'eps') )\n % EPS, DOMAIN and TECH are specified\n pref.chebfuneps = varargin{2};\n dom = varargin{3};\n pref.tech = @trigtech; \nelseif ( (nargin == 5) && any(strcmpi(varargin{3}, {'trig', 'periodic'}))...\n && strcmpi(varargin{1}, 'eps') )\n % EPS, TECH and DOMAIN are specified\n pref.chebfuneps = varargin{2};\n pref.tech = @trigtech;\n dom = varargin{4};\nelse\n error('CHEBFUN:CHEBFUN3T:constructor', ...\n 'Domain not valid or fully determined.');\nend\nend\n%%\nfunction op = str2op( op )\n% OP = STR2OP(OP), finds independent variables in a string and returns an op\n% handle than can be evaluated.\n\nvars = symvar(op); % Independent variables\nif ( numel(vars) > 3)\n error('CHEBFUN:CHEBFUN3T:constructor:str2op:depvars', ...\n 'Too many independent variables in string input.');\nelse\n op = eval(['@(' vars{1} ',' vars{2} ',' vars{3} ')' op]);\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/@chebfun3t/constructor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3798922174358573}} {"text": "% Coupled nonlinear PDE's\n% Buckley Leverett equation\n% dependent variables: pressure and water saturation\n% Prepared for educational purposes by ** AAE **\n% For whatever reason, the code is very slow and does not converge\n% DOES NOT WORK WELL\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\nclc; clear;\n%% define the geometry\nNx = 50; % number of cells in x direction\nNy = 30; % number of cells in y direction\nW = 50; % [m] length of the domain in x direction\nH = 30; % [m] length of the domain in y direction\nx1=linspace(0,W, Nx);\nx2=x1+0.001;\nx=zeros(2*Nx,1);\nj=0;\nfor i=1:Nx\n j=j+1;\n x(j)=x1(i);\n j=j+1;\n x(j)=x2(i);\nend\ny1=linspace(0,H, Ny);\ny2=y1+0.01;\ny=zeros(2*Ny,1);\nj=0;\nfor i=1:Ny\n j=j+1;\n y(j)=y1(i);\n j=j+1;\n y(j)=y2(i);\nend\nm = createMesh2D(x, y); % creates a 2D mesh\n[X,Y]=ndgrid(m.cellsize.x, m.cellsize.y);\n%% define the physical parametrs\np0 = 1e5; % [bar] pressure\npin = 50e5; % [bar] injection pressure at the left boundary\nq_in=5e-5; % [m^3/s] water injection\nsw0 = 0; % initial water saturation\nswin = 1;\nmu_oil = 1e-3; % [Pa.s] oil viscosity\nmu_water = 1e-3; % [Pa.s] water viscosity\n% reservoir\nk0 = 2e-12; % [m^2] average reservoir permeability\nk_frac=100e-12; % [m^2] fracture permeability\nphi0 = 0.2; % average porosity\nclx=0.05;\ncly=0.05;\nV_dp=0.1; % Dykstra-Parsons coef.\nperm_val= field2d(2*Nx,2*Ny,k0,V_dp,clx,cly);\nk=createCellVariable(m, k0);\nfor i=4:2:2*Nx\n k.value(i,3:end-2)=k_frac;\nend\nfor j=4:2:2*Ny\n k.value(3:end-2,j)=k_frac;\nend\nk.value(1:2,:)=k_frac;\nk.value(end-1:end,:)=k_frac;\nk.value(:,1:2)=k_frac;\nk.value(:,end-1:end)=k_frac;\n%k.value(1:2,:)=k_frac;\nphi=createCellVariable(m, phi0);\nkrw0 = 0.4;\nkro0 = 0.8;\nnw = 1;\nno = 1;\nkrw = @(sw)(krw0*sw.^nw);\ndkrwdsw = @(sw)(krw0*nw*sw.^(nw-1));\nkro = @(sw)(kro0*(1-sw).^no);\ndkrodsw = @(sw)(-kro0*no*(1-sw).^(no-1));\nlw = geometricMean(k)/mu_water;\nlo = geometricMean(k)/mu_oil;\nLw = @(sw)(krw(sw));\nLo = @(sw)(k/mu_oil*kro(sw));\ndLwdsw = @(sw)(k/mu_water*dkrwdsw(sw));\ndLodsw = @(sw)(k/mu_oil*dkrodsw(sw));\n%% Define the boundaries\nBCp = createBC(m); % Neumann BC for pressure\nBCs = createBC(m); % Neumann BC for saturation\n% change the right boandary to constant pressure (Dirichlet)\nBCp.right.a(end-5:end)=0; BCp.right.b(end-5:end)=1; BCp.right.c(end-5:end)=p0;\n% change the left boundary to constant flow\nBCp.left.a(1:5)=-k_frac/mu_water; BCp.left.b(1:5)=0; BCp.left.c(1:5)=q_in;\n% change the left boundary to constant saturation (Dirichlet)\nBCs.left.a(1:5)=0; BCs.left.b(1:5)=1; BCs.left.c(1:5)=1;\n%% define the time step and solver properties\ndt = 10; % [s] time step\nt_end = 1000*dt; % [s] final time\neps_p = 1e-5; % pressure accuracy\neps_sw = 1e-5; % saturation accuracy\n%% define the variables\nsw_old = createCellVariable(m, sw0, BCs);\np_old = createCellVariable(m, p0, BCp);\nsw = sw_old;\np = p_old;\nuw = -gradientTerm(p_old); % an estimation of the water velocity\n%% start the main loop\n% generate intial pressure profile (necessary to initialize the fully\n% implicit solver)\n\nt = 0;\nwhile (teps_p) || (error_sw>eps_sw))\n % calculate parameters\n pgrad = gradientTerm(p);\n sw_face = upwindMean(sw, -pgrad); % average value of water saturation\n labdao = lo.*funceval(kro, sw_face);\n labdaw = lw.*funceval(krw, sw_face);\n dlabdaodsw = lo.*funceval(dkrodsw, sw_face);\n dlabdawdsw = lw.*funceval(dkrwdsw, sw_face);\n labda = labdao+labdaw;\n dlabdadsw = dlabdaodsw+dlabdawdsw;\n % compute [Jacobian] matrices\n Mdiffp1 = diffusionTerm(-labda);\n Mdiffp2 = diffusionTerm(-labdaw);\n Mconvsw1 = convectionUpwindTerm(-dlabdadsw.*pgrad);\n Mconvsw2 = convectionUpwindTerm(-dlabdawdsw.*pgrad);\n [Mtranssw2, RHStrans2] = transientTerm(sw_old, dt, phi);\n % Compute RHS values\n RHS1 = divergenceTerm(-dlabdadsw.*sw_face.*pgrad);\n RHS2 = divergenceTerm(-dlabdawdsw.*sw_face.*pgrad);\n % include boundary conditions\n [Mbcp, RHSbcp] = boundaryCondition(BCp);\n [Mbcsw, RHSbcsw] = boundaryCondition(BCs);\n % Couple the equations; BC goes into the block on the main diagonal\n M = [Mdiffp1+Mbcp Mconvsw1; Mdiffp2 Mconvsw2+Mtranssw2+Mbcsw];\n RHS = [RHS1+RHSbcp; RHS2+RHStrans2+RHSbcsw];\n % solve the linear system of equations\n x = M\\RHS;\n % x = agmg(M, RHS, [], 1e-10, 500, [], [p.value(:); sw.value(:)]);\n % separate the variables from the solution\n p_new = reshapeCell(m,full(x(1:(2*Nx+1)*(2*Ny+1))));\n sw_new = reshapeCell(m,full(x((2*Nx+1)*(2*Ny+1)+1:end)));\n % calculate error values\n error_p = max(abs((p_new(:)-p.value(:))./p_new(:)));\n error_sw = max(abs(sw_new(:)-sw.value(:)));\n % assign new values of p and sw\n p.value = p_new;\n sw.value = sw_new;\n end\n t=t+dt;\n p_old = p;\n sw_old = sw;\n figure(1);visualizeCells(sw);shading interp; drawnow;\n sw_tot=sw.value.*X.*Y/(W*H);\n oil_prod=(sum(sum(sw_tot(2:end-1,2:end-1))));\n figure(2);semilogx(t, p_new(2,2), 'o'); drawnow;\nend\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Advanced/BL2Dcoupled_frac_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.37988882080559366}} {"text": "% Like a durational HMM, except we use soft evidence on the observed nodes.\n% Should give the same results as HSMM/test_mgram2.\n\npast = 1;\n% If past=1, P(Yt|Qt=j,Dt=d) = P(y_{t-d+1:t}|j)\n% If past=0, P(Yt|Qt=j,Dt=d) = P(y_{t:t+d-1}|j) - future evidence\n\nwords = {'the', 't', 'h', 'e'};\ndata = 'the';\nnwords = length(words);\nword_len = zeros(1, nwords);\nword_prob = normalise(ones(1,nwords));\nword_logprob = log(word_prob);\nfor wi=1:nwords\n word_len(wi)=length(words{wi});\nend\nD = max(word_len);\n\n\nalphasize = 26*2;\ndata = letter2num(data);\nT = length(data);\n\n% node numbers\nW = 1; % top level state = word id\nL = 2; % bottom level state = letter position within word\nF = 3;\nO = 4;\n\nss = 4;\nintra = zeros(ss,ss);\nintra(W,[F L O])=1;\nintra(L,[O F])=1;\n\ninter = zeros(ss,ss);\ninter(W,W)=1;\ninter(L,L)=1;\ninter(F,[W L O])=1;\n\n% node sizes\nns = zeros(1,ss);\nns(W) = nwords;\nns(L) = D;\nns(F) = 2;\nns(O) = alphasize;\nns2 = [ns ns];\n\n% Make the DBN\nbnet = mk_dbn(intra, inter, ns, 'observed', O);\neclass = bnet.equiv_class;\n\n% uniform start distrib over words, uniform trans mat\nWstart = normalise(ones(1,nwords));\nWtrans = mk_stochastic(ones(nwords,nwords));\n%Wtrans = ones(nwords,nwords);\n\n% always start in state d = length(word) for each bottom level HMM\nLstart = zeros(nwords, D);\nfor i=1:nwords\n l = length(words{i});\n Lstart(i,l)=1;\nend\n\n% make downcounters\nRLtrans = mk_rightleft_transmat(D, 0); % 0 self loop prob\nLtrans = repmat(RLtrans, [1 1 nwords]);\n\n% Finish when downcoutner = 1\nFprob = zeros(nwords, D, 2);\nFprob(:,1,2)=1;\nFprob(:,2:end,1)=1;\n\n\n% Define CPDs for slice 1\nbnet.CPD{eclass(W,1)} = tabular_CPD(bnet, W, 'CPT', Wstart);\nbnet.CPD{eclass(L,1)} = tabular_CPD(bnet, L, 'CPT', Lstart);\nbnet.CPD{eclass(F,1)} = tabular_CPD(bnet, F, 'CPT', Fprob);\n\n\n% Define CPDs for slice 2\nbnet.CPD{eclass(W,2)} = hhmmQ_CPD(bnet, W+ss, 'Fbelow', F, 'startprob', Wstart, 'transprob', Wtrans);\nbnet.CPD{eclass(L,2)} = hhmmQ_CPD(bnet, L+ss, 'Fself', F, 'Qps', W+ss, 'startprob', Lstart, 'transprob', Ltrans);\n\n\nif 0\n% To test it is generating correctly, we create an artificial\n% observation process that capitalizes at the start of a new segment\n% Oprob(Ft-1,Qt,Dt,Yt)\nOprob = zeros(2,nwords,D,alphasize);\nOprob(1,1,3,letter2num('t'),1)=1;\nOprob(1,1,2,letter2num('h'),1)=1;\nOprob(1,1,1,letter2num('e'),1)=1;\nOprob(2,1,3,letter2num('T'),1)=1;\nOprob(2,1,2,letter2num('H'),1)=1;\nOprob(2,1,1,letter2num('E'),1)=1;\nOprob(1,2,1,letter2num('a'),1)=1;\nOprob(2,2,1,letter2num('A'),1)=1;\nOprob(1,3,1,letter2num('b'),1)=1;\nOprob(2,3,1,letter2num('B'),1)=1;\nOprob(1,4,1,letter2num('c'),1)=1;\nOprob(2,4,1,letter2num('C'),1)=1;\n\n% Oprob1(Qt,Dt,Yt)\nOprob1 = zeros(nwords,D,alphasize);\nOprob1(1,3,letter2num('t'),1)=1;\nOprob1(1,2,letter2num('h'),1)=1;\nOprob1(1,1,letter2num('e'),1)=1;\nOprob1(2,1,letter2num('a'),1)=1;\nOprob1(3,1,letter2num('b'),1)=1;\nOprob1(4,1,letter2num('c'),1)=1;\n\nbnet.CPD{eclass(O,2)} = tabular_CPD(bnet, O+ss, 'CPT', Oprob);\nbnet.CPD{eclass(O,1)} = tabular_CPD(bnet, O, 'CPT', Oprob1);\n\nevidence = cell(ss,T);\n%evidence{W,1}=1;\nsample = cell2num(sample_dbn(bnet, 'length', T, 'evidence', evidence));\nstr = num2letter(sample(4,:))\nend\n\n\nif 1\n\n[log_obslik, obslik, match] = mk_mgram_obslik(lower(data), words, word_len, word_prob);\n% obslik(j,t,d)\nsoftCPDpot = cell(ss,T);\nens = ns;\nens(O)=1;\nens2 = [ens ens];\nfor t=2:T\n dom = [F W+ss L+ss O+ss];\n % tab(Ft-1, Q2, Dt)\n tab = ones(2, nwords, D);\n if past\n tab(1,:,:)=1; % if haven't finished previous word, likelihood is 1\n %tab(2,:,:) = squeeze(obslik(:,t,:)); % otherwise likelihood of this segment\n for d=1:min(t,D)\n tab(2,:,d) = squeeze(obslik(:,t,d));\n end\n else\n for d=1:max(1,min(D,T+1-t))\n tab(2,:,d) = squeeze(obslik(:,t+d-1,d));\n end\n end\n softCPDpot{O,t} = dpot(dom, ens2(dom), tab);\nend\nt = 1;\ndom = [W L O];\n% tab(Q2, Dt)\ntab = ones(nwords, D);\nif past\n %tab = squeeze(obslik(:,t,:));\n tab(:,1) = squeeze(obslik(:,t,1));\nelse\n for d=1:min(D,T-t)\n tab(:,d) = squeeze(obslik(:,t+d-1,d));\n end\nend\nsoftCPDpot{O,t} = dpot(dom, ens(dom), tab);\n\n\n%bnet.observed = [];\n% uniformative observations\n%bnet.CPD{eclass(O,2)} = tabular_CPD(bnet, O+ss, 'CPT', mk_stochastic(ones(2,nwords,D,alphasize)));\n%bnet.CPD{eclass(O,1)} = tabular_CPD(bnet, O, 'CPT', mk_stochastic(ones(nwords,D,alphasize)));\n\nengine = jtree_dbn_inf_engine(bnet);\nevidence = cell(ss,T);\n% we add dummy data to O to force its effective size to be 1.\n% The actual values have already been incorporated into softCPDpot \nevidence(O,:) = num2cell(ones(1,T));\n[engine, ll_dbn] = enter_evidence(engine, evidence, 'softCPDpot', softCPDpot);\n\n\n%evidence(F,:) = num2cell(2*ones(1,T));\n%[engine, ll_dbn] = enter_evidence(engine, evidence);\n\n\ngamma = zeros(nwords, T);\nfor t=1:T\n m = marginal_nodes(engine, [W F], t);\n gamma(:,t) = m.T(:,2);\nend\n\ngamma\n\nxidbn = zeros(nwords, nwords);\nfor t=1:T-1\n m = marginal_nodes(engine, [W F W+ss], t);\n xidbn = xidbn + squeeze(m.T(:,2,:));\nend\n\n% thee\n% xidbn(1,4) = 0.9412 the->e\n% (2,3)=0.0588 t->h\n% (3,4)=0.0588 h-e\n% (4,4)=0.0588 e-e\n\n\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/HHMM/Mgram/mgram2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3795367497068784}} {"text": "% Sample codes for the task-related component analysis (TRCA)-based steady\n% -state visual evoked potential (SSVEP) detection method [1]. The filter\n% bank analysis [2] can also be combined to the TRCA-based algorithm.\n%\n% Dataset (sample.mat):\n% A 40-target SSVEP dataset recorded from a single subject. The stimuli\n% were generated by the joint frequency-phase modulation (JFPM) [3]\n% - Stimulus frequencies : 8.0 - 15.8 Hz with an interval of 0.2 Hz\n% - Stimulus phases : 0pi, 0.5pi, 1.0pi, and 1.5pi\n% - # of channels : 9 (1: Pz, 2: PO5,3: PO3, 4: POz, 5: PO4,\n% 6: PO6, 7: O1, 8: Oz, and 9: O2)\n% - # of recording blocks : 6\n% - Data length of epochs : 5 [seconds]\n% - Sampling rate : 250 [Hz]\n%\n% See also:\n% train_trca.m\n% test_trca.m\n% filterbank.m\n% itr.m\n%\n% Reference:\n% [1] M. Nakanishi, Y. Wang, X. Chen, Y.-T. Wang, X. Gao, and T.-P. Jung,\n% \"Enhancing detection of SSVEPs for a high-speed brain speller using\n% task-related component analysis\", \n% IEEE Trans. Biomed. Eng, 65(1): 104-112, 2018.\n% [2] X. Chen, Y. Wang, S. Gao, T. -P. Jung and X. Gao,\n% \"Filter bank canonical correlation analysis for implementing a \n% high-speed SSVEP-based brain-computer interface\",\n% J. Neural Eng., 12: 046008, 2015.\n% [3] X. Chen, Y. Wang, M. Nakanishi, X. Gao, T. -P. Jung, S. Gao,\n% \"High-speed spelling with a noninvasive brain-computer interface\",\n% Proc. Int. Natl. Acad. Sci. U. S. A, 112(44): E6058-6067, 2015.\n%\n% Masaki Nakanishi, 22-Dec-2017\n% Swartz Center for Computational Neuroscience, Institute for Neural\n% Computation, University of California San Diego\n% E-mail: masaki@sccn.ucsd.edu\n\n%% Clear workspace\nclear all\nclose all\nclc\nhelp tutorial_trca\n\n%% Set paths\n\naddpath('../src');\n\n%% Parameter for analysis (Modify according to your analysis)\n\n% Filename\nfilename = '../data/sample.mat';\n\n% Data length for target identification [s]\nlen_gaze_s = 0.5; \n\n% Visual latency being considered in the analysis [s]\nlen_delay_s = 0.13; \n\n% The number of sub-bands in filter bank analysis\nnum_fbs = 5;\n\n% 1 -> The ensemble TRCA-based method, 0 -> The TRCA-based method\nis_ensemble = 0;\n\n% 100*(1-alpha_ci): confidence intervals\nalpha_ci = 0.05; \n\n%% Fixed parameter (Modify according to the experimental setting)\n\n% Sampling rate [Hz]\nfs = 250; \n\n% Duration for gaze shifting [s]\nlen_shift_s = 0.5; \n\n% List of stimulus frequencies\nlist_freqs = [8:1:15 8.2:1:15.2 8.4:1:15.4 8.6:1:15.6 8.8:1:15.8];\n \n% The number of stimuli\nnum_targs = length(list_freqs); \n\n% Labels of data\nlabels = [1:1:num_targs]; \n\n%% Preparing useful variables (DONT'T need to modify)\n\n% Data length [samples]\nlen_gaze_smpl = round(len_gaze_s*fs); \n\n% Visual latency [samples]\nlen_delay_smpl = round(len_delay_s*fs); \n\n% Selection time [s]\nlen_sel_s = len_gaze_s + len_shift_s;\n\n% Confidence interval\nci = 100*(1-alpha_ci); \n\n%% Performing the TRCA-based SSVEP detection algorithm\n\nfprintf('Results of the ensemble TRCA-based method.\\n');\n\n% Preparing data\nload(filename);\n[~, num_chans, ~, num_blocks] = size(eeg);\nsegment_data = len_delay_smpl+1:len_delay_smpl+len_gaze_smpl;\neeg = eeg(:, :, segment_data, :); \n\n% Estimate classification performance\nfor loocv_i = 1:1:num_blocks\n \n % Training stage \n traindata = eeg;\n traindata(:, :, :, loocv_i) = [];\n model = train_trca(traindata, fs, num_fbs);\n \n % Test stage\n testdata = squeeze(eeg(:, :, :, loocv_i));\n estimated = test_trca(testdata, model, is_ensemble);\n \n % Evaluation \n is_correct = (estimated==labels);\n accs(loocv_i) = mean(is_correct)*100;\n itrs(loocv_i) = itr(num_targs, mean(is_correct), len_sel_s);\n fprintf('Trial %d: Accuracy = %2.2f%%, ITR = %2.2f bpm\\n',...\n loocv_i, accs(loocv_i), itrs(loocv_i));\n \nend % loocv_i\n\n% Summarize\n[mu, ~, muci, ~] = normfit(accs, alpha_ci);\nfprintf('Mean accuracy = %2.2f %% (%2d%% CI: %2.2f - %2.2f %%)\\n',...\n mu, ci, muci(1), muci(2));\n\n[mu, ~, muci, ~] = normfit(itrs, alpha_ci);\nfprintf('Mean ITR = %2.2f bpm (%2d%% CI: %2.2f - %2.2f bpm)\\n\\n',...\n mu, ci, muci(1), muci(2));", "meta": {"author": "mnakanishi", "repo": "TRCA-SSVEP", "sha": "c3f7a761fa641c8bad88659f1025171ceec3941e", "save_path": "github-repos/MATLAB/mnakanishi-TRCA-SSVEP", "path": "github-repos/MATLAB/mnakanishi-TRCA-SSVEP/TRCA-SSVEP-c3f7a761fa641c8bad88659f1025171ceec3941e/tutorial/tutorial_trca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3794118528900432}} {"text": "\nfunction [retransformed_irf_estimates]=favar_retransX_irf_estimates(irf_estimates,transformationindex,levels)\n% number of variables and shocks, and iterations (It-Bu)\n[n1,n2]=size(irf_estimates);\nItBu=1;\n% initialise\nretransformed_irf_estimates=cell(size(irf_estimates));\n% different treatment for different cases\nif levels==1 % only cum sum, also for second differences\n for oo=1:n1 % variables\n for ll=1:n2 % shocks\n for ii=1:3 %for up.,median,low.\n if transformationindex(oo)==1 %1: no transformation, Level\n retransformed_irf_estimates{oo,ll}(ii,:)=irf_estimates{oo,ll}(ii,:);\n elseif transformationindex(oo)==2\n retransformed_irf_estimates{oo,ll}(ii,:)=cumsum(irf_estimates{oo,ll}(ii,:),2); %2: First Difference\n% retransformed_irf_estimates{oo,ll}(ii,:)=irf_estimates{oo,ll}(ii,:);\n elseif transformationindex(oo)==3\n %retransformed_irf_record{oo,ll}(ii,:)=cumsum(irf_record{oo,ll}(ii,:),2); %3: Second Difference\n retransformed_irf_estimates{oo,ll}(ii,:)=irf_estimates{oo,ll}(ii,:);\n elseif transformationindex(oo)==4\n %retransformed_irf_record{oo,ll}(ii,:)=irf_record{oo,ll}(ii,:);\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(irf_estimates{oo,ll}(ii,:))-ones(ItBu,1); %4: Log-Level\n elseif transformationindex(oo)==5\n retransformed_irf_estimates{oo,ll}(ii,:)=cumsum(irf_estimates{oo,ll}(ii,:),2); %5: Log-First-Difference\n% retransformed_irf_estimates{oo,ll}(ii,:)=exp(cumsum(irf_estimates{oo,ll}(ii,:),2))-ones(ItBu,1); %5: Log-First-Difference\n elseif transformationindex(oo)==6\n %retransformed_irf_record{oo,ll}(ii,:)=cumsum(irf_record{oo,ll}(ii,:),2); %6: Log-Second-Difference\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(cumsum(irf_estimates{oo,ll}(ii,:),2))-ones(ItBu,1); %5: Log-First-Difference\n end\n end\n end\n end\nelseif levels==2 % exp + cum sum\n for oo=1:n1 % variable\n for ll=1:n2 % shocks\n for ii=1:3 %for up.,median,low.\n if transformationindex(oo)==1 %1: no transformation, Level\n retransformed_irf_estimates{oo,ll}(ii,:)=irf_estimates{oo,ll}(ii,:);\n elseif transformationindex(oo)==2\n retransformed_irf_estimates{oo,ll}(ii,:)=cumsum(irf_estimates{oo,ll}(ii,:),2); %2: First Difference\n elseif transformationindex(oo)==3\n retransformed_irf_estimates{oo,ll}(ii,:)=cumsum(irf_estimates{oo,ll}(ii,:),2); % 6: Second Difference\n elseif transformationindex(oo)==4\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(irf_estimates{oo,ll}(ii,:))-ones(ItBu,1); %4: Log-Level\n elseif transformationindex(oo)==5\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(cumsum(irf_estimates{oo,ll}(ii,:),2))-ones(ItBu,1); %5: Log-First-Difference\n elseif transformationindex(oo)==6\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(cumsum(irf_estimates{oo,ll}(ii,:),2))-ones(ItBu,1); %6: Log-Second-Difference\n end\n end\n end\n end\nelseif levels==3 % exp + cum sum + cum sum for second differences types\n for oo=1:n1 % variables\n for ll=1:n2 % shocks\n for ii=1:3 %for up.,median,low.\n if transformationindex(oo)==1 %1: no transformation, Level\n retransformed_irf_estimates{oo,ll}(ii,:)=irf_estimates{oo,ll}(ii,:);\n elseif transformationindex(oo)==2\n retransformed_irf_estimates{oo,ll}(ii,:)=cumsum(irf_estimates{oo,ll}(ii,:),2); %2: First Difference\n elseif transformationindex(oo)==3\n retransformed_irf_estimates{oo,ll}(ii,:)=cumsum(cumsum(irf_estimates{oo,ll}(ii,:),2),2); % 6: Second Difference\n elseif transformationindex(oo)==4\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(irf_estimates{oo,ll}(ii,:))-ones(ItBu,1); %4: Log-Level\n elseif transformationindex(oo)==5\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(cumsum(irf_estimates{oo,ll}(ii,:),2))-ones(ItBu,1); %5: Log-First-Difference\n elseif transformationindex(oo)==6\n retransformed_irf_estimates{oo,ll}(ii,:)=exp(cumsum(cumsum(irf_estimates{oo,ll}(ii,:),2),2))-ones(ItBu,1); %6: Log-Second-Difference\n end\n end\n end\n end\n \nelse % do nothing, e.g. levels=0\n retransformed_irf_estimates=irf_estimates;\nend\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/favar_retransX_irf_estimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3793950177744489}} {"text": "classdef dislocationSystem\n% class representing dislocation\n%\n% Syntax\n% dS = dislocationSystem(b,l)\n% dS = dislocationSystem(sS)\n%\n% Input\n% b - @Miller Burgers vector\n% l - @Miller line vector\n% sS - @slipSystem\n% pr - poisson ratio\n%\n% Class Properties\n% b - @Miller Burgers vector\n% l - @Miller line vector\n% u - energy\n% CS - @crystalSymmetry\n% isEdge - is edge dislocation\n% isScrew - is screw dislocation\n%\n% See also\n% DislocationSystems SlipSystems GND\n\n properties\n b % burgers vector\n l % line vector\n u % line energy of the dislocation system\n end\n \n properties (Dependent = true)\n CS\n isEdge\n isScrew\n end\n \n methods\n function dS = dislocationSystem(sS,l,u)\n \n if nargin == 0, return; end\n \n % adjust length burger vector edge dislocation a/2\n % for screw dislocations ??\n \n if isa(sS,'slipSystem')\n \n % define edge dislocations\n if sS.CS.lattice == 'hexagonal' %#ok\n dS.b = 1/3 * sS.b; \n elseif sS.CS.lattice == 'cubic' %#ok\n dS.b = 1/2 * sS.b;\n else\n dS.b = sS.b;\n warning('I could not determine the correct length of the Burgers vector. Please adjust it manually.')\n end\n dS.l = cross(sS.b,sS.n);\n \n % define screw dislocations\n b = 0.5*unique(sS.b,'antipodal','noSymmetry');\n dS.b = [dS.b(:);b(:)];\n dS.l = [dS.l(:);b(:)];\n \n % line energy\n dS.u = 1 + dS.isEdge;\n \n else\n \n b = sS;\n omega = angle(b,l,'noSymmetry');\n assert(all(omega > pi/2-1e-5 | omega<1e-5),...\n 'line vector and burgers vector should be either be orthogonal! or identical')\n \n dS.b = sS;\n l.antipodal = true;\n dS.l = l;\n if nargin < 3, u = 1; end\n if numel(u) ~= length(dS.b), u = repmat(u,size(dS.b)); end\n dS.u = u;\n \n end\n \n end\n \n function CS = get.CS(sS)\n if isa(sS.b,'Miller')\n CS = sS.b.CS;\n else\n CS = specimenSymmetry;\n end\n end\n \n function isEdge = get.isEdge(dS)\n isEdge = angle(dS.b,dS.l,'noSymmetry') > pi/2 - 1e-5;\n end\n \n function isScrew = get.isScrew(dS)\n isScrew = angle(dS.b,dS.l,'noSymmetry') < 1e-5;\n end\n \n \n function display(dS,varargin)\n % standard output\n \n displayClass(dS,inputname(1),varargin{:});\n\n % display symmetry\n if isa(dS.CS,'crystalSymmetry')\n if ~isempty(dS.CS.mineral)\n disp([' mineral: ',char(dS.CS,'verbose')]);\n else\n disp([' symmetry: ',char(dS.CS,'verbose')]);\n end\n end\n \n toChar = @(x) char(round(x),'spaceSep');\n \n if any(dS.isEdge(:))\n \n disp([' edge dislocations : ',size2str(submatrix(ones(size(dS)),dS.isEdge))]);\n \n if isa(dS.CS,'crystalSymmetry')\n matrix = [arrayfun(toChar,dS.b(dS.isEdge),'UniformOutput',false),...\n arrayfun(toChar,dS.l(dS.isEdge),'UniformOutput',false),...\n vec2cell(dS.u(dS.isEdge))];\n \n cprintf(matrix,'-L',' ','-Lc',...\n {'Burgers vector' 'line vector' 'energy'},'-d',' ','-ic',true);\n disp(' ');\n \n end\n \n end\n \n if any(dS.isScrew(:))\n\n \n disp([' screw dislocations: ',size2str(submatrix(ones(size(dS)),dS.isScrew))]);\n \n if isa(dS.CS,'crystalSymmetry')\n matrix = [arrayfun(toChar,dS.l(dS.isScrew),'UniformOutput',false),...\n vec2cell(dS.u(dS.isScrew))];\n \n cprintf(matrix,'-L',' ','-Lc',...\n {'Burgers vector' 'energy'},'-d',' ','-ic',true);\n disp(' ');\n end\n end\n\n end\n \n function n = numArgumentsFromSubscript(varargin)\n n = 0;\n end\n \n end\n \n methods (Static = true)\n function dS = fcc(cs,varargin)\n dS = dislocationSystem(symmetrise(slipSystem.fcc(cs),'antipodal'));\n end\n \n function dS = bcc(cs,varargin)\n dS = dislocationSystem(symmetrise(slipSystem.bcc(cs),'antipodal'));\n end\n \n function dS = hcp(cs,varargin)\n dS = dislocationSystem(symmetrise(slipSystem.hcp(cs),'antipodal'));\n end\n \n end\n \nend", "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/geometry/@dislocationSystem/dislocationSystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3792038089785083}} {"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: September 9th, 2016\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 geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Make_Your_Plates_and_Input_Files()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 256; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nLx = 1.0; % Length of Eulerian Grid in x-Direction\ndx = Lx/Nx; % Grid spatial resolution\n\n%\n% Immersed Structure Geometric / Dynamic Parameters %\n%\nds = 0.5*dx; % Lagrangian Pt. Spacing (2x resolution of Eulerian grid)\nstruct_name = 'plates'; % Name for .vertex, .spring, etc files. (must match what's in 'input2d')\n\n\n% Call function to construct geometry\n[xLag,yLag,dist] = give_Me_Immsersed_Boundary_Geometry(ds,Nx,Lx);\n\n\n% Plot Geometry to test\nplot(xLag,yLag,'r-'); hold on;\nplot(xLag,yLag,'*'); hold on;\nxlabel('x'); ylabel('y');\naxis([0 Lx 0 Lx]);\n\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .spring file!\nk_Spring = 2.5e4; % Spring stiffness (does not need to be equal for all springs)\nds_Plates = dist; % Spring resting length (does not need to be equal for all springs)\nprint_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Plates,ds,struct_name);\n\n\n% Prints .beam file!\n% k_Beam = 0.5; % Beam Stiffness (does not need to be equal for all beams)\n% C = compute_Curvatures(xLag,yLag) % Computes curvature of initial configuration\n%print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name);\n\n\n% Prints .target file!\n%k_Target = 1e7;\n%print_Lagrangian_Target_Pts(xLag,k_Target,struct_name);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called 'struct_name'.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag); % Total # of Lag. Pts\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called 'struct_name'.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Plates,ds,struct_name)\n\n N = length(xLag);\n\n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', N-2 + N/2 ); % Print # of springs \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); \n elseif s > N/2\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds); \n end\n end\n \n % SPRINGS ACROSS PLATES\n for s=1:N/2\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+N/2, k_Spring, ds_Plates); \n end\n \n fclose(spring_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints TARGET points to a file called 'struct_name'.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', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\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_name'.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(s) ); \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(s) ); \n end\n end\n fclose(beam_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes \"curvature\" of starting configuration\n% \n% NOTE: not curvature in the traditional geometric sense, in the 'discrete'\n% sense through cross product.\n%\n% NOTE: assumes a CLOSED structure\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = compute_Curvatures(xLag,yLag)\n\nN = length(xLag);\nC = zeros( N );\n\n%Note: needs to be done same order as you print .beam file!\nfor i=1:N\n \n % Pts Xp -> Xq -> Xr (same as beam force calc.)\n \n if ( (i > 1) && (i < N) )\n \n Xp = xLag(i-1); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(i-1); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==1)\n \n Xp = xLag(N); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(N); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==N)\n \n Xp = xLag(N-1); Xq = xLag(N); Xr = xLag(1);\n Yp = yLag(N-1); Yq = yLag(N); Yr = yLag(1);\n \n end\n \n C(i) = (Xr-Xq)*(Yq-Yp) - (Yr-Yq)*(Xq-Xp); %Cross product btwn vectors\n \nend\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \nfunction [xLag,yLag,dist] = give_Me_Immsersed_Boundary_Geometry(ds,Nx,L)\n\n% ds: Lagrangian pt. spacing\n% Nx: Eulerian grid resolution\n% L: Length of computational domain\n\nyLag = 0:ds:L/5; % Make plate of length L/10\nxLag = zeros(1,length(yLag)); % Make corresponding xPts for Vertical Plate\n\n% Translate points\nyLag = yLag + (L/2-L/10); % Translate them symmetrically\n\n% Make sides\nxLag_Left = xLag + (L/2-L/10);\nxLag_Right = xLag + (L/2+L/10);\n\n% Combine Pts Into ONE Vector\nxLag = [xLag_Left xLag_Right];\nyLag = [yLag yLag];\n\n% Distance between plates\ndist = (L/2+L/10) - (L/2-L/10);\n\n% Plot the Geometry\n% plot(xLag,yLag,'*'); hold on;\n% axis([0 L 0 L]);\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/Examples_First_Year_Seminar/Plates/Make_Your_Plates_and_Input_Files.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.37892670316628396}} {"text": "function p05_title ( )\n\n%*****************************************************************************80\n%\n%% P05_TITLE prints a title for problem 05.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% None\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Problem 05\\n' );\n fprintf ( 1, ' Name: ST04\\n' );\n fprintf ( 1, ' Stroud #4, page 26.\\n' );\n fprintf ( 1, ' Region: 0 <= X(i) <= 1\\n' );\n fprintf ( 1, ' Integrand: F(X) = 1 / ( 1 + sum ( 2 * X(i) ) )\\n' );\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/quadrature_test/p05_title.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.3788982359289645}} {"text": "function PlotAdaptiveContour3D(u, levels, tol)\n\n% function PlotAdaptiveContour3D(u, levels, tol)\n% Purpose: adaptively refine the mesh to approximately locate isocontours\n\nGlobals3D;\n\n% build interpolation matrix (coarse->fine)\nEToVi = [1 5 7 8; 5 2 6 9; 7 6 3 10; 8 9 10 4; 8 5 7 9; 7 5 6 9; 8 9 7 10; 9 6 7 10];\nVXi = [-1 1 -1 -1 0 0 -1 -1 0 -1];\nVYi = [-1 -1 1 -1 -1 0 0 -1 -1 0];\nVZi = [-1 -1 -1 1 -1 -1 -1 0 0 0];\n\nv1 = EToVi(:,1); v2 = EToVi(:,2); v3 = EToVi(:,3); v4 = EToVi(:,4);\nri = 0.5*(-(r+s+t+1)*VXi(v1) + (1+r)*VXi(v2) + (1+s)*VXi(v3) + (1+t)*VXi(v4) );\nsi = 0.5*(-(r+s+t+1)*VYi(v1) + (1+r)*VYi(v2) + (1+s)*VYi(v3) + (1+t)*VYi(v4) );\nti = 0.5*(-(r+s+t+1)*VZi(v1) + (1+r)*VZi(v2) + (1+s)*VZi(v3) + (1+t)*VZi(v4) );\n\ninterp = Vandermonde3D(N, ri(:), si(:), ti(:))*invV;\nri = [-1;1;-1;-1]; si = [-1;-1;1;-1]; ti = [-1;-1;-1;1]; refNp = length(ri);\ninterp1 = Vandermonde3D(N, ri(:), si(:), ti(:))*invV;\n\nNlevels = length(levels);\n\nsk = 1;\nF = spalloc(Np,Np,1);\nfor i=0:N % old ordering\n for j=0:N - i\n for k=0:N - i - j\n if(i+j+k<=1), F(sk,sk) = 1.; end;\n sk = sk+1;\n end\n end\nend\n\nhold on;\nfor n=1:Nlevels\n \n xref = x; yref = y; zref = z; uref = u; Kref = K; Jref = J;\n \n err = 1;\n while(err > tol)\n \n level = levels(n);\n \n umin = min(uref, [], 1);\n umax = max(uref, [], 1);\n \n refineflag = (umin <= level & umax >= level);\n \n toref = find( refineflag);\n Nref = length(toref);\n \n uref = reshape(interp*uref(:,toref), Np, 8*Nref);\n xref = reshape(interp*xref(:,toref), Np, 8*Nref);\n yref = reshape(interp*yref(:,toref), Np, 8*Nref);\n zref = reshape(interp*zref(:,toref), Np, 8*Nref);\n Jref = reshape(interp*Jref(:,toref), Np, 8*Nref)/8;\n\n Kref = 8*Nref;\n\n ufilt = V*(F*(invV*uref));\n err = max(max(abs(ufilt-uref)));\n\n end\n \n xref = interp1*xref; yref = interp1*yref; zref = interp1*zref; uref = interp1*uref; \n \n tets = reshape(1:4*Kref, 4, Kref)';\n \n x1 = xref(1,:)'; y1 = yref(1,:)'; z1 = zref(1,:)'; u1 = uref(1,:)' + 1e-10*rand(Kref,1);\n x2 = xref(2,:)'; y2 = yref(2,:)'; z2 = zref(2,:)'; u2 = uref(2,:)' + 1e-10*rand(Kref,1);\n x3 = xref(3,:)'; y3 = yref(3,:)'; z3 = zref(3,:)'; u3 = uref(3,:)' + 1e-10*rand(Kref,1);\n x4 = xref(4,:)'; y4 = yref(4,:)'; z4 = zref(4,:)'; u4 = uref(4,:)' + 1e-10*rand(Kref,1);\n \n trix = []; triy = []; triz = []; triu = [];;\n \n umin = min(uref, [], 1);\n umax = max(uref, [], 1);\n \n lev = levels(n);\n \n % find candidate elements\n ks = find(umin<= lev & umax >= lev);\n \n Nks = length(ks);\n \n if(Nks>0)\n \n fc = zeros(Nks,6);\n \n u1ks = u1(ks); u2ks = u2(ks); u3ks = u3(ks); u4ks = u4(ks);\n \n % find local coordinate at each of 6 edges\n c1 = (lev-u1ks)./(u2ks-u1ks); fc(:,1) = (c1>=0 & c1<=1);\n c2 = (lev-u2ks)./(u3ks-u2ks); fc(:,2) = (c2>=0 & c2<=1);\n c3 = (lev-u3ks)./(u1ks-u3ks); fc(:,3) = (c3>=0 & c3<=1);\n c4 = (lev-u1ks)./(u4ks-u1ks); fc(:,4) = (c4>=0 & c4<=1); \n c5 = (lev-u2ks)./(u4ks-u2ks); fc(:,5) = (c5>=0 & c5<=1); \n c6 = (lev-u3ks)./(u4ks-u3ks); fc(:,6) = (c6>=0 & c6<=1); \n\n % find triangle intersection\n tris = find(sum(fc, 2)==3); Ntris = length(tris); tfc = fc(tris,:); ids = find(tfc');\n ktris = ks(tris);\n \n % trim list\n tc1 = c1(tris); tc2 = c2(tris); tc3 = c3(tris); tc4 = c4(tris); tc5 = c5(tris); tc6 = c6(tris);\n \n tx1 = x1(ktris); ty1 = y1(ktris); tz1 = z1(ktris);\n tx2 = x2(ktris); ty2 = y2(ktris); tz2 = z2(ktris);\n tx3 = x3(ktris); ty3 = y3(ktris); tz3 = z3(ktris);\n tx4 = x4(ktris); ty4 = y4(ktris); tz4 = z4(ktris);\n \n xc = zeros(Ntris, 6); yc = zeros(Ntris, 6); zc = zeros(Ntris, 6);\n xc(:,1) = (1-tc1).*tx1 + tc1.*tx2; yc(:,1) = (1-tc1).*ty1 + tc1.*ty2; zc(:,1) = (1-tc1).*tz1 + tc1.*tz2;\n xc(:,2) = (1-tc2).*tx2 + tc2.*tx3; yc(:,2) = (1-tc2).*ty2 + tc2.*ty3; zc(:,2) = (1-tc2).*tz2 + tc2.*tz3;\n xc(:,3) = (1-tc3).*tx3 + tc3.*tx1; yc(:,3) = (1-tc3).*ty3 + tc3.*ty1; zc(:,3) = (1-tc3).*tz3 + tc3.*tz1;\n xc(:,4) = (1-tc4).*tx1 + tc4.*tx4; yc(:,4) = (1-tc4).*ty1 + tc4.*ty4; zc(:,4) = (1-tc4).*tz1 + tc4.*tz4;\n xc(:,5) = (1-tc5).*tx2 + tc5.*tx4; yc(:,5) = (1-tc5).*ty2 + tc5.*ty4; zc(:,5) = (1-tc5).*tz2 + tc5.*tz4;\n xc(:,6) = (1-tc6).*tx3 + tc6.*tx4; yc(:,6) = (1-tc6).*ty3 + tc6.*ty4; zc(:,6) = (1-tc6).*tz3 + tc6.*tz4;\n xc = xc'; yc = yc'; zc = zc';\n \n ids = reshape(ids, 3, Ntris);\n \n trix = [trix, xc(ids)];\n triy = [triy, yc(ids)];\n triz = [triz, zc(ids)];\n triu = [triu, lev*ones(size(ids))];\n \n % find quadrilateral intersection\n quads = find(sum(fc, 2)==4); Nquads = length(quads); qfc = fc(quads,:); ids = find(qfc');\n kquads = ks(quads);\n \n % quad list\n qc1 = c1(quads); qc2 = c2(quads); qc3 = c3(quads); qc4 = c4(quads); qc5 = c5(quads); qc6 = c6(quads);\n \n qx1 = x1(kquads); qy1 = y1(kquads); qz1 = z1(kquads);\n qx2 = x2(kquads); qy2 = y2(kquads); qz2 = z2(kquads);\n qx3 = x3(kquads); qy3 = y3(kquads); qz3 = z3(kquads);\n qx4 = x4(kquads); qy4 = y4(kquads); qz4 = z4(kquads);\n \n xc = zeros(Nquads, 6); yc = zeros(Nquads, 6); zc = zeros(Nquads, 6);\n xc(:,1) = (1-qc1).*qx1 + qc1.*qx2; yc(:,1) = (1-qc1).*qy1 + qc1.*qy2; zc(:,1) = (1-qc1).*qz1 + qc1.*qz2;\n xc(:,2) = (1-qc2).*qx2 + qc2.*qx3; yc(:,2) = (1-qc2).*qy2 + qc2.*qy3; zc(:,2) = (1-qc2).*qz2 + qc2.*qz3;\n xc(:,3) = (1-qc3).*qx3 + qc3.*qx1; yc(:,3) = (1-qc3).*qy3 + qc3.*qy1; zc(:,3) = (1-qc3).*qz3 + qc3.*qz1;\n xc(:,4) = (1-qc4).*qx1 + qc4.*qx4; yc(:,4) = (1-qc4).*qy1 + qc4.*qy4; zc(:,4) = (1-qc4).*qz1 + qc4.*qz4;\n xc(:,5) = (1-qc5).*qx2 + qc5.*qx4; yc(:,5) = (1-qc5).*qy2 + qc5.*qy4; zc(:,5) = (1-qc5).*qz2 + qc5.*qz4;\n xc(:,6) = (1-qc6).*qx3 + qc6.*qx4; yc(:,6) = (1-qc6).*qy3 + qc6.*qy4; zc(:,6) = (1-qc6).*qz3 + qc6.*qz4;\n xc = xc'; yc = yc'; zc = zc';\n \n ids1 = reshape(ids, 4, Nquads);\n ids2 = ids1([1;4;2;3],:);\n ids3 = ids1([1;3;4;2],:);\n \n % find length perimeters bounded by 4 nodes\n perims1 = QuadPerimeter3D(xc(ids1),yc(ids1),zc(ids1));\n perims2 = QuadPerimeter3D(xc(ids2),yc(ids2),zc(ids2)); \n perims3 = QuadPerimeter3D(xc(ids3),yc(ids3),zc(ids3));\n \n % locate minimum perimeter quad\n idsA = find(perims1)\n% fields Array of structures with information about detected fields.\n% Optional list of property-value pairs (see table below)\n%\n% ==============================================================================================\n% Properties Values\n% ----------------------------------------------------------------------------------------------\n% 'searchWidth' If map is not perfect, but contains NaN values along borders, then\n% search for border pixels can have NaNs. To mitigate this, we check\n% searchWidth rows/columns near border and if the closest to the border pixel\n% equals to NaN, we search for first non-NaN value in searchWidth rows-columns.\n% This argument is optional and default value is 8.\n% 'walls' Definition of walls along which the border score is calculated. Provided by\n% a string which contains characters that stand for walls:\n% T - top wall (we assume the bird-eye view on the arena)\n% R - right wall\n% B - bottom wall\n% L - left wall\n% Characters are case insensitive. Default value is 'TRBL' meaning that border\n% score is calculated along all walls. Any combination is possible, e.g.\n% 'R' to calculate along right wall, 'BL' to calculate along two walls, e.t.c.\n% ==============================================================================================\n% coverage Border coverage, ranges from 0 to 1.\n%\nfunction coverage = borderCoverage(fields, varargin)\n coverage = 0;\n\n inp = inputParser;\n defaultSearchWidth = 8;\n defaultWalls = 'TRBL'; % top, right, bottom, left\n\n checkSearchWidth = @(x) isnumeric(x) && isscalar(x) && (x > 0);\n checkWalls = @internCheckWalls;\n\n addRequired(inp, 'fields');\n addParameter(inp, 'searchWidth', defaultSearchWidth, checkSearchWidth);\n addParameter(inp, 'walls', defaultWalls, checkWalls);\n\n inp.KeepUnmatched = true;\n parse(inp, fields, varargin{:});\n\n % get parsed results\n walls = inp.Results.walls;\n searchWidth = inp.Results.searchWidth;\n\n % find out what walls are present\n dict = {'B', 'L', 'R', 'T'}; % already sorted\n u = unique(walls);\n t = ['^' sprintf('%c{0,%d}', [u; histc(walls, u)]) '$'];\n wallsIdx = find(~cellfun('isempty', regexpi(dict, t))); % indices in dict of present walls\n\n for i=1:length(fields)\n curField = fields(i).map;\n\n % coverage for left wall\n if any(ismember(wallsIdx, 2))\n aux_map = curField(:, 1:searchWidth);\n [covered, norm] = wall_field(aux_map);\n if (covered/norm > coverage)\n coverage = covered/norm;\n end\n end\n\n % coverage for right wall\n if any(ismember(wallsIdx, 3))\n aux_map = curField(:, end:-1:end+1-searchWidth);\n [covered, norm] = wall_field(aux_map);\n if (covered/norm > coverage)\n coverage=covered/norm;\n end\n end\n\n % coverage for bottom wall, since we are dealing with data that came from a camera\n % 'bottom' is actually at the top of the matrix curField.\n if (any(ismember(wallsIdx, 1)))\n aux_map = curField(1:searchWidth, :)';\n [covered, norm] = wall_field(aux_map);\n if (covered/norm > coverage)\n coverage=covered/norm;\n end\n end\n\n % coverage for top wall\n if (any(ismember(wallsIdx, 4)))\n aux_map = curField(end:-1:end+1-searchWidth, :)';\n [covered, norm] = wall_field(aux_map);\n if (covered/norm > coverage)\n coverage = covered/norm;\n end\n end\n end\nend\n\n% 'covered' pixels will have distance to border 0.\n% Essentially we need to calculate number of elements,\n% that equal to zero and take NaNs into account.\nfunction [covered, norm] = wall_field(map)\n ly = size(map, 1);\n\n D = bwdist(map);\n nanIndices = find(isnan(map(:, 1)));\n numNans = length(nanIndices);\n for i = 1:numNans\n testRow = nanIndices(i);\n nonNan = find(~isnan(map(testRow, :)), 1, 'first');\n if ~isempty(nonNan)\n numNans = numNans - 1;\n D(testRow, 1) = D(testRow, nonNan);\n end\n end\n\n norm = ly - numNans;\n covered = nansum(D(:, 1) == 0) - numNans;\nend\n\n% check input argument that defines walls\n% We need to figure out if argument contains one of the characters\n% from the dictionary.\n% Rise descriptive exception in case of an error.\nfunction res = internCheckWalls(walls)\n res = true;\n if ~ischar(walls)\n error('BNT:args:notChar', 'Argument is not a string.')\n end\n if length(walls) > 4\n error('BNT:args:length', 'Argument can not exceed 4 characters (default ''TLBR'')');\n end\n\n dict = {'T', 'R', 'B', 'L'};\n\n % http://stackoverflow.com/questions/19343339/matlab-find-the-indices-of-a-cell-array-of-strings-with-characters-all-containe\n u = unique(walls);\n t = ['^' sprintf('%c{0,%d}', [u; histc(walls, u)]) '$'];\n s = cellfun(@sort, dict, 'uni', 0);\n idx = find(~cellfun('isempty', regexp(s, t)), 1);\n %res = ~isempty(idx); % if it is not empty, then we have characters from dict in walls\n if isempty(idx)\n error('BNT:args:noValidChars', 'There is no information about the walls in the argument.');\n end\nend", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+analyses/borderCoverage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3786519129647713}} {"text": "function z = plus( x, y )\n %PLUS Addition of two TT/MPS tensors.\n % Z = PLUS(X,Y) adds two TT/MPS tensors. The rank of the resulting\n % tensor is 2*R.\n %\n % See also MINUS, UMINUS.\n \n % TTeMPS Toolbox. \n % Michael Steinlechner, 2013-2016\n % Questions and contact: michael.steinlechner@epfl.ch\n % BSD 2-clause license, see LICENSE.txt\n \n % add sanity check...\n rx = x.rank;\n ry = y.rank;\n nx = x.size;\n\n z = TTeMPS( cell(1, x.order) );\n \n % first core:\n p = size(x.U{1},4);\n tmp = zeros( 1, nx(1), rx(2)+ry(2), p );\n tmp( 1, :, 1:rx(2), : ) = x.U{1};\n tmp( 1, :, rx(2)+1:end, : ) = y.U{1};\n z.U{1} = tmp;\n\n % central cores:\n for i = 2:x.order-1\n % possibility of block format:\n p = size(x.U{i},4);\n tmp = zeros( rx(i)+ry(i), nx(i), rx(i+1)+ry(i+1), p);\n tmp( 1:rx(i), :, 1:rx(i+1), :) = x.U{i};\n tmp( rx(i)+1:end, :, rx(i+1)+1:end, :) = y.U{i};\n z.U{i} = tmp;\n end\n\n % last core:\n p = size(x.U{end},4);\n tmp = zeros( rx(end-1)+ry(end-1), nx(end), 1, p );\n tmp( 1:rx(end-1), :, 1, : ) = x.U{end};\n tmp( rx(end-1)+1:end, :, 1, : ) = y.U{end};\n z.U{end} = tmp;\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/TTeMPS_1.1/@TTeMPS/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3786519129647713}} {"text": "function stats = ReconstructPosition(positions,spikes,phases,varargin)\n\n%ReconstructPosition - Bayesian reconstruction of positions from spike trains.\n%\n% Instantaneous positions are reconstructed using a Bayesian algorithm.\n% Instantaneous population firing rates can be estimated either over fixed time\n% windows, or over fractions of the theta cycle (or of any other brain rhythm).\n% Similarly, positions will be reconstructed either over time or phase windows.\n% The model is first trained on a subset of the data, then tested on the rest.\n%\n% USAGE\n%\n% stats = ReconstructPosition(positions,spikes,phases,)\n%\n% positions linear or two-dimensional positions, in [0..1]\n% spikes list of (t,group,cluster) triplets (obtained via e.g.\n% GetSpikes, using full output)\n% phases optional unwrapped phase of the LFP (see Phase)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'training' time interval over which the model should be trained\n% (default = first half of the position data)\n% 'window' length of the time or phase window (default = 0.020 s for\n% time, and pi/3 for phases)\n% 'type' two letters (one for X and one for Y) indicating which\n% coordinates are linear ('l') and which are circular ('c')\n% - for 1D data, only one letter is used (default 'll')\n% 'nBins' firing curve or map resolution (default = [200 200])\n% =========================================================================\n%\n% OUTPUT\n%\n% stats.positions real position across time or phase windows\n% stats.spikes cell firing vector across time or phase windows\n% stats.estimations estimated position across time or phase windows\n% stats.errors estimation error across time or phase windows\n% stats.average average estimation error in each phase window\n% stats.windows time windows (possibly computed from phases)\n% stats.phases phase windows (empty for fixed time windows)\n%\n\n% Copyright (C) 2012-2013 by Michaël Zugaro, (C) 2012 by Karim El Kanbi\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\n% Defaults\nwt = 0.020; % default time window\nwp = pi/3; % default phase window\nwindow = [];\nnBins = 200;\ntraining = 0.5;\ntype = '';\nnDimensions = 1;\n\n% Check number of parameters\nif nargin < 2 || mod(length(varargin),2) ~= 0,\n\tbuiltin('error','Incorrect number of parameters (type ''help ReconstructPosition'' for details).');\nend\n\n% Optional parameter 'phases'\nif nargin == 2,\n\tphases = [];\nelseif nargin >= 3 && ischar(phases),\n\tvarargin = {phases,varargin{:}};\n\tphases = [];\nend\n\n% Check parameter sizes\nif ~isdmatrix(positions),\n\tbuiltin('error','Incorrect positions (type ''help ReconstructPosition'' for details).');\nend\nif ~isdmatrix(spikes),\n\tbuiltin('error','Incorrect spikes (type ''help ReconstructPosition'' for details).');\nend\nif size(positions,2) > 3,\n\tnDimensions = 2;\nend\nif ~isempty(phases) && ~isdmatrix(phases),\n\tbuiltin('error','Incorrect value for property ''phases'' (type ''help ReconstructPosition'' for details).');\nend\n\n% Check number of output parameters\nif isempty(phases) && nargout == 3,\n\tbuiltin('error','Too many output parameters or missing phases (type ''help ReconstructPosition'' for details).');\nend\n\n% Parse parameters\nfor i = 1:2:length(varargin),\n\tif ~ischar(varargin{i}),\n\t\tbuiltin('error',['Parameter ' num2str(i+2) ' is not a property (type ''help ReconstructPosition'' for details).']);\n\tend\n\tswitch(lower(varargin{i})),\n\t\tcase 'training',\n\t\t\ttraining = varargin{i+1};\n\t\t\tif ~isdvector(training,'>'),\n\t\t\t\tbuiltin('error','Incorrect value for property ''training'' (type ''help ReconstructPosition'' for details).');\n\t\t\tend\n\t\tcase 'window',\n\t\t\twindow = varargin{i+1};\n\t\t\tif ~isdscalar(window,'>0'),\n\t\t\t\tbuiltin('error','Incorrect value for property ''window'' (type ''help ReconstructPosition'' for details).');\n\t\t\tend\n\t\tcase 'show',\n\t\t\tshow = varargin{i+1};\n\t\t\tif ~isstring_FMAT(show,'on','off'),\n\t\t\t\tbuiltin('error','Incorrect value for property ''show'' (type ''help ReconstructPosition'' for details).');\n\t\t\tend\n\t\tcase 'nBins',\n\t\t\tnBins = varargin{i+1};\n\t\t\tif ~isinteger(nBins),\n\t\t\t\tbuiltin('error','Incorrect value for property ''nBins'' (type ''help ReconstructPosition'' for details).');\n\t\t\tend\n\t\tcase 'type',\n\t\t\ttype = lower(varargin{i+1});\n\t\t\tif (nDimensions == 1 && ~isstring_FMAT(type,'cc','cl','lc','ll')) || (nDimensions == 2 && ~isstring_FMAT(type,'ccl','cll','lcl','lll','ccc','clc','lcc','llc')),\n\t\t\t\tbuiltin('error','Incorrect value for property ''type'' (type ''help ReconstructPosition'' for details).');\n\t\t\tend\n\t\totherwise,\n\t\t\tbuiltin('error',['Unknown property ''' num2str(varargin{i}) ''' (type ''help ReconstructPosition'' for details).']);\n\tend\nend\n\n% Defaults\nif isempty(window),\n\tif isempty(phases),\n\t\twindow = wt;\n\telse\n\t\twindow = wp;\n\t\tif ~isiscalar((2*pi)/window),\n\t\t\tbuiltin('error',['Incorrect phase window: not an integer fraction of 2pi (type ''help ReconstructPosition'' for details).']);\n\t\tend\n\tend\nend\nif isdscalar(training),\n\ttraining = [-Inf positions(1,1)+training*(positions(end,1)-positions(1,1))];\nelse\n\tif min([positions(1,1) spikes(1,1)]) < training(1) & min([positions(end,1) spikes(end,1)]) > training(2),\n\t\tbuiltin('error',['Spikes or positions occur both before and after training interval (type ''help ReconstructPosition'' for details).']);\n\tend\nend\nif isempty(type),\n\tif nDimensions == 2,\n\t\ttype = 'lll';\n\telse\n\t\ttype = 'll';\n\tend\nend\nnBinsX = nBins(1);\nif length(nBins) > 2,\n\tnBinsY = nBins(2);\nelse\n\tif nDimensions == 2,\n\t\tnBinsY = nBinsX;\n\telse\n\t\tnBinsY = 1;\n\tend\nend\n\n\n% List units, assign them an ID (number them from 1 to N), and associate these IDs with each spike\n% (IDs will be easier to manipulate than (group,cluster) pairs in subsequent computations)\n[units,~,i] = unique(spikes(:,2:end),'rows');\nnUnits = length(units);\nindex = 1:nUnits;\nid = index(i)';\nspikes = [spikes(:,1) id];\n\n% Split data (training vs test)\ntrainingPositions = Restrict(positions,training);\ntrainingSpikes = Restrict(spikes,training);\ntestPositions = positions(~InIntervals(positions,training),:);\ntestSpikes = spikes(~InIntervals(spikes,training),:);\n\n% TRAINING\n\n% Compute occupancy probability P(x) (i.e. normalized occupancy map)\nfirstUnit = trainingSpikes(:,2) == 1;\ns = trainingSpikes(firstUnit,1);\nmap = Map(trainingPositions,s,'nbins',nBins,'smooth',5,'type',type);\nPx = map.time;\nPx = Px ./ sum(Px(:));\n\n% Compute average firing probability lambda for each unit (i.e. firing maps)\nlambda(:,:,1) = map.z;\nfor i = 2:nUnits,\n\tnextUnit = trainingSpikes(:,2) == i;\n\ts = trainingSpikes(nextUnit,1);\n\tmap = Map(trainingPositions,s,'nbins',nBins,'smooth',5,'type',type);\n\tlambda(:,:,i) = map.z;\nend\n\n% TEST\n\n% Determine time windows (using unwrapped phases if necessary)\nif ~isempty(phases),\n\ttestPhases = phases(~InIntervals(phases,training),:);\n\tdrop = testPhases(:,1) < testPositions(1,1);\n\ttestPhases(drop,:) = [];\n\tstartPhase = ceil(testPhases(1,2)/(2*pi))*2*pi;\n\tstopPhase = floor(testPhases(end,2)/(2*pi))*2*pi;\n\twindows = (startPhase:window:stopPhase)';\n\tstats.phases = windows;\n\twindows = Interpolate(testPhases(:,[2 1]),windows);\n\twindows = [windows(1:end-1,2) windows(2:end,2)];\nelse\n\tstats.phases = [];\n\twindows = (testPositions(1,1):window:testPositions(end,1))';\n\twindows = [windows(1:end-1) windows(2:end)];\nend\nnWindows = size(windows,1);\n\nstats.estimations = nan(nBinsY,nBinsX,nWindows);\nstats.spikes = zeros(nUnits,nWindows);\n% Loop over data windows\nfor i = 1:nWindows,\n \n\t% Get spikes for this window\n\ts = Restrict(testSpikes,windows(i,:));\n\n\tif isempty(s),\n\t\t% No spikes: set uniform probability\n\t\tstats.estimations(:,:,i) = ones(nBinsY,nBinsX,1)/(nBinsX*nBinsY);\n\t\tcontinue;\n\tend\n \n\t% Population spike count vector\n\tstats.spikes(:,i) = Accumulate(s(:,2),1,nUnits);\n\t% To avoid 'for' loops, prepare for vector computation:\n\t% assign a spike count to each position and unit (3D array)\n\tn = reshape(repmat(stats.spikes(:,i),1,nBinsX*nBinsY)',nBinsY,nBinsX,nUnits);\n\n\t% For each cell i, compute P(ni|x) using a Poisson model\n\tdt = windows(i,2) - windows(i,1);\n\tPnix = (dt*lambda).^n./factorial(n).*exp(-dt*lambda);\n\t% Compute P(n|x) assuming independent probabilities across units (hmm...)\n\t% i.e. P(n|x) = product over i of P(ni|x)\n\tPnx = prod(Pnix,3);\n \n\t% Compute P(n) = sum over x of P(n|x)*P(x)\n\tPn = sum(sum(Pnx.*Px));\n \n\t% Compute P(x|n) = P(n|x)*P(x)/P(n)\n\tPxn = Pnx .* Px / Pn;\n\n\t% Store result\n\tstats.estimations(:,:,i) = Pxn;\n\nend\nstats.estimations = squeeze(stats.estimations);\nstats.windows = windows;\n\n% Estimation error\n\nstats.errors = [];\nstats.average = [];\nif nDimensions == 1,\n\t% Bin test positions and compute distance to center\n\tstats.positions = Interpolate(testPositions,windows(:,1));\n\tstats.positions(:,2) = Bin(stats.positions(:,2),[0 1],nBinsX);\n\tdx = (round(nBinsX/2)-stats.positions(:,2))';\n\t% Shift estimated position by the real distance to center\n\tstats.errors = CircularShift(stats.estimations(:,1:length(dx)),dx);\n\t% Average over one or more cycles\n\tk = 2*pi/window;\n\tn = floor(size(stats.errors,2)/k)*k;\n\tstats.average = reshape(stats.errors(:,1:n),nBins,k,[]);\n\tstats.average = nanmean(stats.average,3);\nelse\n\twarning('Computation of estimation error not yet implemented for 2D environments');\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/Analyses/ReconstructPosition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.37865190625104933}} {"text": "function [D, optinf] = ccmod(X, S, dsz, opt)\n\n% ccmod -- Convolutional Constrained Method of Optimal Directions (MOD)\n%\n% argmin_{d_m} (1/2) \\sum_k ||\\sum_m x_k,m * d_m - s_k||_2^2\n% such that ||d_m||_2 = 1\n%\n% The solution of the Convolutional Constrained MOD problem\n% (see wohlberg-2016-efficient) is computed using the ADMM\n% approach (see boyd-2010-distributed).\n%\n% Usage:\n% [D, optinf] = ccmod(X, S, dsz, opt)\n%\n% Input:\n% X Coefficient maps (3D array)\n% S Input images\n% dsz Dictionary size\n% opt Algorithm parameters structure\n%\n% Output:\n% D Dictionary filter set (3D array)\n% optinf Details of optimisation\n%\n%\n% Options structure fields:\n% Verbose Flag determining whether iteration status is displayed.\n% Fields are iteration number, functional value,\n% data fidelity term, l1 regularisation term, and\n% primal and dual residuals (see Sec. 3.3 of\n% boyd-2010-distributed). The values of rho and sigma\n% are also displayed if options request that they are\n% automatically adjusted.\n% MaxMainIter Maximum main iterations\n% AbsStopTol Absolute convergence tolerance (see Sec. 3.3.1 of\n% boyd-2010-distributed)\n% RelStopTol Relative convergence tolerance (see Sec. 3.3.1 of\n% boyd-2010-distributed)\n% G0 Initial value for G\n% H0 Initial value for H\n% sigma ADMM penalty parameter\n% AutoSigma Flag determining whether sigma is automatically updated\n% (see Sec. 3.4.1 of boyd-2010-distributed)\n% AutoSigmaPeriod Iteration period on which sigma is updated\n% SigmaRsdlRatio Primal/dual residual ratio in sigma update test\n% SigmaScaling Multiplier applied to sigma when updated\n% AutoSigmaScaling Flag determining whether SigmaScaling value is\n% adaptively determined (see wohlberg-2015-adaptive). If\n% enabled, SigmaScaling specifies a maximum allowed\n% multiplier instead of a fixed multiplier.\n% StdResiduals Flag determining whether standard residual definitions\n% (see Sec 3.3 of boyd-2010-distributed) are used instead\n% of normalised residuals (see wohlberg-2015-adaptive)\n% RelaxParam Relaxation parameter (see Sec. 3.4.3 of\n% boyd-2010-distributed)\n% LinSolve Linear solver for main problem: 'SM' or 'CG'\n% MaxCGIter Maximum CG iterations when using CG solver\n% CGTol CG tolerance when using CG solver\n% CGTolAuto Flag determining use of automatic CG tolerance\n% CGTolFactor Factor by which primal residual is divided to obtain CG\n% tolerance, when automatic tolerance is active\n% ZeroMean Force learned dictionary entries to be zero-mean\n% AuxVarObj Flag determining whether objective function is computed\n% using the auxiliary (split) variable\n%\n%\n% Author: Brendt Wohlberg Modified: 2015-12-18\n%\n% This file is part of the SPORCO library. Details of the copyright\n% and user license can be found in the 'License' file distributed with\n% the library.\n\n\nif nargin < 4,\n opt = [];\nend\ncheckopt(opt, defaultopts([]));\nopt = defaultopts(opt);\n\n% Set up status display for verbose operation\nhstr = 'Itn Obj Cnst r s ';\nsfms = '%4d %9.2e %9.2e %9.2e %9.2e';\nnsep = 44;\nif opt.AutoSigma,\n hstr = [hstr ' sigma '];\n sfms = [sfms ' %9.2e'];\n nsep = nsep + 10;\nend\nif opt.Verbose && opt.MaxMainIter > 0,\n disp(hstr);\n disp(char('-' * ones(1,nsep)));\nend\n\n% Collapsing of trailing singleton dimensions greatly complicates\n% handling of both SMV and MMV cases. The simplest approach would be\n% if S could always be reshaped to 4d, with dimensions consisting of\n% image rows, image cols, a single dimensional placeholder for number\n% of filters, and number of measurements, but in the single\n% measurement case the third dimension is collapsed so that the array\n% is only 3d.\nif size(S,3) > 1,\n xsz = size(X);\n % Insert singleton 3rd dimension (for number of filters) so that\n % 4th dimension is number of images in input s volume\n S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);\nelse\n xsz = [size(X) 1];\nend\n\n% Set dsz to correct form\nif numel(dsz) == 3, dsz = dsz(1:2); end\n\n% Mean removal and normalisation projections\nPzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));\nPnrm = @(x) normalise(x);\n\n% Projection of filter to full image size and its transpose\n% (zero-pad and crop respectively)\nPzp = @(x) zpad(x, xsz(1:2));\nPzpT = @(x) bcrop(x, dsz);\n\n% Projection of dictionary filters onto constraint set\nif opt.ZeroMean,\n Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));\nelse\n Pcn = @(x) Pnrm(Pzp(PzpT(x)));\nend\n\n% Start timer\ntstart = tic;\n\n% Compute coefficients in DFT domain\nXf = fft2(X, size(S,1), size(S,2));\n% Compute signal in DFT domain\nSf = fft2(S);\n% S convolved with all coefficients in DFT domain\nXSf = sum(bsxfun(@times, conj(Xf), Sf), 4);\n\n% Set up algorithm parameters and initialise variables\nsigma = opt.sigma;\nif isempty(sigma), sigma = size(S,3); end;\nNd = prod(xsz(1:3));\ncgt = opt.CGTol;\noptinf = struct('itstat', [], 'opt', opt);\nr = Inf;\ns = Inf;\nepri = 0;\nedua = 0;\n\n% Initialise main working variables\nD = []; Df = [];\nif isempty(opt.G0),\n G = zeros([xsz(1) xsz(2) xsz(3)], class(S));\nelse\n G = opt.G0;\nend\nGprv = G;\nif isempty(opt.H0),\n if isempty(opt.G0),\n H = zeros([xsz(1) xsz(2) xsz(3)], class(S));\n else\n H = G;\n end\nelse\n H = opt.H0;\nend\n\n\n% Main loop\nk = 1;\nwhile k <= opt.MaxMainIter && (r > epri | s > edua),\n\n % Solve subproblems and update dual variable\n if strcmp(opt.LinSolve, 'SM'),\n Df = solvemdbi_ism(Xf, sigma, XSf + sigma*fft2(G - H));\n else\n [Df, cgst] = solvemdbi_cg(Xf, sigma, XSf + sigma*fft2(G - H), ...\n cgt, opt.MaxCGIter, Df(:));\n end\n D = ifft2(Df, 'symmetric');\n\n % See pg. 21 of boyd-2010-distributed\n if opt.RelaxParam == 1,\n Dr = D;\n else\n Dr = opt.RelaxParam*D + (1-opt.RelaxParam)*G;\n end\n\n G = Pcn(Dr + H);\n H = H + Dr - G;\n\n % Compute data fidelity term in Fourier domain (note normalisation)\n if opt.AuxVarObj,\n Gf = fft2(G); % This represents unnecessary computational cost\n Job = sum(vec(abs(sum(bsxfun(@times,Gf,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));\n Jcn = 0;\n else\n Job = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));\n Jcn = norm(vec(Pcn(D) - D));\n end\n\n nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));\n if opt.StdResiduals,\n % See pp. 19-20 of boyd-2010-distributed\n r = norm(vec(D - G));\n s = norm(vec(sigma*(Gprv - G)));\n epri = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;\n edua = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;\n else\n % See wohlberg-2015-adaptive\n r = norm(vec(D - G))/max(nD,nG);\n s = norm(vec(Gprv - G))/nH;\n epri = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;\n edua = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;\n end\n\n if opt.CGTolAuto && (r/opt.CGTolFactor) < cgt,\n cgt = r/opt.CGTolFactor;\n end\n\n % Record and display iteration details\n tk = toc(tstart);\n optinf.itstat = [optinf.itstat; [k Job Jcn r s epri edua sigma tk]];\n if opt.Verbose,\n if opt.AutoSigma,\n disp(sprintf(sfms, k, Job, Jcn, r, s, sigma));\n else\n disp(sprintf(sfms, k, Job, Jcn, r, s));\n end\n end\n\n % See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed\n if opt.AutoSigma,\n if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,\n if opt.AutoSigmaScaling,\n sigmlt = sqrt(r/s);\n if sigmlt < 1, sigmlt = 1/sigmlt; end\n if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end\n else\n sigmlt = opt.SigmaScaling;\n end\n ssf = 1;\n if r > opt.SigmaRsdlRatio*s, ssf = sigmlt; end\n if s > opt.SigmaRsdlRatio*r, ssf = 1/sigmlt; end\n sigma = ssf*sigma;\n H = H/ssf;\n end\n end\n\n Gprv = G;\n k = k + 1;\n\nend\n\n% Record run time and working variables\noptinf.runtime = toc(tstart);\noptinf.D = D;\noptinf.G = G;\noptinf.H = H;\noptinf.sigma = sigma;\noptinf.cgt = cgt;\nif exist('cgst'), optinf.cgst = cgst; end\n\nD = PzpT(G);\n\nif opt.Verbose && opt.MaxMainIter > 0,\n disp(char('-' * ones(1,nsep)));\nend\n\nreturn\n\n\nfunction u = vec(v)\n\n u = v(:);\n\nreturn\n\n\nfunction u = normalise(v)\n\n nrm = sqrt(sum(sum(v.^2, 1), 2));\n nrm(nrm == 0) = 1;\n u = bsxfun(@rdivide, v, nrm);\n\nreturn\n\n\nfunction u = zpad(v, sz)\n\n u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));\n u(1:size(v,1), 1:size(v,2),:,:) = v;\n\nreturn\n\n\nfunction u = bcrop(v, sz)\n\n if numel(sz) <= 2,\n if numel(sz) == 1\n cs = [sz sz];\n else\n cs = sz;\n end\n u = v(1:cs(1), 1:cs(2), :);\n else\n if size(sz,1) < size(sz,2), sz = sz'; end\n cs = max(sz);\n u = zeros(cs(1), cs(2), size(v,3));\n for k = 1:size(v,3),\n u(1:sz(k,1), 1:sz(k,2), k) = v(1:sz(k,1), 1:sz(k,2), k);\n end\n end\n\nreturn\n\n\nfunction opt = defaultopts(opt)\n\n if ~isfield(opt,'Verbose'),\n opt.Verbose = 0;\n end\n if ~isfield(opt,'MaxMainIter'),\n opt.MaxMainIter = 200;\n end\n if ~isfield(opt,'AbsStopTol'),\n opt.AbsStopTol = 1e-6;\n end\n if ~isfield(opt,'RelStopTol'),\n opt.RelStopTol = 1e-4;\n end\n if ~isfield(opt,'G0'),\n opt.G0 = [];\n end\n if ~isfield(opt,'H0'),\n opt.H0 = [];\n end\n if ~isfield(opt,'sigma'),\n opt.sigma = [];\n end\n if ~isfield(opt,'AutoSigma'),\n opt.AutoSigma = 0;\n end\n if ~isfield(opt,'AutoSigmaPeriod'),\n opt.AutoSigmaPeriod = 10;\n end\n if ~isfield(opt,'SigmaRsdlRatio'),\n opt.SigmaRsdlRatio = 10;\n end\n if ~isfield(opt,'SigmaScaling'),\n opt.SigmaScaling = 2;\n end\n if ~isfield(opt,'AutoSigmaScaling'),\n opt.AutoSigmaScaling = 0;\n end\n if ~isfield(opt,'StdResiduals'),\n opt.StdResiduals = 0;\n end\n if ~isfield(opt,'RelaxParam'),\n opt.RelaxParam = 1;\n end\n if ~isfield(opt,'LinSolve'),\n opt.LinSolve = 'SM';\n end\n if ~isfield(opt,'MaxCGIter'),\n opt.MaxCGIter = 1000;\n end\n if ~isfield(opt,'CGTol'),\n opt.CGTol = 1e-3;\n end\n if ~isfield(opt,'CGTolAuto'),\n opt.CGTolAuto = 0;\n end\n if ~isfield(opt,'CGTolAutoFactor'),\n opt.CGTolFactor = 50;\n end\n if ~isfield(opt,'ZeroMean'),\n opt.ZeroMean = 0;\n end\n if ~isfield(opt,'AuxVarObj'),\n opt.AuxVarObj = 0;\n end\n\nreturn\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/ConvSR_Image_Fusion_Codes/sporco/DictLearn/ccmod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3785986251967852}} {"text": "function c = multiprod(a, b, idA, idB)\n%MULTIPROD Multiplying 1-D or 2-D subarrays contained in two N-D arrays.\n% C = MULTIPROD(A,B) is equivalent to C = MULTIPROD(A,B,[1 2],[1 2])\n% C = MULTIPROD(A,B,[D1 D2]) is eq. to C = MULTIPROD(A,B,[D1 D2],[D1 D2])\n% C = MULTIPROD(A,B,D1) is equival. to C = MULTIPROD(A,B,D1,D1)\n%\n% MULTIPROD performs multiple matrix products, with array expansion (AX)\n% enabled. Its first two arguments A and B are \"block arrays\" of any\n% size, containing one or more 1-D or 2-D subarrays, called \"blocks\" (*).\n% For instance, a 5?6?3 array may be viewed as an array containing five\n% 6?3 blocks. In this case, its size is denoted by 5?(6?3). The 1 or 2\n% adjacent dimensions along which the blocks are contained are called the\n% \"internal dimensions\" (IDs) of the array (?).\n%\n% 1) 2-D by 2-D BLOCK(S) (*)\n% C = MULTIPROD(A, B, [DA1 DA2], [DB1 DB2]) contains the products\n% of the P?Q matrices in A by the R?S matrices in B. [DA1 DA2] are\n% the IDs of A; [DB1 DB2] are the IDs of B.\n%\n% 2) 2-D by 1-D BLOCK(S) (*)\n% C = MULTIPROD(A, B, [DA1 DA2], DB1) contains the products of the\n% P?Q matrices in A by the R-element vectors in B. The latter are\n% considered to be R?1 matrices. [DA1 DA2] are the IDs of A; DB1 is\n% the ID of B.\n%\n% 3) 1-D by 2-D BLOCK(S) (*)\n% C = MULTIPROD(A, B, DA1, [DB1 DB2]) contains the products of the \n% Q-element vectors in A by the R?S matrices in B. The vectors in A\n% are considered to be 1?Q matrices. DA1 is the ID of A; [DB1 DB2]\n% are the IDs of B.\n%\n% 4) 1-D BY 1-D BLOCK(S) (*)\n% (a) If either SIZE(A, DA1) == 1 or SIZE(B, DB1) == 1, or both,\n% C = MULTIPROD(A, B, DA1, DB1) returns products of scalars by \n% vectors, or vectors by scalars or scalars by scalars.\n% (b) If SIZE(A, DA1) == SIZE(B, DB1), \n% C = MULTIPROD(A, B, [0 DA1], [DB1 0]) or \n% C = MULTIPROD(A, B, DA1, DB1) virtually turns the vectors\n% contained in A and B into 1?P and P?1 matrices, respectively,\n% then returns their products, similar to scalar products.\n% Namely, C = DOT2(A, B, DA1, DB1) is equivalent to \n% C = MULTIPROD(CONJ(A), B, [0 DA1], [DB1 0]).\n% (c) Without limitations on the length of the vectors in A and B,\n% C = MULTIPROD(A, B, [DA1 0], [0 DB1]) turns the vectors\n% contained in A and B into P?1 and 1?Q matrices, respectively,\n% then returns their products, similar to outer products.\n% Namely, C = OUTER(A, B, DA1, DB1) is equivalent to\n% C = MULTIPROD(CONJ(A), B, [DA1 0], [0 DB1]).\n%\n% Common constraints for all syntaxes:\n% The external dimensions of A and B must either be identical or \n% compatible with AX rules. The internal dimensions of each block\n% array must be adjacent (DA2 == DA1 + 1 and DB2 == DB1 + 1 are\n% required). DA1 and DB1 are allowed to be larger than NDIMS(A) and\n% NDIMS(B). In syntaxes 1, 2, and 3, Q == R is required, unless the\n% blocks in A or B are scalars. \n%\n% Array expansion (AX):\n% AX is a powerful generalization to N-D of the concept of scalar\n% expansion. Indeed, A and B may be scalars, vectors, matrices or\n% multi-dimensional arrays. Scalar expansion is the virtual\n% replication or annihilation of a scalar which allows you to combine\n% it, element by element, with an array X of any size (e.g. X+10,\n% X*10, or []-10). Similarly, in MULTIPROD, the purpose of AX is to\n% automatically match the size of the external dimensions (EDs) of A\n% and B, so that block-by-block products can be performed. ED matching\n% is achieved by means of a dimension shift followed by a singleton\n% expansion:\n% 1) Dimension shift (see SHIFTDIM).\n% Whenever DA1 ~= DB1, a shift is applied to impose DA1 == DB1.\n% If DA1 > DB1, B is shifted to the right by DA1 - DB1 steps.\n% If DB1 > DA1, A is shifted to the right by DB1 - DA1 steps.\n% 2) Singleton expansion (SX).\n% Whenever an ED of either A or B is singleton and the\n% corresponding ED of the other array is not, the mismatch is\n% fixed by virtually replicating the array (or diminishing it to\n% length 0) along that dimension.\n% \n% MULTIPROD is a generalization for N-D arrays of the matrix\n% multiplication function MTIMES, with AX enabled. Vector inner, outer,\n% and cross products generalized for N-D arrays and with AX enabled are\n% performed by DOT2, OUTER, and CROSS2 (MATLAB Central, file #8782).\n% Elementwise multiplications (see TIMES) and other elementwise binary\n% operations with AX enabled are performed by BAXFUN (MATLAB Central,\n% file #23084). Together, these functions make up the ?ARRAYLAB toolbox?.\n%\n% Input and output format:\n% The size of the EDs of C is determined by AX. Block size is\n% determined as follows, for each of the above-listed syntaxes:\n% 1) C contains P?S matrices along IDs MAX([DA1 DA2], [DB1 DB2]).\n% 2) Array Block size ID(s)\n% ----------------------------------------------------\n% A P?Q (2-D) [DA1 DA2]\n% B R (1-D) DB1\n% C (a) P (1-D) MAX(DA1, DB1)\n% C (b) P?Q (2-D) MAX([DA1 DA2], [DB1 DB1+1])\n% ----------------------------------------------------\n% (a) The 1-D blocks in B are not scalars (R > 1).\n% (b) The 1-D blocks in B are scalars (R = 1).\n% 3) Array Block size ID(s)\n% ----------------------------------------------------\n% A Q (1-D) DA1\n% B R?S (2-D) [DB1 DB2]\n% C (a) S (1-D) MAX(DA1, DB1)\n% C (b) R?S (2-D) MAX([DA1 DA1+1], [DB1 DB2])\n% ----------------------------------------------------\n% (a) The 1-D blocks in A are not scalars (Q > 1).\n% (b) The 1-D blocks in A are scalars (Q = 1).\n% 4) Array Block size ID(s)\n% --------------------------------------------------------------\n% (a) A P (1-D) DA1\n% B Q (1-D) DB1\n% C MAX(P,Q) (1-D) MAX(DA1, DB1)\n% --------------------------------------------------------------\n% (b) A P (1-D) DA1\n% B P (1-D) DB1\n% C 1 (1-D) MAX(DA1, DB1)\n% --------------------------------------------------------------\n% (c) A P (1-D) DA1\n% B Q (1-D) DB1\n% C P?Q (2-D) MAX([DA1 DA1+1], [DB1 DB1+1])\n% --------------------------------------------------------------\n%\n% Terminological notes:\n% (*) 1-D and 2-D blocks are generically referred to as \"vectors\" and \n% \"matrices\", respectively. However, both may be also called\n% ?scalars? if they have a single element. Moreover, matrices with a\n% single row or column (e.g. 1?3 or 3?1) may be also called ?row\n% vectors? or ?column vectors?.\n% (?) Not to be confused with the \"inner dimensions\" of the two matrices\n% involved in a product X * Y, defined as the 2nd dimension of X and\n% the 1st of Y (DA2 and DB1 in syntaxes 1, 2, 3).\n%\n% Examples:\n% 1) If A is .................... a 5?(6?3)?2 array,\n% and B is .................... a 5?(3?4)?2 array,\n% C = MULTIPROD(A, B, [2 3]) is a 5?(6?4)?2 array.\n%\n% A single matrix A pre-multiplies each matrix in B\n% If A is ........................... a (1?3) single matrix,\n% and B is ........................... a 10?(3?4) 3-D array,\n% C = MULTIPROD(A, B, [1 2], [3 4]) is a 10?(1?4) 3-D array.\n%\n% Each matrix in A pre-multiplies each matrix in B (all possible\n% combinations)\n% If A is .................... a (6?3)?5 array,\n% and B is .................... a (3?4)?1?2 array,\n% C = MULTIPROD(A, B, [1 2]) is a (6?4)?5?2 array.\n%\n% 2a) If A is ........................... a 5?(6?3)?2 4-D array,\n% and B is ........................... a 5?(3)?2 3-D array,\n% C = MULTIPROD(A, B, [2 3], [2]) is a 5?(6)?2 3-D array.\n%\n% 2b) If A is ........................... a 5?(6?3)?2 4-D array,\n% and B is ........................... a 5?(1)?2 3-D array,\n% C = MULTIPROD(A, B, [2 3], [2]) is a 5?(6?3)?2 4-D array.\n%\n% 4a) If both A and B are .................. 5?(6)?2 3-D arrays,\n% C = MULTIPROD(A, B, 2) is .......... a 5?(1)?2 3-D array, while\n% 4b) C = MULTIPROD(A, B, [2 0], [0 2]) is a 5?(6?6)?2 4-D array\n%\n% See also DOT2, OUTER, CROSS2, BAXFUN, MULTITRANSP, MULTITRACE, MULTISCALE.\n\n% $ Version: 2.1 $\n% CODE by: Paolo de Leva\n% (Univ. of Rome, Foro Italico, IT) 2009 Jan 24\n% optimized by: Paolo de Leva\n% Jinhui Bai (Georgetown Univ., D.C.) 2009 Jan 24\n% COMMENTS by: Paolo de Leva 2009 Feb 24\n% OUTPUT tested by: Paolo de Leva 2009 Feb 24\n% -------------------------------------------------------------------------\n\n%error( nargchk(2, 4, nargin) ); % Allow 2 to 4 input arguments % HK\nnarginchk(2, 4); % added by HK\nswitch nargin % Setting IDA and/or IDB\n case 2, idA = [1 2]; idB = [1 2];\n case 3, idB = idA;\nend\n\n% ESC 1 - Special simple case (both A and B are 2D), solved using C = A * B\n\n if ndims(a)==2 && ndims(b)==2 && ...\n isequal(idA,[1 2]) && isequal(idB,[1 2])\n c = a * b; return\n end\n\n% MAIN 0 - Checking and evaluating array size, block size, and IDs\n\n sizeA0 = size(a);\n sizeB0 = size(b);\n [sizeA, sizeB, shiftC, delC, sizeisnew, idA, idB, ...\n squashOK, sxtimesOK, timesOK, mtimesOK, sumOK] = ...\n sizeval(idA,idB, sizeA0,sizeB0);\n\n% MAIN 1 - Applying dimension shift (first step of AX) and \n% turning both A and B into arrays of either 1-D or 2-D blocks\n\n if sizeisnew(1), a = reshape(a, sizeA); end \n if sizeisnew(2), b = reshape(b, sizeB); end\n\n% MAIN 2 - Performing products with or without SX (second step of AX)\n\n if squashOK % SQUASH + MTIMES (fastest engine)\n c = squash2D_mtimes(a,b, idA,idB, sizeA,sizeB, squashOK); \n elseif timesOK % TIMES (preferred w.r. to SX + TIMES)\n if sumOK, c = sum(a .* b, sumOK);\n else c = a .* b; end\n elseif sxtimesOK % SX + TIMES\n if sumOK, c = sum(bsxfun(@times, a, b), sumOK);\n else c = bsxfun(@times, a, b); end\n elseif mtimesOK % MTIMES (rarely used)\n c = a * b;\n end\n\n% MAIN 3 - Reshaping C (by inserting or removing singleton dimensions)\n\n [sizeC sizeCisnew] = adjustsize(size(c), shiftC, false, delC, false);\n if sizeCisnew, c = reshape(c, sizeC); end\n\n\nfunction c = squash2D_mtimes(a, b, idA, idB, sizeA, sizeB, squashOK)\n% SQUASH2D_MTIMES Multiproduct with single-block expansion (SBX).\n% Actually, no expansion is performed. The multi-block array is\n% rearranged from N-D to 2-D, then MTIMES is applied, and eventually the\n% result is rearranged back to N-D. No additional memory is required.\n% One and only one of the two arrays must be single-block, and its IDs\n% must be [1 2] (MAIN 1 removes leading singletons). Both arrays\n% must contain 2-D blocks (MAIN 1 expands 1-D blocks to 2-D).\n\n if squashOK == 1 % A is multi-block, B is single-block (squashing A)\n\n % STEP 1 - Moving IDA(2) to last dimension\n nd = length(sizeA);\n d2 = idA(2); \n order = [1:(d2-1) (d2+1):nd d2]; % Partial shifting\n a = permute(a, order); % ...?Q\n\n % STEP 2 - Squashing A from N-D to 2-D \n q = sizeB(1);\n s = sizeB(2);\n lengthorder = length(order);\n collapsedsize = sizeA(order(1:lengthorder-1)); \n n = prod(collapsedsize);\n a = reshape(a, [n, q]); % N?Q \n fullsize = [collapsedsize s]; % Size to reshape C back to N-D\n\n else % B is multi-block, A is single-block (squashing B)\n\n % STEP 1 - Moving IDB(1) to first dimension\n nd = length(sizeB);\n d1 = idB(1); \n order = [d1 1:(d1-1) (d1+1):nd]; % Partial shifting\n b = permute(b, order); % Q?...\n\n % STEP 2 - Squashing B from N-D to 2-D \n p = sizeA(1);\n q = sizeA(2);\n lengthorder = length(order);\n collapsedsize = sizeB(order(2:lengthorder)); \n n = prod(collapsedsize);\n b = reshape(b, [q, n]); % Q?N\n fullsize = [p collapsedsize]; % Size to reshape C back to N-D\n\n end\n\n % FINAL STEPS - Multiplication, reshape to N-D, inverse permutation\n invorder(order) = 1 : lengthorder;\n c = permute (reshape(a*b, fullsize), invorder);\n\n\nfunction [sizeA, sizeB, shiftC, delC, sizeisnew, idA, idB, ...\n squashOK, sxtimesOK, timesOK, mtimesOK, sumOK] = ...\n sizeval(idA0,idB0, sizeA0,sizeB0)\n%SIZEVAL Evaluation of array size, block size, and IDs\n% Possible values for IDA and IDB:\n% [DA1 DA2], [DB1 DB2]\n% [DA1 DA2], [DB1]\n% [DA1], [DB1 DB2]\n% [DA1], [DB1]\n% [DA1 0], [0 DB1]\n% [0 DA1], [DB1 0]\n%\n% sizeA/B Equal to sizeA0/B0 if RESHAPE is not needed in MAIN 1\n% shiftC, delC Variables controlling MAIN 3.\n% sizeisnew 1x2 logical array; activates reshaping of A and B.\n% idA/B May change only if squashOK ~= 0\n% squashOK If only A or B is a multi-block array (M-B) and the other\n% is single-block (1-B), it will be rearranged from N-D to\n% 2-D. If both A and B are 1-B or M-B arrays, squashOK = 0.\n% If only A (or B) is a M-B array, squashOK = 1 (or 2).\n% sxtimesOK, timesOK, mtimesOK Flags controlling MAIN 2 (TRUE/FALSE).\n% sumOK Dimension along which SUM is performed. If SUM is not\n% needed, sumOK = 0.\n\n% Initializing output arguments\n\n idA = idA0;\n idB = idB0;\n squashOK = 0;\n sxtimesOK = false;\n timesOK = false;\n mtimesOK = false;\n sumOK = 0;\n shiftC = 0;\n delC = 0;\n\n% Checking for gross input errors\n\n NidA = numel(idA);\n NidB = numel(idB);\n idA1 = idA(1);\n idB1 = idB(1);\n if NidA>2 || NidB>2 || NidA==0 || NidB==0 || ...\n ~isreal(idA1) || ~isreal(idB1) || ...\n ~isnumeric(idA1) || ~isnumeric(idB1) || ...\n 0>idA1 || 0>idB1 || ... % negative \n idA1~=fix(idA1) || idB1~=fix(idB1) || ... % non-integer\n ~isfinite(idA1) || ~isfinite(idB1) % Inf or NaN \n error('MULTIPROD:InvalidDimensionArgument', ...\n ['Internal-dimension arguments (e.g., [IDA1 IDA2]) must\\n', ...\n 'contain only one or two non-negative finite integers']);\n end\n\n% Checking Syntaxes containing zeros (4b/c)\n\n declared_outer = false;\n idA2 = idA(NidA); % It may be IDA1 = IDA2 (1-D block)\n idB2 = idB(NidB);\n\n if any(idA==0) || any(idB==0)\n \n % \"Inner products\": C = MULTIPROD(A, B, [0 DA1], [DB1 0])\n if idA1==0 && idA2>0 && idB1>0 && idB2==0\n idA1 = idA2;\n idB2 = idB1;\n % \"Outer products\": C = MULTIPROD(A, B, [DA1 0], [0 DB1]) \n elseif idA1>0 && idA2==0 && idB1==0 && idB2>0\n declared_outer = true;\n idA2 = idA1;\n idB1 = idB2;\n else\n error('MULTIPROD:InvalidDimensionArgument', ...\n ['Misused zeros in the internal-dimension arguments\\n', ...\n '(see help heads 4b and 4c)']);\n end\n NidA = 1; \n NidB = 1;\n idA = idA1;\n idB = idB1;\n\n elseif (NidA==2 && idA2~=idA1+1) || ... % Non-adjacent IDs\n (NidB==2 && idB2~=idB1+1)\n error('MULTIPROD:InvalidDimensionArgument', ...\n ['If an array contains 2-D blocks, its two internal dimensions', ... \n 'must be adjacent (e.g. IDA2 == IDA1+1)']);\n end\n\n% ESC - Case for which no reshaping is needed (both A and B are scalars)\n\n scalarA = isequal(sizeA0, [1 1]);\n scalarB = isequal(sizeB0, [1 1]);\n if scalarA && scalarB\n sizeA = sizeA0;\n sizeB = sizeB0;\n sizeisnew = [false false];\n timesOK = true; return\n end\n\n% Computing and checking adjusted sizes\n% The lengths of ADJSIZEA and ADJSIZEB must be >= IDA(END) and IDB(END)\n\n NsA = idA2 - length(sizeA0); % Number of added trailing singletons\n NsB = idB2 - length(sizeB0);\n adjsizeA = [sizeA0 ones(1,NsA)];\n adjsizeB = [sizeB0 ones(1,NsB)];\n extsizeA = adjsizeA([1:idA1-1, idA2+1:end]); % Size of EDs\n extsizeB = adjsizeB([1:idB1-1, idB2+1:end]);\n p = adjsizeA(idA1);\n q = adjsizeA(idA2);\n r = adjsizeB(idB1);\n s = adjsizeB(idB2); \n scalarsinA = (p==1 && q==1);\n scalarsinB = (r==1 && s==1);\n singleA = all(extsizeA==1);\n singleB = all(extsizeB==1);\n if q~=r && ~scalarsinA && ~scalarsinB && ~declared_outer\n error('MULTIPROD:InnerDimensionsMismatch', ...\n 'Inner matrix dimensions must agree.');\n end\n\n% STEP 1/3 - DIMENSION SHIFTING (FIRST STEP OF AX)\n% Pipeline 1 (using TIMES) never needs left, and may need right shifting.\n% Pipeline 2 (using MTIMES) may need left shifting of A and right of B.\n\n shiftA = 0;\n shiftB = 0;\n diffBA = idB1 - idA1; \n if scalarA % Do nothing\n elseif singleA && ~scalarsinB, shiftA = -idA1 + 1; % Left shifting A\n elseif idB1 > idA1, shiftA = diffBA; % Right shifting A \n end \n if scalarB % Do nothing\n elseif singleB && ~scalarsinA, shiftB = -idB1 + 1; % Left shifting B\n elseif idA1 > idB1, shiftB = -diffBA; % Right shifting B\n end\n\n% STEP 2/3 - SELECTION OF PROPER ENGINE AND BLOCK SIZE ADJUSTMENTS\n\n addA = 0; addB = 0;\n delA = 0; delB = 0;\n swapA = 0; swapB = 0;\n idC1 = max(idA1, idB1);\n idC2 = idC1 + 1;\n checktimes = false;\n\n if (singleA||singleB) &&~scalarsinA &&~scalarsinB % Engine using MTIMES\n\n if singleA && singleB \n mtimesOK = true;\n shiftC=idC1-1; % Right shifting C\n idC1=1; idC2=2;\n elseif singleA\n squashOK = 2;\n idB = [idB1, idB1+1] + shiftB;\n else % singleB\n squashOK = 1;\n idA = [idA1, idA1+1] + shiftA;\n end\n\n if NidA==2 && NidB==2 % 1) 2-D BLOCKS BY 2-D BLOCKS\n % OK \n elseif NidA==2 % 2) 2-D BLOCKS BY 1-D BLOCKS\n addB=idB1+1; delC=idC2;\n elseif NidB==2 % 3) 1-D BLOCKS BY 2-D BLOCKS\n addA=idA1; delC=idC1;\n else % 4) 1-D BLOCKS BY 1-D BLOCKS\n if declared_outer\n addA=idA1+1; addB=idB1;\n else\n addA=idA1; addB=idB1+1; delC=idC2;\n end\n end \n\n else % Engine using TIMES (also used if SCALARA || SCALARB)\n \n sxtimesOK = true;\n\n if NidA==2 && NidB==2 % 1) 2-D BLOCKS BY 2-D BLOCKS\n\n if scalarA || scalarB\n timesOK=true; \n elseif scalarsinA && scalarsinB % scal-by-scal\n checktimes=true;\n elseif scalarsinA || scalarsinB || ... % scal-by-mat\n (q==1 && r==1) % vec-by-vec (\"outer\")\n elseif p==1 && s==1 % vec-by-vec (\"inner\")\n swapA=idA1; sumOK=idC1; checktimes=true;\n elseif s==1 % mat-by-vec\n swapB=idB1; sumOK=idC2;\n elseif p==1 % vec-by-mat\n swapA=idA1; sumOK=idC1;\n else % mat-by-mat\n addA=idA2+1; addB=idB1; sumOK=idC2; delC=idC2;\n end\n\n elseif NidA==2 % 2) 2-D BLOCKS BY 1-D BLOCKS\n\n if scalarA || scalarB\n timesOK=true; \n elseif scalarsinA && scalarsinB % scal-by-scal\n addB=idB1; checktimes=true;\n elseif scalarsinA % scal-by-vec\n delA=idA1;\n elseif scalarsinB % mat-by-scal\n addB=idB1;\n elseif p==1 % vec-by-vec (\"inner\")\n delA=idA1; sumOK=idC1; checktimes=true;\n else % mat-by-vec\n addB=idB1; sumOK=idC2; delC=idC2;\n end\n\n elseif NidB==2 % 3) 1-D BLOCKS BY 2-D BLOCKS\n\n if scalarA || scalarB\n timesOK=true; \n elseif scalarsinA && scalarsinB % scal-by-scal\n addA=idA1+1; checktimes=true;\n elseif scalarsinB % vec-by-scal\n delB=idB2;\n elseif scalarsinA % scal-by-mat\n addA=idA1+1;\n elseif s==1 % vec-by-vec (\"inner\")\n delB=idB2; sumOK=idC1; checktimes=true;\n else % vec-by-mat\n addA=idA1+1; sumOK=idC1; delC=idC1;\n end\n\n else % 4) 1-D BLOCKS BY 1-D BLOCKS\n\n if scalarA || scalarB\n timesOK=true; \n elseif declared_outer % vec-by-vec (\"outer\")\n addA=idA1+1; addB=idB1;\n elseif scalarsinA && scalarsinB % scal-by-scal\n checktimes=true;\n elseif scalarsinA || scalarsinB % vec-by-scal\n else % vec-by-vec\n sumOK=idC1; checktimes=true;\n end\n end\n end\n\n% STEP 3/3 - Adjusting the size of A and B. The size of C is adjusted\n% later, because it is not known yet.\n\n [sizeA, sizeisnew(1)] = adjustsize(sizeA0, shiftA, addA, delA, swapA);\n [sizeB, sizeisnew(2)] = adjustsize(sizeB0, shiftB, addB, delB, swapB);\n\n if checktimes % Faster than calling BBXFUN\n diff = length(sizeB) - length(sizeA);\n if isequal([sizeA ones(1,diff)], [sizeB ones(1,-diff)])\n timesOK = true;\n end\n end\n\n\nfunction [sizeA, sizeisnew] = adjustsize(sizeA0, shiftA, addA, delA, swapA)\n% ADJUSTSIZE Adjusting size of a block array.\n\n % Dimension shifting (by adding or deleting trailing singleton dim.)\n if shiftA>0, [sizeA,newA1] = addsing(sizeA0, 1, shiftA);\n elseif shiftA<0, [sizeA,newA1] = delsing(sizeA0, 1,-shiftA); \n else sizeA = sizeA0; newA1 = false;\n end\n % Modifying block size (by adding, deleting, or moving singleton dim.)\n if addA, [sizeA,newA2] = addsing(sizeA, addA+shiftA, 1); % 1D-->2D \n elseif delA, [sizeA,newA2] = delsing(sizeA, delA+shiftA, 1); % 2D-->1D\n elseif swapA, [sizeA,newA2] = swapdim(sizeA,swapA+shiftA); % ID Swapping\n else newA2 = false;\n end\n sizeisnew = newA1 || newA2;\n\n\nfunction [newsize, flag] = addsing(size0, dim, ns)\n%ADDSING Adding NS singleton dimensions to the size of an array.\n% Warning: NS is assumed to be a positive integer.\n% Example: If the size of A is ..... SIZE0 = [5 9 3]\n% NEWSIZE = ADDSING(SIZE0, 3, 2) is [5 9 1 1 3]\n\n if dim > length(size0)\n newsize = size0;\n flag = false;\n else \n newsize = [size0(1:dim-1), ones(1,ns), size0(dim:end)];\n flag = true;\n end\n\n\nfunction [newsize, flag] = delsing(size0, dim, ns)\n%DELSING Removing NS singleton dimensions from the size of an array.\n% Warning: Trailing singletons are not removed\n% Example: If the size of A is SIZE0 = [1 1 1 5 9 3]\n% NEWSIZE = DELSING(SIZE, 1, 3) is [5 9 3]\n\n if dim > length(size0)-ns % Trailing singletons are not removed\n newsize = size0;\n flag = false;\n else % Trailing singl. added, so NEWSIZE is guaranteed to be 2D or more\n newsize = size0([1:dim-1, dim+ns:end, dim]);\n flag = true;\n end\n\n\nfunction [newsize, flag] = swapdim(size0, dim)\n%SWAPDIM Swapping two adjacent dimensions of an array (DIM and DIM+1).\n% Used only when both A and B are multi-block arrays with 2-D blocks.\n% Example: If the size of A is .......... 5?(6?3)\n% NEWSIZE = SWAPIDS(SIZE0, 2) is 5?(3?6)\n\n newsize = [size0 1]; % Guarantees that dimension DIM+1 exists.\n newsize = newsize([1:dim-1, dim+1, dim, dim+2:end]);\n flag = true;\n", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/SPD_DR_ECCV2014/local_manopt/multiprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.37833306132342737}} {"text": "function f = times(f, g)\n%.* CHEBFUN multiplication.\n% F.*G multiplies F and G, where F and G may be CHEBFUN objects or scalars.\n% If F and/or G is array-valued, the dimensions must match.\n%\n% See also MTIMES.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Deal with the special cases:\nif ( ~isa(f, 'chebfun') ) % ??? * CHEBFUN\n\n % Ensure CHEBFUN is the first input:\n if ( ~g(1).isTransposed )\n f = times(g, f);\n else\n f = times(g.', f.').';\n end\n\nelseif ( isempty(g) ) % CHEBFUN * []\n\n f = [];\n return\n\nelseif ( isempty(f) ) % empty CHEBFUN * CHEBFUN\n\n % Nothing to do here. (Return an empty CHEBFUN as output.)\n return \n\nelseif ( isnumeric(g) ) % CHEBFUN * double\n\n if ( numel(f) == 1 )\n % Array-valued case:\n\n % Loop over the funs:\n for k = 1:numel(f.funs)\n f.funs{k} = times(f.funs{k}, g);\n end\n\n % Multiply the pointValues:\n if ( numel(g) > 1 )\n f.pointValues = bsxfun(@times, f.pointValues, g);\n else\n f.pointValues = f.pointValues .* g;\n end\n \n else\n % Quasimatrix case:\n\n numCols = numel(f);\n % Promote g if required:\n if ( ~isscalar(g) )\n error('CHEBFUN:CHEBFUN:times:dim', 'Matrix dimensions must agree.');\n end\n % Loop over the columns:\n for k = 1:numCols\n f(k) = f(k).*g;\n end\n \n end\n\n\nelseif ( ~isa(g, 'chebfun') ) % CHEBFUN * ???\n\n error('CHEBFUN:CHEBFUN:times:unknown', ...\n ['Undefined function ''times'' for input arguments of type ' ...\n '%s and %s.'], class(f), class(g));\n\nelse % CHEBFUN .* CHEBFUN \n\n % Check to see if one of the CHEBFUNs is transposed:\n if ( xor(f(1).isTransposed, g(1).isTransposed) )\n error('CHEBFUN:CHEBFUN:times:matdim', ...\n 'Matrix dimensions must agree. (One input is transposed).');\n end\n \n dimCheck(f, g);\n \n if ( numel(f) == 1 && numel(g) == 1 )\n % CHEBFUN case:\n\n % If one of the two CHEBFUNs uses a PERIODICTECH reprensetation, \n % cast it to a NONPERIODICTECH.\n if ( ~isPeriodicTech(f.funs{1}) && isPeriodicTech(g.funs{1}) )\n g = chebfun(g, g.domain, 'tech', get(f.funs{1}, 'tech'));\n elseif ( isPeriodicTech(f.funs{1}) && ~isPeriodicTech(g.funs{1}) )\n f = chebfun(f, f.domain, 'tech', get(g.funs{1}, 'tech'));\n end\n \n % Overlap:\n [f, g] = overlap(f, g);\n\n % Loop over the FUNs:\n for k = 1:numel(f.funs)\n f.funs{k} = times(f.funs{k}, g.funs{k});\n end\n f.pointValues = f.pointValues .* g.pointValues;\n \n else\n % QUASIMATRIX case:\n\n % Convert to cell for simplicity\n f = cheb2cell(f);\n g = cheb2cell(g);\n \n % Loop over the columns:\n if ( numel(f) == 1 )\n for k = numel(g):-1:1\n h(k) = f{1} .* g{k};\n end\n elseif ( numel(g) == 1 )\n for k = numel(f):-1:1\n h(k) = f{k} .* g{1};\n end\n else % numel(f) = numel(g)\n for k = numel(f):-1:1\n h(k) = f{k} .* g{k};\n end\n end\n f = h;\n end\nend\n\n% Set small breakpoint values to zero:\nf = thresholdBreakpointValues(f);\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/@chebfun/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3783112113811143}} {"text": "%扩频函数\nfunction [out] = spread(data, code)\n\n% ****************************************************************\n% data : 输入数据序列\n% code : 扩频码序列\n% out : 扩频后的输出数据序列\n% ****************************************************************\n\nswitch nargin\ncase { 0 , 1 } %如果输入参数个数不对,提示错误\n error('缺少输入参数');\nend\n\n[hn,vn] = size(data);\n[hc,vc] = size(code);\n\nif hn > hc %如果扩频码数小于输入的待扩频的数据序列,提示错误\n error('缺少扩频码序列');\nend\n\nout = zeros(hn,vn*vc);\n\nfor ii=1:hn\n out(ii,:) = reshape(code(ii,:).'*data(ii,:),1,vn*vc);\nend\n\n%******************************** end of file ********************************\n", "meta": {"author": "2417677728", "repo": "OFDM", "sha": "2850c0b77692ae6ed6b292b839513716bfad2447", "save_path": "github-repos/MATLAB/2417677728-OFDM", "path": "github-repos/MATLAB/2417677728-OFDM/OFDM-2850c0b77692ae6ed6b292b839513716bfad2447/spread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3782456102901808}} {"text": "%%*****************************************************************************\n%% checkdepconst: compute AAt to determine if the\n%% constraint matrices Ak are linearly independent.\n%%\n%% [At,b,y,idxB,neardepconstr,feasible,AAt] = checkdepconstr(blk,At,b,y,rmdepconstr);\n%%\n%% rmdepconstr = 1, if want to remove dependent columns in At\n%% = 0, otherwise.\n%%\n%% idxB = indices of linearly independent columns of original At.\n%% neardepconstr = 1 if there is nearly dependent columns in At\n%% = 0, otherwise.\n%% Note: the definition of \"nearly dependent\" is dependent on the\n%% threshold used to determine the small diagonal elements in\n%% the LDLt factorization of A*At.\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 [At,b,y,idxB,neardepconstr,feasible,AAt] = ...\n checkdepconstr(blk,At,b,y,rmdepconstr)\n\nglobal existlowrank printlevel\nglobal nnzmatold\n%%\n%% compute AAt\n%%\nm = length(b);\nAAt = sparse(m,m); numdencol = 0; UU = [];\nfor p = 1:size(blk,1)\n pblk = blk(p,:);\n if strcmp(pblk{1},'s');\n m1 = size(At{p,1},2); m2 = m - m1;\n if (m2 > 0)\n if (m2 > 0.3*m); AAt = full(AAt); end\n dd = At{p,3};\n lenn = size(dd,1);\n idxD = [0; find(diff(dd(:,1))); lenn];\n ss = [0, cumsum(pblk{3})];\n if (existlowrank)\n AAt(1:m1,1:m1) = AAt(1:m1,1:m1) + At{p,1}'*At{p,1}; %#ok\n for k = 1:m2\n idx = ss(k)+1 : ss(k+1);\n idx2 = idxD(k)+1: idxD(k+1);\n ii = dd(idx2,2)-ss(k); %% undo cumulative indexing\n jj = dd(idx2,3)-ss(k);\n len = pblk{3}(k);\n Dk = spconvert([ii,jj,dd(idx2,4); len,len,0]);\n tmp = svec(pblk,At{p,2}(:,idx)*Dk*At{p,2}(:,idx)');\n tmp2 = AAt(1:m1,m1+k) + (tmp'*At{p,1})';\n AAt(1:m1,m1+k) = tmp2; %#ok\n AAt(m1+k,1:m1) = tmp2'; %#ok\n end\n end\n DD = spconvert([dd(:,2:4); sum(pblk{3}),sum(pblk{3}),0]);\n VtVD = (At{p,2}'*At{p,2})*DD;\n VtVD2 = VtVD'.*VtVD;\n for k = 1:m2\n idx0 = ss(k)+1 : ss(k+1);\n %%tmp = VtVD(idx0,:)' .* VtVD(:,idx0);\n tmp = VtVD2(:,idx0);\n tmp = tmp*ones(length(idx0),1);\n tmp3 = AAt(m1+1:m1+m2,m1+k) + mexqops(pblk{3},tmp,ones(length(tmp),1),1);\n AAt(m1+1:m1+m2,m1+k) = tmp3; %#ok\n end\n else\n AAt = AAt + abs(At{p,1})'*abs(At{p,1});\n end\n else\n decolidx = checkdense(At{p,1}');\n if ~isempty(decolidx);\n n2 = size(At{p,1},1);\n dd = ones(n2,1);\n len= length(decolidx);\n dd(decolidx) = zeros(len,1);\n AAt = AAt + (abs(At{p,1})' *spdiags(dd,0,n2,n2)) *abs(At{p,1});\n tmp = At{p,1}(decolidx,:)';\n UU = [UU, tmp]; %#ok\n numdencol = numdencol + len;\n else\n AAt = AAt + abs(At{p,1})'*abs(At{p,1});\n end\n end\nend\nif (numdencol > 0) && (printlevel)\n fprintf('\\n number of dense column in A = %d',numdencol);\nend\nnumdencol = size(UU,2);\n%%\n%%\n%%\nfeasible = 1; neardepconstr = 0;\nif ~issparse(AAt); AAt = sparse(AAt); end\nnnzmatold = mexnnz(AAt);\nrho = 1e-15;\ndiagAAt = diag(AAt);\nmexschurfun(AAt,rho*max(diagAAt,1));\n[L.R,indef,L.perm] = chol(AAt,'vector');\nL.d = full(diag(L.R)).^2;\nif (indef)\n msg = 'AAt is not pos. def.';\n idxB = 1:m;\n neardepconstr = 1;\n if (printlevel); fprintf('\\n checkdepconstr: %s',msg); end\n return;\nend\n%%\n%% find independent rows of A\n%%\ndd = zeros(m,1);\nidxB = (1:m)';\ndd(L.perm) = abs(L.d);\nidxN = find(dd < 1e-13*mean(L.d));\nddB = dd(setdiff(1:m,idxN));\nddN = dd(idxN);\nif ~isempty(ddN) && ~isempty(ddB) && (min(ddB)/max(ddN) < 10)\n %% no clear separation of elements in dd\n %% do not label constraints as dependent\n idxN = [];\nend\nif ~isempty(idxN)\n neardepconstr = 1;\n if (printlevel)\n fprintf('\\n number of nearly dependent constraints = %1.0d',length(idxN));\n end\n if (numdencol==0)\n if (rmdepconstr)\n idxB = setdiff((1:m)',idxN);\n if (printlevel)\n fprintf('\\n checkdepconstr: removing dependent constraints...');\n end\n [W,resnorm] = findcoeffsub(blk,At,idxB,idxN);\n tol = 1e-8;\n if (resnorm > sqrt(tol))\n idxB = (1:m)';\n neardepconstr = 0;\n if (printlevel)\n fprintf('\\n checkdepconstr: basis rows cannot be reliably identified,');\n fprintf(' abort removing nearly dependent constraints');\n end\n return;\n end\n tmp = W'*b(idxB) - b(idxN);\n nnorm = norm(tmp)/max(1,norm(b));\n if (nnorm > tol)\n feasible = 0;\n if (printlevel)\n fprintf('\\n checkdepconstr: inconsistent constraints exist,');\n fprintf(' problem is infeasible.');\n end\n else\n feasible = 1;\n for p = 1:size(blk,1)\n At{p,1} = At{p,1}(:,idxB);\n end\n b = b(idxB);\n y = y(idxB);\n AAt = AAt(idxB,idxB);\n end\n else\n if (printlevel)\n fprintf('\\n To remove these constraints,');\n fprintf(' re-run sqlp.m with OPTIONS.rmdepconstr = 1.');\n end\n end\n else\n if (printlevel)\n fprintf('\\n warning: the sparse part of AAt may be nearly singular.');\n end\n end\nend\n%%*****************************************************************************\n%% findcoeffsub:\n%%\n%% [W,resnorm] = findcoeffsub(blk,At,idXB,idXN);\n%%\n%% idXB = indices of independent columns of At.\n%% idxN = indices of dependent columns of At.\n%%\n%% AB = At(:,idxB); AN = At(:,idxN) = AB*W\n%%\n%% SDPT3: version 3.0\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last modified: 2 Feb 01\n%%*****************************************************************************\n\nfunction [W,resnorm] = findcoeffsub(blk,At,idxB,idxN)\n\nAB = []; AN = [];\nfor p = 1:size(blk,1)\n AB = [AB; At{p,1}(:,idxB)]; %#ok\n AN = [AN; At{p,1}(:,idxN)]; %#ok\nend\nn = size(AB,2);\n%%\n%%-----------------------------------------\n%% find W so that AN = AB*W\n%%-----------------------------------------\n%%\n[L,U,P,Q] = lu(sparse(AB));\nrhs = P*AN;\nLhat = L(1:n,:);\nW = Q*( U \\ (Lhat \\ rhs(1:n,:)));\nresnorm = norm(AN-AB*W,'fro')/max(1,norm(AN,'fro'));\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/checkdepconstr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3781987614322146}} {"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\ndx = Lx/Nx; % Eulerian Grid-step in x-direction\ndy = Ly/Ny; % Eulerian Grid-step 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);\nyLag = yLag - 1.25;\n\n\nfprintf('\\nUSER-INPUT FOR MODEL IN FITZHUGH_NAGUMO_1d:\\n');\nfprintf('numPtsAlongTube = %d\\n',length(xLag)/2);\nfprintf('ind_Start = %d\\n',length(xLag)-2+1);\nfprintf('ind_End = %d\\n\\n',length(xLag)-2+length(xLag)/2)\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\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,d,struct_name);\n\n% Prints .muscle file!\n%LFO = d; SK = 0.3; a = 0.25; b = 4.0; Fmax = 1e5;\n%print_Lagrangian_Muscles(xLag,LFO,SK,a,b,Fmax,struct_name)\n\n\n% Prints .beam file!\nk_Beam = 2.5e6; C = 0.0;\nprint_Lagrangian_Beams(xLag,k_Beam,C,struct_name);\n\n\n% Prints .target file!\nk_Target = 1e7;\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name);\n\n% Prints .concentration file!\nkDiffusion = 5e-5;\nConcentration = give_Me_Initial_Concentration(Lx,Ly/2,Nx,Ny/2,dx,dy);\nprint_Concentration_Info(Nx,Ny/2,Concentration,kDiffusion,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,d,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/2 ); %(N-2) btwn adajcent Lag. Pts, (N/2) btwn opposite sides of HT\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 \n for s = 1:N/2\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+N/2, k_Spring/1e10, 0.0); \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\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints CONCENTRATION INFO to file called\n% 'struct_name'.concentration\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \nfunction print_Concentration_Info(Nx,Ny,C,kDiffusion,struct_name)\n\n con_fid = fopen([struct_name '.concentration'], 'w');\n \n fprintf(con_fid, '%d\\n', kDiffusion );\n\n for i=1:Ny\n for j=1:Nx\n fprintf(con_fid, '%1.16e ', C(i,j) );\n end\n fprintf(con_fid,'\\n');\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives initial concentration gradient inside channel\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = give_Me_Initial_Concentration(Lx,Ly,Nx,Ny,dx,dy)\n\n%WHERE OUTER TUBE LIES\n%xMin = 0.15; xMax = 0.45;\n%yMin = 0.85; yMax = 1.15;\n\nxMin = 1.6; xMax = 2.2;\nyMin = 0.8; yMax = 1.7;\n\nxMid = (xMin+xMax)/2;\nyMid = (yMin+yMax)/2;\n\nxDiff = (xMax-xMin)/2;\nyDiff = (yMax-yMin)/2;\n\nx = 0:dx:Lx;\ny = 0:dy:Ly;\ninds = give_Me_Indices_To_Apply_Force(x,y,xMin,xMax,yMin,yMax);\n\nC = zeros(Ny,Nx);\nfor i=1:length( inds(:,1) )\n xInd = inds(i,1);\n yInd = inds(i,2);\n xPt = x(xInd);\n yPt = y(yInd);\n %C(xInd,yInd ) = (-0.5/yDiff^2)*( (yPt-yMid) - yDiff )*( (yPt-yMid) + yDiff ) + (-0.5/xDiff^2)*( (xPt-xMid) - xDiff )*( (xPt-xMid) + xDiff ); %1.0;\n C(yInd,xInd ) = (-1.0/xDiff^2)*( (xPt-xMid) - xDiff )*( (xPt-xMid) + xDiff ); %1.0;\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes indices for placing initial concentration \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction inds = give_Me_Indices_To_Apply_Force(x,y,xMin,xMax,yMin,yMax)\n\nj=1; noMinYet = 1;\nwhile noMinYet\n \n if ( x(j) >= xMin )\n iX_min = j;\n noMinYet = 0;\n end\n j=j+1;\nend\n\nj=length(x); noMaxYet = 1;\nwhile noMaxYet\n \n if ( x(j) <= xMax )\n iX_max = j;\n noMaxYet = 0;\n end\n j=j-1;\nend\n\nj=1; noMinYet = 1;\nwhile noMinYet\n \n if ( y(j) >= yMin )\n iY_min = j;\n noMinYet = 0;\n end\n j=j+1;\nend\n\nj=length(y); noMaxYet = 1;\nwhile noMaxYet\n \n if ( y(j) <= yMax )\n iY_max = j;\n noMaxYet = 0;\n end\n j=j-1;\nend\n\niX_Vec = iX_min:1:iX_max;\niY_Vec = iY_min:1:iY_max;\n\nn = 1;\nfor i=1:length(iX_Vec)\n for j=1:length(iY_Vec)\n inds(n,1) = iX_Vec(i);\n inds(n,2) = iY_Vec(j);\n n = n+1; \n end\nend\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/128x128_Electromechanical_Pumping_w_Ca_Dynamics/HeartTube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3778102212788976}} {"text": "function lik = lik_inputdependentnoise(varargin)\n%lik_inputdependentnoise Create input-dependent noise likelihood structure \n%\n% Description\n% LIK = LIK_INPUTDEPENDENTNOISE('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% creates a Gaussian likelihood with input dependent noise structure \n% in which the named parameters have the specified values. Any unspecified\n% parameters are set to default values.\n%\n% LIK = LIK_INPUTDEPENDENTNOISE(LIK,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a likelihood function structure with the named\n% parameters altered with the specified values.\n%\n% Parameters for Gaussian likelihood function [default]\n% sigma2 - variance [0.1]\n% sigma2_prior - prior for sigma2 [prior_logunif]\n% n - number of observations per input (See using average\n% observations below)\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|f1, f2) = || i=1 N(y_i | f1_i, sigma2*exp(f2_i))\n%\n% where f1 is the first latent variable defining the mean of the\n% gaussian distribution, f2 is the second latent variable defining\n% the noise structure and sigma2 is coefficient for noise.\n%\n% See also\n% GP_SET, LIK_*, PRIOR_*\n%\n% Copyright (c) 2007-2010 Jarno Vanhatalo & Jouni Hartikainen\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2011 Ville Tolvanen\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_INPUTDEPENDENTNOISE';\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.parse(varargin{:});\n lik=ip.Results.lik;\n \n if isempty(lik)\n init=true;\n lik.nondiagW=true;\n lik.type = 'Inputdependentnoise';\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'Inputdependentnoise')\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 % 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 \n if init\n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_inputdependentnoise_pak;\n lik.fh.unpak = @lik_inputdependentnoise_unpak;\n lik.fh.lp = @lik_inputdependentnoise_lp;\n lik.fh.lpg = @lik_inputdependentnoise_lpg;\n lik.fh.ll = @lik_inputdependentnoise_ll;\n lik.fh.llg = @lik_inputdependentnoise_llg; \n lik.fh.llg2 = @lik_inputdependentnoise_llg2;\n lik.fh.llg3 = @lik_inputdependentnoise_llg3;\n lik.fh.predy = @lik_inputdependentnoise_predy;\n lik.fh.invlink = @lik_inputdependentnoise_invlink;\n lik.fh.predprcty = @lik_inputdependentnoise_predprcty;\n lik.fh.recappend = @lik_inputdependentnoise_recappend;\n end\n\n function [w,s,h] = lik_inputdependentnoise_pak(lik)\n %LIK_INPUTDEPENDENTNOISE_PAK Combine likelihood parameters into one vector.\n %\n % Description \n % W = LIK_INPUTDEPENDENTNOISE_PAK(LIK) takes a likelihood structure LIK and\n % combines the parameters into a single row vector W. This is a mandatory \n % subfunction used for example in energy and gradient computations.\n % \n % w = log(lik.sigma2)\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_UNPAK, GP_PAK\n \n w = []; s = {}; h=[];\n if isfield(lik.p, 'sigma2') && ~isempty(lik.p.sigma2)\n w = [w log(lik.sigma2)];\n s = [s 'log(gaussian.sigma2)'];\n h = [h 0];\n % Hyperparameters of sigma2\n [wh, sh, hh] = lik.p.sigma2.fh.pak(lik.p.sigma2);\n w = [w wh];\n s = [s sh];\n h = [h hh];\n end \n end\n\n\n function [lik, w] = lik_inputdependentnoise_unpak(lik, w)\n %LIK_INPUTDEPENDENTNOISE_UNPAK Extract likelihood parameters from the vector.\n %\n % Description\n % [LIK, W] = LIK_INPUTDEPENDENTNOISE_UNPAK(W, LIK) takes a likelihood\n % structure LIK and extracts the parameters from the vector W\n % to the LIK structure. This is a mandatory subfunction used for \n % example in energy and gradient computations.\n % \n % Assignment is inverse of \n % w = log(lik.sigma2)\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_PAK, GP_UNPAK\n\n if ~isempty(lik.p.sigma2)\n lik.sigma2 = exp(w(1));\n w = w(2:end);\n \n % Hyperparameters of sigma2\n [p, w] = lik.p.sigma2.fh.unpak(lik.p.sigma2, w);\n lik.p.sigma2 = p;\n end\n end\n\n\n function lp = lik_inputdependentnoise_lp(lik, varargin)\n %LIK_INPUTDEPENDENTNOISE_LP log(prior) of the likelihood parameters\n %\n % Description\n % LP = LIK_INPUTDEPENDENTNOISE_LP(LIK) takes a likelihood structure \n % LIK and returns log(p(th)), where th collects the parameters. This\n % subfunction is needed when there are likelihood parameters.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LLG, LIK_INPUTDEPENDENTNOISE_LLG3, LIK_INPUTDEPENDENTNOISE_LLG2, GPLA_E\n \n\n % If prior for sigma2 parameter, add its contribution\n lp = 0;\n\n if ~isempty(lik.p.sigma2)\n likp=lik.p;\n lp = likp.sigma2.fh.lp(lik.sigma2, likp.sigma2) + log(lik.sigma2);\n end\n \n end\n\n \n function lpg = lik_inputdependentnoise_lpg(lik)\n %LIK_INPUTDEPENDENTNOISE_LPG d log(prior)/dth of the likelihood \n % parameters th\n %\n % Description\n % E = LIK_INPUTDEPENDENTNOISE_LPG(LIK) takes a likelihood structure \n % LIK and returns d log(p(th))/dth, where th collects the parameters.\n % This subfunction is needed when there are likelihood parameters.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LLG, LIK_INPUTDEPENDENTNOISE_LLG3, LIK_INPUTDEPENDENTNOISE_LLG2, GPLA_G\n \n\n lpg = [];\n \n if ~isempty(lik.p.sigma2)\n likp=lik.p;\n \n lpgs = likp.sigma2.fh.lpg(lik.sigma2, likp.sigma2);\n lpg = lpgs(1).*lik.sigma2 + 1;\n if length(lpgs) > 1\n lpg = [lpg lpgs(2:end)];\n end\n end\n end \n \n function ll = lik_inputdependentnoise_ll(lik, y, ff, z)\n %LIK_INPUTDEPENDENTNOISE_LL Log likelihood\n %\n % Description\n % LL = LIK_INPUTDEPENDENTNOISE_LL(LIK, Y, F, Z) takes a likelihood\n % structure LIK, incedence counts Y, expected counts Z, and\n % latent values F. Returns the log likelihood, log p(y|f,z).\n % This subfunction is needed when using Laplace approximation \n % or MCMC for inference with non-Gaussian likelihoods. This\n % subfunction is also used in information criteria (DIC, WAIC)\n % computations.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LLG, LIK_INPUTDEPENDENTNOISE_LLG3, LIK_INPUTDEPENDENTNOISE_LLG2, GPLA_E\n \n \n f=ff(:);\n n=size(y,1);\n f1=f(1:n);\n f2=f((n+1):2*n);\n expf2=exp(f2);\n expf2(expf21e6)=1e6;\n sigma2 = lik.sigma2;\n \n ll = sum(-0.5*log(2*pi.*sigma2.*expf2) - 1./(2.*sigma2.*expf2).*(y-f1).^2);\n \n end\n\n function llg = lik_inputdependentnoise_llg(lik, y, ff, param, z)\n %LIK_INPUTDEPENDENTNOISE_LLG Gradient of the log likelihood\n %\n % Description \n % LLG = LIK_INPUTDEPENDENTNOISE_LLG(LIK, Y, F, PARAM) takes a likelihood\n % structure LIK, incedence counts Y, expected counts Z and\n % latent values F. Returns the gradient of the log likelihood\n % with respect to PARAM. At the moment PARAM can be 'param' or\n % 'latent'. This subfunction is needed when using Laplace\n % approximation or MCMC for inference with non-Gaussian likelihoods.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LL, LIK_INPUTDEPENDENTNOISE_LLG2, LIK_INPUTDEPENDENTNOISE_LLG3, GPLA_E\n\n\n f=ff(:);\n n=size(y,1);\n f1=f(1:n);\n f2=f((n+1):2*n);\n expf2 = exp(f2);\n expf2(expf21e6)=1e6;\n sigma2 = lik.sigma2;\n \n switch param\n case 'param'\n \n llg=sum(-0.5./sigma2+(y-f1).^2./(2*expf2.*sigma2^2));\n % correction for the log transformation\n llg = llg.*lik.sigma2;\n \n case 'latent'\n \n llg1= (y-f1)./(sigma2*expf2);\n llg2= -0.5+(y-f1).^2./(2.*(expf2.*sigma2));\n \n% llg1=(-y+f1)/(sqrt(2*pi).*(sigma2.*expf2).^(3/2)).*exp(-1/(2.*sigma2*expf2).*(y-f1).^2);\n% llg2=-exp(f2-(y-f1).^2/(2.*expf2.*sigma2)).*sigma2/(2.*sqrt(2.*pi).*(expf2.*sigma2).^(3/2))+exp(-f2-(y-f1).^2/(2*expf2*sigma2)).*(y-f1).^2/(2.*sqrt(2.*pi.*expf2).*sigma2.^(3/2));\n \n llg=[llg1; llg2];\n end\n end\n\n function [llg2] = lik_inputdependentnoise_llg2(lik, y, ff, param, z)\n %function [pi_vec, pi_mat] = lik_inputdependentnoise_llg2(lik, y, ff, param, z)\n %LIK_INPUTDEPENDENTNOISE_LLG2 Second gradients of the log likelihood\n %\n % Description \n % LLG2 = LIK_INPUTDEPENDENTNOISE_LLG2(LIK, Y, F, PARAM) takes a likelihood\n % structure LIK, incedence counts Y, expected counts Z, and\n % latent values F. Returns the Hessian of the log likelihood\n % with respect to PARAM. At the moment PARAM can be only\n % 'latent'. LLG2 is a vector with diagonal elements of the\n % Hessian matrix (off diagonals are zero). This subfunction\n % is needed when using Laplace approximation or EP for\n % inference with non-Gaussian likelihoods.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LL, LIK_INPUTDEPENDENTNOISE_LLG, LIK_INPUTDEPENDENTNOISE_LLG3, GPLA_E\n\n\n f=ff(:);\n \n n=length(y);\n f1=f(1:n);\n f2=f((n+1):2*n);\n sigma2 = lik.sigma2;\n expf2=exp(f2);\n expf2(expf21e6)=1e6;\n\n switch param\n case 'param'\n \n case 'latent'\n \n% llg2 = [2./(sigma2.*expf2); 3/2.*(y-f1).^2./(sigma2.*expf2)];\n% llg2mat = [diag(1./sqrt(sigma2.*expf2)); diag(-(y-f1)./sqrt(sigma2.*expf2))];\n \n llg2_11=-1./(sigma2.*expf2);\n llg2_12=-(y-f1)./(sigma2*expf2);\n llg2_22=-(y-f1).^2./(2.*sigma2.*expf2);\n \n llg2 = [llg2_11 llg2_12; llg2_12 llg2_22];\n \n case 'latent+param'\n \n llg2_1=-(y-f1)./(expf2.*sigma2^2);\n llg2_2=-(y-f1).^2./(2*sigma2.^2.*expf2);\n \n llg2=[llg2_1; llg2_2];\n % correction for the log transformation\n llg2 = llg2.*lik.sigma2;\n \n end\n end \n \n function llg3 = lik_inputdependentnoise_llg3(lik, y, ff, param, z)\n %LIK_INPUTDEPENDENTNOISE_LLG3 Third gradients of the log likelihood\n %\n % Description\n % LLG3 = LIK_INPUTDEPENDENTNOISE_LLG3(LIK, Y, F, PARAM) takes a likelihood\n % structure LIK, incedence counts Y, expected counts Z and\n % latent values F and returns the third gradients of the log\n % likelihood with respect to PARAM. At the moment PARAM can be\n % only 'latent'. LLG3 is a vector with third gradients. This\n % subfunction is needed when using Laplace approximation for\n % inference with non-Gaussian likelihoods.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LL, LIK_INPUTDEPENDENTNOISE_LLG, LIK_INPUTDEPENDENTNOISE_LLG2, GPLA_E, GPLA_G\n\n f=ff(:);\n \n n=size(y,1);\n f1=f(1:n);\n f2=f((n+1):2*n);\n expf2=exp(f2);\n expf2(expf21e6)=1e6;\n sigma2 = lik.sigma2;\n \n switch param\n case 'param'\n \n case 'latent'\n nl=2;\n llg3=zeros(nl,nl,nl,n);\n \n % y=0:\n % thrid derivative derivative wrt f1 (11)\n % llg3(1,1,1,:) = 0\n % thrid derivative derivative wrt f2 (11)\n llg3(1,1,2,:) = 1./(expf2.*sigma2);\n \n % thrid derivative derivative wrt f1 (12/21)\n llg3(1,2,1,:) = 1./(expf2.*sigma2);\n llg3(2,1,1,:) = llg3(1,2,1,:);\n % thrid derivative derivative wrt f2 (12/21)\n llg3(1,2,2,:) = (y-f1)./(expf2.*sigma2);\n llg3(2,1,2,:) = llg3(1,2,2,:);\n \n % thrid derivative derivative wrt f1 (22)\n llg3(2,2,1,:) = llg3(1,2,2,:);\n % thrid derivative derivative wrt f1 (22)\n llg3(2,2,2,:) = (y-f1).^2./(2.*expf2.*sigma2);\n \n case 'latent2+param'\n \n llg3_11=1./(expf2.*sigma2.^2);\n llg3_12=(y-f1)./(expf2.*sigma2.^2);\n llg3_22=(y-f1).^2./(2.*expf2.*sigma2.^2);\n \n \n llg3 = [diag(llg3_11) diag(llg3_12); diag(llg3_12) diag(llg3_22)];\n % correction for the log transformation\n llg3 = llg3.*lik.sigma2;\n \n end\n end\n \n\n function [lpy, Ey, Vary] = lik_inputdependentnoise_predy(lik, Ef, Varf, yt, z)\n %LIK_INPUTDEPENDENTNOISE_PREDY Returns the predictive mean, variance and density of y\n %\n % Description \n % [LPY] = LIK_INPUTDEPENDENTNOISE_PREDY(LIK, EF, VARF, YT) takes a\n % likelihood structure LIK, posterior mean EF, posterior\n % variance VARF of the latent variable and observations YT and \n % returns the logarithm of the predictive density PY of YT, that is \n % p(yt | th) = \\int p(yt | f, th) p(f|y) df.\n % This subfunction is needed when computing posterior predictive \n % distributions for future observations.\n % \n % [LPY, EY, VARY] = LIK_INPUTDEPENDENTNOISE_PREDY(LIK, EF, VARF YT)\n % Returns also the posterior predictive mean EY and variance VARY of \n % the observations related to the latent variables. This subfunction \n % is needed when computing posterior predictive distributions for \n % future observations.\n %\n % See also\n % GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n\n% ntest=size(yt,1);\n Ef = Ef(:);\n ntest = 0.5*size(Ef,1);\n Ef1=Ef(1:ntest); Ef2=Ef(ntest+1:end);\n if size(Varf,2) == size(Varf,1)\n Varf1=diag(Varf(1:ntest,1:ntest));Varf2=diag(Varf(ntest+1:end,ntest+1:end));\n else\n if size(Varf,2)==1\n Varf=reshape(Varf,ntest,2);\n end\n Varf1=Varf(:,1); Varf2=Varf(:,2);\n end\n sigma2=lik.sigma2;\n \n lpy = zeros(size(yt));\n \n Ey=Ef1;\n Vary=Varf1 + sigma2.*exp(Ef2+Varf2/2);\n \n if ~isempty(yt)\n for i2=1:ntest\n m1=Ef1(i2); m2=Ef2(i2);\n s1=sqrt(Varf1(i2)); s2=sqrt(Varf2(i2));\n pd=@(f1,f2) norm_pdf(yt(i2), f1, sqrt(sigma2.*exp(f2))).*norm_pdf(f1,Ef1(i2),sqrt(Varf1(i2))).*norm_pdf(f2,Ef2(i2),sqrt(Varf2(i2)));\n lpy(i2) = log(dblquad(pd, m1-6.*s1, m1+6.*s1, m2-6.*s2, m2+6.*s2));\n end\n else\n lpy=[];\n end\n% sigma2 = lik.sigma2;\n% Ef1=Ef(1:ntest);\n% Ef2=Ef((ntest+1):2*ntest);\n% Ey = Ef1;\n% Vary = Varf + sigma2.*exp(Ef2);\n \n\n end\n\n function prctys = lik_inputdependentnoise_predprcty(lik, Ef, Varf, zt, prcty)\n %LIK_BINOMIAL_PREDPRCTY Returns the percentiles of predictive density of y\n %\n % Description\n % PRCTY = LIK_BINOMIAL_PREDPRCTY(LIK, EF, VARF YT, ZT)\n % Returns percentiles of the predictive density PY of YT, that is\n % This requires also the succes counts YT, numbers of trials ZT. This\n % subfunction is needed when using function gp_predprcty.\n %\n % See also\n % GP_PREDPCTY\n \n n=size(Ef,1)./2;\n prcty = prcty./100;\n prcty = norminv(prcty, 0, 1);\n prctys = bsxfun(@plus, Ef(1:n), bsxfun(@times, sqrt(Varf(1:n) + lik.sigma2.*exp(Ef(n+1:end))), prcty));\n \n end\n\n function p = lik_inputdependentnoise_invlink(lik, f, z)\n %LIK_INPUTDEPENDENTNOISE_INVLINK Returns values of inverse link function\n % \n % Description \n % P = LIK_INPUTDEPENDENTNOISE_INVLINK(LIK, F) takes a likelihood structure LIK and\n % latent values F and returns the values of inverse link function P.\n % This subfunction is needed when using function gp_predprcty.\n %\n % See also\n % LIK_INPUTDEPENDENTNOISE_LL, LIK_INPUTDEPENDENTNOISE_PREDY\n \n p = exp(f);\n end\n \n function reclik = lik_inputdependentnoise_recappend(reclik, ri, lik)\n %RECAPPEND Append the parameters to the record\n %\n % Description \n % RECLIK = GPCF_INPUTDEPENDENTNOISE_RECAPPEND(RECLIK, RI, LIK) takes a\n % likelihood record structure RECLIK, record index RI and\n % likelihood structure LIK with the current MCMC samples of\n % the parameters. Returns RECLIK which contains all the old\n % samples and the current samples from LIK. This subfunction \n % is needed when using MCMC sampling (gp_mc).\n % \n % See also\n % GP_MC\n\n % Initialize record\n if nargin == 2\n reclik.type = 'Inputdependentnoise';\n reclik.nondiagW=true;\n\n % Initialize parameter\n\n % Set the function handles\n reclik.fh.pak = @lik_inputdependentnoise_pak;\n reclik.fh.unpak = @lik_inputdependentnoise_unpak;\n reclik.fh.lp = @lik_inputdependentnoise_lp;\n reclik.fh.lpg = @lik_inputdependentnoise_lpg;\n reclik.fh.ll = @lik_inputdependentnoise_ll;\n reclik.fh.llg = @lik_inputdependentnoise_llg; \n reclik.fh.llg2 = @lik_inputdependentnoise_llg2;\n reclik.fh.llg3 = @lik_inputdependentnoise_llg3;\n reclik.fh.predy = @lik_inputdependentnoise_predy;\n reclik.fh.predprcty = @lik_inputdependentnoise_predprcty;\n reclik.fh.invlink = @lik_inputdependentnoise_invlink;\n reclik.fh.recappend = @lik_inputdependentnoise_recappend;\n reclik.p=[];\n if ~isempty(ri.p.sigma2)\n reclik.p.sigma2 = ri.p.sigma2;\n end\n return\n end\n \n reclik.sigma2(ri,:)=lik.sigma2;\n if ~isempty(lik.p.sigma2)\n reclik.p.sigma2 = feval(lik.p.sigma2.fh.recappend, reclik.p.sigma2, ri, lik.p.sigma2);\n end\n end\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/lik_inputdependentnoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.37768882231239476}} {"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: battistn@tcnj.edu\n% Current Institution: TCNJ\n% Date Modified: April 2021\n% \n% Date Created: May 27th, 2015\n% Institution when Created: UNC-CH\n%\n% This code is capable of creating Lagrangian Structures using:\n% \t1. Springs\n% \t2. Beams (*torsional springs or non-invariant beams*)\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 lengths, 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 (battistn@tcnj.edu) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the LEAF_LEAF-EXAMPLE geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Leaf_Leaf()\n\n%-----------------------------------------------------\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%-----------------------------------------------------\nNx = 384 % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nNy = 64 % # of Eulerian Grid Pts. in y-Direction (MUST BE EVEN!!!)\nLx = 30.0 % Length of Eulerian Grid in x-Direction (cm)\nLy = 5.0 % Length of Eulerian Grid in y-Direction (cm)\nds= 0.5*Lx/Nx; % Lagrangian spacing\n\n\n%----------------------------------------------------------------\n% AIR PROPERTIES FOR INPUT\n%\n% Density: [rho] = kg/m^3\n% Newton: [N] = kg * m/s^2\n% Dyn. Visc.: [N*s/m^2] = (kg*m/s^2)*(s/m^2) = kg / (m*s)\n% \n%----------------------------------------------------------------\n% PROPERTIES IN MKS UNITS\n%mu_Air = 18.03e-6; % N*s/m^2 dynamic viscosity of air at 18C (64.4F)\n%rho_Air = 1.21; % kg/m^3 density of air at 18C\nmu_Air = 1.895e-5; % N*s/m^2 = dynamic viscosity of air at 18C (64.4F)\nrho_Air = 1.145; % kg/m^3 density of air at 35C\n%(from https://www.engineersedge.com/physics/viscosity_of_air_dynamic_and_kinematic_14483.htm)\n%\n% CONVERT TO CGS UNITS\nmu_Air = mu_Air * (1000/1) * (1/100) %(1000g/1kg) & (1m/100cm) \nrho_Air = rho_Air * (1000/1) * (1/100)^3 %(1000g/1kg) & (1m/100cm) \n%\n% FINAL UNITS\n% [mu_Air] = g/(cm*s)\n% [rho_Air] = g/cm^3\n\n\n%----------------------------------------------------\n% LEAF GEOMETRY\n%----------------------------------------------------\nxLag = []; % Initialize Storage\nyLag = []; % Initialize Storage\nL_leaf = 1.0; % Length of tail off cylinder\nstruct_name = 'leaf'; % Name for .vertex, .spring, etc files\n%\nx0 = 3.0; % Starting x-Pt for LEAF\ny0 = Ly/2; % Starting y_Pt for LEAF\n%\nxLag_L = x0:ds:x0+L_leaf;\nyLag_L = y0*ones(1,length(xLag_L));\n\n\n%----------------------------------------------------\n% IF CHANNEL WALLS / CYLINDRICAL LEADING EDGE %\n%----------------------------------------------------\nr = 0.01; % Radii of Cylinder\n\n%--------------------------------------------\n% Call function to construct geometry\n% * No Channel Walls\n% * No Cylinder on Leading Edge\n%--------------------------------------------\n[xLag_Cy,yLag_Cy] = give_Me_Cylinder_Immersed_Boundary_Geometry(ds,r,x0,y0);\n% \n% % Plot Geometry to test\n% plot(xLag_Ch(1:end/2),yLag_Ch(1:end/2),'r-'); hold on;\n% plot(xLag_Ch(end/2+1:end),yLag_Ch(end/2+1:end),'r-'); hold on;\n% plot(xLag_Cy,yLag_Cy,'r-'); hold on;\n% plot(xLag_L,yLag_L,'m-'); hold on;\n% axis([0 Lx 0 Ly]);\n% %\n% plot(xLag_Ch,yLag_Ch,'*'); hold on;\n% plot(xLag_Cy,yLag_Cy,'g*'); hold on;\n% xlabel('x'); ylabel('y');\n% axis square;\n% \n% xLag = [xLag xLag_Ch xLag_Cy]; % Add xLagPts from Circle to xLag Pt. Vector (*no springs or beams*)\n% yLag = [yLag yLag_Ch yLag_Cy]; % Add xLagPts from Circle to xLag Pt. Vector (*no springs or beams*)\n% \n% Nbefore = length(xLag); % # of Lagrangian Pts Before Leaf to COUNT for...\n% % ... Cylinder / Channel Points have TARGET PTS\n%\n\nxLag = [xLag xLag_Cy]; % Add xLagPts from Circle to xLag Pt. Vector (*no springs or beams*)\nyLag = [yLag yLag_Cy]; % Add xLagPts from Circle to xLag Pt. Vector (*no springs or beams*)\n\nNbefore = length(xLag); % # of Lag Pts Before Leaf Starts\n \nxLag = [xLag xLag_L]; % Update xLag Pts to Include Leaf\nyLag = [yLag yLag_L]; % Update xLag Pts to Include Leaf\n\nNtot = length(xLag); % Total # of Lag Pts\n\n%------------------------\n% PLOT GEOMETRY\n%------------------------\nplot(xLag,yLag,'.'); hold on;\nxlabel('x'); ylabel('y');\naxis([0 Lx 0 Ly]);\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .spring file!\nk_Spring = 2.5e4; %1e7\nprint_Lagrangian_Springs(xLag,yLag,k_Spring,struct_name,Nbefore,Ntot);\n\n\n% Prints .beam file!\nk_Beam = 2e8; C = 0.0; %2e12 -> 4e12\nprint_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name,Nbefore,Ntot);\n\n\n% Prints .target file!\nk_Target = 2.5e4;\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name,Nbefore);\n\n\n% Prints .mass file!\nk_Mass = 1e0; % 'spring' stiffness parameter for tethering\nMass = 0.5e-3; % \"MASS\" value for 'ghost' lag movement\nprint_Lagrangian_Mass_Pts(xLag,k_Mass,Mass,struct_name,Nbefore,Ntot);\n\n% Call function for initial concentration\n[Concentration]= give_Me_Initial_Concentration(Nx,Ny);\n\n% Prints .concentration file!\nprint_Concentration_Info(Nx,Ny,Concentration,struct_name);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called .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 .target\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Target_Pts(xLag,k_Target,struct_name,Nbefore)\n\n %N = length(xLag);\n\n target_fid = fopen([struct_name '.target'], 'w');\n\n fprintf(target_fid, '%d\\n', Nbefore+3 );\n\n %Loops over any Channel/Cylinder Pts AND First 3 Pts Along LEAF\n for s = 1:Nbefore+3\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 BEAMs (Torsional Springs) to a file called .beam\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name,Nbefore,Ntot)\n \n % k_Beam: beam stiffness\n % C: beam curvature\n \n if Nbefore ~= 0\n N = Ntot-Nbefore-1;\n else\n N = Ntot-Nbefore-2; % NOTE: Total number of beams \n end\n \n \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 %------------------------------------------------\n % BEAM BETWEEN CYLINDER AND LEAF\n % (including those TETHERED in place by \n % TARGET PTS)\n %------------------------------------------------\n if Nbefore ~= 0 \n s1 = Nbefore;\n s2 = Nbefore+1;\n s3 = Nbefore+2;\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s1, s2, s3, k_Beam, C); \n end\n\n %------------------------------------------------\n % BEAM BETWEEN VERTICES ALONG \"LEAF\"\n % (including those TETHERED in place by \n % TARGET PTS)\n %------------------------------------------------\n for s = Nbefore+2:Ntot-1\n s1 = s-1;\n s2 = s;\n s3 = s+1;\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s1, s2, s3, k_Beam, C); \n end\n fclose(beam_fid); \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called .spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,k_Spring,struct_name,Nbefore,Ntot)\n\n if Nbefore ~= 0\n N = Ntot-Nbefore;\n else\n N = Ntot-Nbefore-1;\n end\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 %------------------------------------------------\n % SPRINGS BETWEEN CYLINDER AND LEAF\n % (including those TETHERED in place by \n % TARGET PTS)\n %------------------------------------------------\n if Nbefore ~= 0\n \n % springs between adjacent pts on cylinder\n for i=1:Nbefore\n if i.mass\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n \nfunction print_Lagrangian_Mass_Pts(xLag,kMass,Mass,struct_name,Nbefore,Ntot)\n\n %LOOP OVER LAG PTS FOR MASS PTS IN LAGRANGIAN INDEXING\n N = (Ntot-Nbefore);\n \n mass_fid = fopen([struct_name '.mass'], 'w');\n\n fprintf(mass_fid, '%d\\n', N );\n\n %Loops over all Lagrangian Pts.\n for s = Nbefore+1:Ntot%Nbefore:Ntot\n fprintf(mass_fid, '%d %1.16e %1.16e\\n', s, kMass, Mass );\n end\n \n fclose(mass_fid); \n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for channel\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Channel_Immersed_Boundary_Geometry(ds,L,w,Lx,Ly)\n\n% The immsersed structure is a channel %\nx = (Lx-L)/2:ds:(L+(Lx-L)/2); %xPts\nyBot = (Ly-w)/2; %yVal for bottom of Channel\nyTop = Ly - (Ly-w)/2; %yVal for top of Channel\n\nxLag = [x x];\nyLag = [yBot*ones(1,length(x)) yTop*ones(1,length(x))];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for cylinder\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLagN,yLagN] = give_Me_Cylinder_Immersed_Boundary_Geometry(ds,r,x0,y0)\n\n% The immsersed structure is a cylinder %\n\ndtheta = ds/ (4*r);\ntheta = 0; i=1;\nwhile theta < 2*pi\n xLag(i) = (x0-r-ds) + r*cos(theta);\n yLag(i) = y0 + r*sin(theta);\n theta = theta + dtheta;\n i=i+1;\nend\n\nfor i=1:length(xLag)\n xLagN(i) = xLag(end-(i-1));\n yLagN(i) = yLag(end-(i-1));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints initial concentration to a file called\n% .concentration\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\nfunction print_Concentration_Info(Nx,Ny,C,struct_name)\n\n con_fid = fopen([struct_name '.concentration'], 'w');\n\n for i=1:Ny\n for j=1:Nx\n fprintf(con_fid, '%1.16e ', C(i,j) );\n end\n fprintf(con_fid,'\\n');\n end \n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives initial concentration gradient inside channel\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [C] = give_Me_Initial_Concentration(Nx,Ny)\n\nC = zeros(Ny,Nx);\n\n\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_Concentration_Dynamics/Leaf_64/Leaf_Leaf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.377389531926168}} {"text": "function [results] = vdpgm(given_data, opts)\n%\n% function [results] = vdpgm(given_data, opts)\n%\n\nstart_time = clock;\nif nargin == 1\n opts = struct();\nend\nif issparse(given_data)\n given_data = full(given_data);\nend\nif ~ isfield(opts, 'algorithm')\n % algorithm can be one of 'vdp', 'bj', 'cdp', 'csb' and 'non_dp'\n % vdp : variational DP\n % bj : Blei and Jordan\n % cdp : collapsed Dirichlet prior\n % csb : collapsed stick-breaking\n % non_dp : variational Bayes for Gaussian mixtures\n opts.algorithm = 'vdp';\nend\nif ~ isfield(opts, 'collapsed_means')\n opts.collapsed_means = 0;\nend\nif ~ isfield(opts, 'do_sort')\n opts.do_sort = '0';\nend\nif ~ isfield(opts, 'get_q_of_z')\n opts.get_q_of_z = 0;\nend\nif ~ isfield(opts, 'weight')\n opts.weight = 1;\nend\nif ~ isfield(opts, 'get_log_likelihood')\n opts.get_log_likelihood = 0;\nend\nif ~ isfield(opts, 'use_kd_tree')\n opts.use_kd_tree = 1;\nend\nif ~ isfield(opts, 'threshold')\n opts.threshold = 1.0e-5;\nend\nif ~ isfield(opts, 'sis')\n opts.sis = 0;\nend\nif ~ isfield(opts, 'initial_depth')\n opts.initial_depth = 3;\nend\nif ~ isfield(opts, 'initial_K')\n opts.initial_K = 1;\nend\nif ~ isfield(opts, 'ite')\n opts.ite = inf;\nend\nif ~ isfield(opts, 'do_split')\n opts.do_split = 0;\nend\nif ~ isfield(opts, 'do_merge')\n opts.do_merge = 0;\nend\nif ~ isfield(opts, 'do_greedy')\n opts.do_greedy = 1;\nend\nif ~ isfield(opts, 'max_target_ratio')\n opts.max_target_ratio = 0.5;\nend\nif ~ isfield(opts, 'init_of_split')\n % 'pc', 'rnd', 'rnd_close' or 'close_f'\n opts.init_of_split = 'pc';\nend\nif ~ isfield(opts, 'recursive_expanding_depth')\n opts.recursive_expanding_depth = 2;\nend\nif ~ isfield(opts, 'recursive_expanding_threshold')\n opts.recursive_expanding_threshold = 1.0e-1;\nend\nif ~ isfield(opts, 'recursive_expanding_frequency')\n opts.recursive_expanding_frequency = 3;\nend\nif isfield(opts, 'seed')\n rand('state', opts.seed);\nelse\n seed = rand('state');\n results.seed = seed;\nend\n\ndata.given_data = given_data;\nif opts.use_kd_tree\n partitions = init_kdtree_partitions(given_data, opts.initial_depth);\n data.kdtree = partitions;\nend\n\n% the hyperparameters of priors\nhp_prior = mk_hp_prior(data, opts);\n\nif isfield(opts, 'hp_posterior')\n opts.use_kd_tree = 0;\n if opts.get_q_of_z\n results.q_of_z = mk_q_of_z(data, opts.hp_posterior, opts.hp_prior, opts);\n end\n if opts.get_log_likelihood\n results.log_likelihood = mk_log_likelihood(data, opts.hp_posterior, opts.hp_prior, opts);\n end\n if isfield(opts, 'test_data')\n results.predictive_posterior = log_predictive_dist(data, opts.q_of_z, opts.hp_posterior, ...\n opts.hp_prior, opts);\n end\n return\nend\n\nif opts.sis > 0\n q_of_z = sequential_importance_sampling(data, hp_prior, opts);\nelseif isfield(opts, 'q_of_z')\n q_of_z = opts.q_of_z;\nelse\n q_of_z = rand_q_of_z(data, opts.initial_K, opts);\nend\n\nhp_posterior = mk_hp_posterior(data, q_of_z, hp_prior, opts);\nif opts.do_greedy\n [free_energy, hp_posterior, data] = greedy(data, hp_posterior, hp_prior, opts);\nelse\n [free_energy, hp_posterior, data] = split_merge(data, hp_posterior, hp_prior, opts);\nend\n\nresults.algorithm = opts.algorithm;\nresults.elapsed_time = etime(clock, start_time);\nresults.free_energy = free_energy;\nresults.hp_prior = hp_prior;\nresults.hp_posterior = hp_posterior;\nresults.K = length(hp_posterior.eta);\nresults.opts = opts;\nif opts.get_q_of_z\n results.q_of_z = mk_q_of_z(data, hp_posterior, hp_prior, opts);\n if opts.use_kd_tree\n results.q_of_z = mk_non_kdtree_q_of_z(data, results.q_of_z);\n end\nend\nif opts.get_log_likelihood\n results.log_likelihood = mk_log_likelihood(data, hp_posterior, hp_prior, opts);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction log_likelihood = mk_log_likelihood(data, hp_posterior, hp_prior, opts);\n[D,N] = size(data.given_data);\nK = size(hp_posterior.m, 2);\nlog_likelihood = zeros(K,N);\nE_pi = mk_E_pi(hp_posterior, hp_prior, opts);\nfor c=1:K\n mu = hp_posterior.m(:,c);\n f = hp_posterior.eta(c) + 1 - D;\n Sigma = (hp_posterior.xi(c)+1) / hp_posterior.xi(c) / f * hp_posterior.B{c};\n log_likelihood(c,:) = log_no_w(E_pi(c)) + logmvtpdf(data.given_data, mu, f, Sigma);\nend\nlog_likelihood = log_sum_exp(log_likelihood, 1); % 1 by N\nlog_likelihood = sum(log_likelihood, 2);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction log_prob = log_predictive_dist(data, q_of_z, hp_posterior, hp_prior, opts);\nif opts.use_kd_tree\n N = length(data.kdtree);\n D = size(data.kdtree(1).sum_x, 1);\n Na = [data.kdtree(:).N];\n if isequal(opts.algorithm, 'vdp')\n true_Nc = Na*q_of_z; % 1*K\n q_of_z(:,end) = 0;\n end\n Nc = Na*q_of_z; % 1*K\n sum_x = [data.kdtree(:).sum_x] * q_of_z;\nelse\n [D,N] = size(data.given_data);\n if isequal(opts.algorithm, 'vdp')\n true_Nc = sum(q_of_z, 1); % 1*K\n q_of_z(:,end) = 0;\n end\n Nc = sum(q_of_z, 1); % 1*K\n sum_x = data.given_data * q_of_z;\nend\nE_pi = mk_E_pi(hp_posterior, hp_prior, opts);\nm = (sum_x + repmat(hp_prior.xi0*hp_prior.m0, 1, size(sum_x,2))) ./ repmat(Nc, D, 1);\nE_pi(find(Nc==0)) = 0;\nn = size(opts.test_data, 2);\nlog_prob = zeros(size(m,2), n);\nfor c=1:size(m,2)\n f = hp_posterior.eta(c) + 1 - D;\n sigma = hp_posterior.B{c} * (hp_posterior.xi(c)+1) / hp_posterior.xi(c) / f;\n if E_pi(c) > 0\n log_prob(c,:) = log(E_pi(c)) + log_T_dist(opts.test_data, m(:,c), ...\n sigma, f);\n else\n log_prob(c,:) = -inf;\n end\nend\nlog_prob = log_sum_exp(log_prob,1);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction log_prob = log_T_dist(X, m, sigma, f);\n% X is a D by n matrix\n[D,n] = size(X);\ndiff = X-repmat(m,1,n);\nlog_prob = gammaln((f+D)/2) ...\n - D/2*log(f*pi) ...\n - gammaln(f/2) ...\n - 0.5*detln(sigma) ...\n - (f+D)/2*log(1 + sum( diff .* ((f*sigma) \\ diff), 1));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction quad_term = mk_quad_term(data, q_of_z, hp_prior, opts)\n% calculate the quad_term in marginalizing out means\n% quad_term : D by D by K\n%\n[N, K] = size(q_of_z);\nD = size(data.given_data, 1);\nNc = sum(q_of_z, 1); % 1 by K\nxi = Nc + hp_prior.xi0;\nf0 = 1 ./ (xi.^2);\nf1 = - 2 ./ (xi.^3);\nf2 = 3 ./ (xi.^4);\nv = q_of_z.*(1 - q_of_z); % N by K\nc = v.*((1-q_of_z).^2 + q_of_z.^2);\nq = v.*((1-q_of_z).^3 + q_of_z.^3);\np_x = data.given_data * q_of_z; % D by K\nv_x = data.given_data * v; % D by K\nc_x = data.given_data * c; % D by K\nv_p_x = data.given_data * (q_of_z + v); % D by K\nc_p_x = data.given_data * (q_of_z + c); % D by K\nfor t=1:K\n first_term = f0(t) ...\n *((repmat(v(:,t)', D, 1).*data.given_data)*data.given_data' ...\n + p_x(:,t)*p_x(:,t)');\n second_term = f1(t) ...\n *((repmat(c(:,t)', D, 1).*data.given_data)*data.given_data' ...\n + v_p_x(:,t)*v_p_x(:,t)' - v_x(:,t)*v_x(:,t)' - p_x(:,t)*p_x(:,t)');\n tmp = q(:,t) - 3*v(:,t).^2 + v(:,t)*sum(v(:,t));\n third_term = f2(t) ...\n *((repmat(tmp', D, 1).*data.given_data)*data.given_data' ...\n + c_p_x(:,t)*c_p_x(:,t)' - c_x(:,t)*c_x(:,t)' - p_x(:,t)*p_x(:,t)' ...\n + 2*v_x(:,t)*v_x(:,t)' ...\n + sum(v(:,t))*p_x(:,t)*p_x(:,t)');\n quad_term(:,:,t) = first_term + second_term + third_term;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction E_log_p_of_z_given_other_z = mk_E_log_p_of_z_given_other_z(hp_posterior, hp_prior, opts);\n% returns E[log p(z_n|Z^-n)]_q(Z^-n)\n% E_log_p_of_z_given_other_z : N by K\nq_of_z = hp_posterior.q_of_z;\n[N,K] = size(q_of_z);\n[E_Nc_minus_n, V_Nc_minus_n] = mk_E_Nc_minus_n(q_of_z); % N by K\nuse_variance = 1;\nif isequal(opts.algorithm, 'cdp')\n if use_variance\n E_log_p_of_z_given_other_z = ...\n log(E_Nc_minus_n + hp_prior.alpha/K) ...\n - 0.5*V_Nc_minus_n./((E_Nc_minus_n+hp_prior.alpha/K).^2) ...\n - log(N - 1 + hp_prior.alpha);\n else\n E_log_p_of_z_given_other_z = ...\n log(E_Nc_minus_n + hp_prior.alpha/K) ...\n - log(N - 1 + hp_prior.alpha);\n end\nelseif isequal(opts.algorithm, 'csb')\n E_Nc_minus_n_cumsum_geq = fliplr(cumsum(fliplr(E_Nc_minus_n), 2));\n q_of_z_cumsum_geq = fliplr(cumsum(fliplr(q_of_z), 2));\n dummy = q_of_z_cumsum_geq.*(1-q_of_z_cumsum_geq);\n v_Nc_cumsum_geq = repmat(sum(dummy, 1), N, 1) - dummy;\n\n E_Nc_minus_n_cumsum = E_Nc_minus_n_cumsum_geq - E_Nc_minus_n;\n q_of_z_cumsum = q_of_z_cumsum_geq - q_of_z;\n dummy = q_of_z_cumsum.*(1-q_of_z_cumsum);\n v_Nc_cumsum = repmat(sum(dummy, 1), N, 1) - dummy;\n \n if use_variance\n first_term = ...\n (log(1+E_Nc_minus_n) ...\n - 0.5*V_Nc_minus_n./((1+E_Nc_minus_n).^2) ...\n - log(1+hp_prior.alpha+E_Nc_minus_n_cumsum_geq) ...\n + 0.5*v_Nc_cumsum_geq./((1+hp_prior.alpha+E_Nc_minus_n_cumsum_geq).^2));\n first_term(:,end) = 0;\n dummy = log(hp_prior.alpha+E_Nc_minus_n_cumsum) ...\n - 0.5*v_Nc_cumsum./((hp_prior.alpha+E_Nc_minus_n_cumsum).^2) ...\n - log(1+hp_prior.alpha+E_Nc_minus_n_cumsum_geq) ...\n + 0.5*v_Nc_cumsum_geq./((1+hp_prior.alpha+E_Nc_minus_n_cumsum_geq).^2);\n second_term = cumsum(dummy, 2) - dummy;\n else\n first_term = log(1+E_Nc_minus_n) - log(1+hp_prior.alpha+E_Nc_minus_n_cumsum_geq);\n first_term(:,end) = 0;\n dummy = log(hp_prior.alpha+E_Nc_minus_n_cumsum) ...\n - log(1+hp_prior.alpha+E_Nc_minus_n_cumsum_geq);\n second_term = cumsum(dummy, 2) - dummy;\n end\n E_log_p_of_z_given_other_z = first_term + second_term;\nelse\n error('unsupported algorithm');\nend\n% Gaussian approximation may not give a proper distribution.\n% note. E[log p] is not need to be proper\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [E_Nc_minus_n, V_Nc_minus_n] = mk_E_Nc_minus_n(q_of_z)\n% returns E[Nc^-n]; the expected value of Nc-n; N by K\n% V[Nc^-n]; the variance of Nc-n; N by K\n% q_of_z : N by K\nN = size(q_of_z, 1);\nE_Nc_minus_n = repmat(sum(q_of_z, 1), N, 1) - q_of_z;\ntmp = q_of_z.*(1-q_of_z);\nV_Nc = sum(tmp, 1);\nV_Nc_minus_n = repmat(V_Nc, N, 1) - tmp;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction E_pi = mk_E_pi(hp_posterior, hp_prior, opts);\nif isequal(opts.algorithm, 'cdp') | isequal(opts.algorithm, 'non_dp')\n E_pi = hp_posterior.tilde_alpha / sum(hp_posterior.tilde_alpha);\nelseif isequal(opts.algorithm, 'bj')\n second_term = [0 cumsum(log(hp_posterior.gamma(2,:)) - log(sum(hp_posterior.gamma)),2)]; % 1 by K\n E_pi = exp([(log(hp_posterior.gamma(1,:)) ...\n - log(sum(hp_posterior.gamma,1)) ...\n + second_term(1:end-1)) ...\n , second_term(end)]); % 1 by K\nelseif isequal(opts.algorithm, 'vdp')\n opts_tmp = opts;\n opts_tmp.algorithm = 'bj';\n E_pi = mk_E_pi(hp_posterior, hp_prior, opts_tmp);\n E_pi(end) = max(1 - sum(E_pi(1:end-1)), 0);\nelseif isequal(opts.algorithm, 'csb')\n [N,K] = size(hp_posterior.q_of_z);\n a = 1 + hp_posterior.Nc; % 1 by K\n b = hp_prior.alpha + N - cumsum(hp_posterior.Nc, 2); % 1 by K\n first_term = a ./ (a+b);\n first_term(end) = 1;\n second_term = cumprod(b./(a+b)) ./ (b./(a+b));\n E_pi = first_term .* second_term;\nelse\n error('not supported algorithm')\nend\n\n%\n% p_TSB(z_test|Z)\n%\n% \\begin{align*}\n% p_{\\text{TSB}}(Z) =& \n% \\alpha^{T-1}\n% \\prod_{ii})}\n% {\\Gamma(1+\\alpha+N_{\\geq i})}\n% \\\\\n% p_{\\text{TSB}}(z_{test}=t,Z) = &\n% \\left(\n% \\frac{1+N_t}{1+\\alpha+N_{\\geq t}}\n% \\right)^{\\mathbb{I}(tj}}\n% {1+\\alpha+N_{\\geq j}}\n% \\right\\}\n% \\alpha^{T-1}\n% \\prod_{ii})}\n% {\\Gamma(1+\\alpha+N_{\\geq i})}\n% \\\\\n% p_{\\text{TSB}}(z_{test}=t|Z) = &\n% \\left(\n% \\frac{1+N_t}{1+\\alpha+N_{\\geq t}}\n% \\right)^{\\mathbb{I}(tj}}\n% {1+\\alpha+N_{\\geq j}}\n% \\end{align*}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q_of_z = sequential_importance_sampling(data, hp_prior, opts);\ndisp('start SIS.')\nN = size(data.given_data, 2);\nfor r = 1:opts.sis\n I = randperm(N);\n% I = I(1:ceil(N*0.1));\n data_r.given_data = data.given_data(:,I);\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% data_r_sub.given_data = data_r.given_data(:,1);\n% q_of_z = ones(1,opts.initial_K) / opts.initial_K;\n% hp_posterior = mk_hp_posterior(data_r_sub, q_of_z, hp_prior, opts);\n% for n = 1:N\n% data_r_sub.given_data = data_r.given_data(:,1:n);\n% q_of_z = mk_q_of_z(data_r_sub, hp_posterior, hp_prior, opts);\n% q_of_z = sort_q_of_z(data, q_of_z, opts); \n% hp_posterior = mk_hp_posterior(data_r_sub, q_of_z, hp_prior, opts);\n% end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n q_of_z = [];\n for n = 1:size(data_r.given_data,2)\n data_r_sub.given_data = data_r.given_data(:,1:n);\n q_of_z(n,:) = ones(1, opts.initial_K) / opts.initial_K;\n hp_posterior = mk_hp_posterior(data_r_sub, q_of_z, hp_prior, opts);\n q_of_z = mk_q_of_z(data_r_sub, hp_posterior, hp_prior, opts);\n% q_of_z = sort_q_of_z(data, q_of_z, opts); \n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n hist(r).hp_posterior = hp_posterior;\n hist(r).free_energy = mk_free_energy(data, hp_posterior, hp_prior, opts);\n [min_f, best_r] = min([hist(:).free_energy]);\n hp_posterior = hist(best_r).hp_posterior;\n disp(['SIS: ' num2str(r) '; best f = ' num2str(min_f) '; best Nc = ' num2str(hp_posterior.Nc)])\nend\ndisp('SIS done.')\nq_of_z = mk_q_of_z(data, hp_posterior, hp_prior, opts);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction nonkdtree_q_of_z = mk_non_kdtree_q_of_z(data, q_of_z);\nnonkdtree_q_of_z = zeros(size(data.given_data,2), size(q_of_z, 2)); % N*K\nfor a=1:length(data.kdtree);\n nonkdtree_q_of_z(data.kdtree(a).indices,:) = repmat(q_of_z(a,:), length(data.kdtree(a).indices), 1);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [free_energy, hp_posterior, data] = greedy(data, hp_posterior, hp_prior, opts);\nfree_energy = mk_free_energy(data, hp_posterior, hp_prior, opts);\ndisp_status(free_energy, hp_posterior, opts);\nwhile 1\n disp('finding the best one....')\n [new_free_energy, new_hp_posterior, new_data, c] = find_best_splitting(data, ...\n hp_posterior, ...\n hp_prior, opts);\n if c == -1\n break\n end\n disp(['finding the best one.... done. component ' num2str(c) ' was split.'])\n disp_status(new_free_energy, new_hp_posterior, opts);\n [new_free_energy, new_hp_posterior, new_data] = update_posterior2(new_data, ...\n new_hp_posterior, ...\n hp_prior, opts, 1, opts.ite);\n if free_energy_improved(free_energy, new_free_energy, 0, opts) == 0\n break\n end\n free_energy = new_free_energy;\n hp_posterior = new_hp_posterior;\n data = new_data;\nend\ndisp_status(free_energy, hp_posterior, opts);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [free_energy, hp_posterior, data, c] = find_best_splitting(data, ...\n hp_posterior, ...\n hp_prior, opts);\nc_max = 10;\nK = size(hp_posterior.m, 2);\ncandidates = find(hp_posterior.Nc>2);\nif isempty(candidates)\n free_energy = 0;\n c = -1;\n return\nend\nq_of_z = mk_q_of_z(data, hp_posterior, hp_prior, opts);\nnew_free_energy = ones(1,max(candidates))*inf;\n%%%%%%%%%%%%%%%%%%%%%\nfc = mk_E_log_q_p_eta(data, hp_posterior, hp_prior, opts);\nlog_lambda = mk_log_lambda(data, hp_posterior, hp_prior, opts);\n%%%%%%%%%%%%%%%%%%%%%\nfor c = candidates(1:min(c_max, length(candidates)))\n disp(['splitting ' num2str(c) '...'])\n [new_data(c), new_q_of_z, info] = split(c, data, q_of_z, hp_posterior, hp_prior, opts, 1);\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n new_c = info.new_c;\n relating_n = find(sum(new_q_of_z(:,[c new_c]),2) > 0.5);\n if isempty(relating_n)\n continue\n end\n new_K = size(new_q_of_z, 2);\n sub_q_of_z = new_q_of_z(relating_n, [c new_c new_K]);\n if opts.use_kd_tree\n sub_data.kdtree = new_data(c).kdtree(relating_n);\n else\n sub_data.given_data = new_data(c).given_data(:,relating_n);\n end\n sub_hp_posteior = mk_hp_posterior(sub_data, sub_q_of_z, hp_prior, opts);\n [sub_f, sub_hp_posteior, dummy, sub_q_of_z] = update_posterior2(sub_data, ...\n sub_hp_posteior, ...\n hp_prior, opts, 0, 10, 0);\n if size(sub_q_of_z,2) < 3\n continue\n end\n if length(find(sum(sub_q_of_z,1)<1.0e-10)) > 1\n continue\n end\n new_log_lambda = log_lambda;\n if opts.use_kd_tree\n updated_data.kdtree = new_data(c).kdtree(info.updated_I);\n new_log_lambda(info.updated_I,:) = mk_log_lambda(updated_data, hp_posterior, hp_prior, opts);\n end\n sub_log_lambda = mk_log_lambda(new_data(c), sub_hp_posteior, hp_prior, opts);\n insert_indices = [c new_c new_K:(new_K+size(sub_q_of_z,2)-3)];\n new_log_lambda(:,insert_indices) = sub_log_lambda;\n new_fc = fc;\n new_fc(insert_indices) = mk_E_log_q_p_eta(sub_data, sub_hp_posteior, hp_prior, opts);\n new_free_energy(c) = mk_free_energy(new_data(c), sub_hp_posteior, hp_prior, opts, new_fc, new_log_lambda);\n new_q_of_z(relating_n,:) = 0;\n new_q_of_z(relating_n,insert_indices) = sub_q_of_z;\n new_q_of_z_cell{c} = new_q_of_z;\nend\n[free_energy, c] = min(new_free_energy);\nif isinf(free_energy)\n c = -1;\n return\nend\ndata = new_data(c);\nhp_posterior = mk_hp_posterior(data, new_q_of_z_cell{c}, hp_prior, opts);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [free_energy, hp_posterior, data] = split_merge(data, hp_posterior, hp_prior, opts);\n%\n% split: \n% tdp: if an empty cluster exists, split is available.\n% otherwise, make a new empty cluster. => K<-K+1.\n%\n% non-dp: if \n%\nc_max = 3;\n[free_energy, hp_posterior] = update_posterior2(data, hp_posterior, hp_prior, opts, 0, opts.ite);\nwhile 1\n K = size(hp_posterior.m, 2);\n new_free_energy = inf;\n %%% split\n if ~ opts.do_split\n break\n end\n disp(['### start splitting'])\n [dummy, candidates_for_splliting] = sort(hp_posterior.Nc, 2, 'descend');\n candidates_for_splliting(find(hp_posterior.Nc(candidates_for_splliting)<1)) = [];\n q_of_z = mk_q_of_z(data, hp_posterior, hp_prior, opts); % N*K\n for c=candidates_for_splliting(1:min(c_max, length(candidates_for_splliting)))\n disp(['### start splitting k=' num2str(c) '...'])\n [new_data, new_q_of_z] = split(c, data, q_of_z, hp_posterior, hp_prior, opts);\n new_hp_posterior = mk_hp_posterior(new_data, new_q_of_z, hp_prior, opts);\n [new_free_energy, new_hp_posterior, new_data] = update_posterior2(new_data, ...\n new_hp_posterior, ...\n hp_prior, ...\n opts, 1);\n if free_energy_improved(free_energy, new_free_energy, 0, opts)\n disp(['### splitting k=' num2str(c) ' improved the free energy. ' ...\n num2str(free_energy) ' -> ' num2str(new_free_energy)])\n break\n else\n disp(['### splitting k=' num2str(c) ' did not improve the free energy.'])\n end\n end\n disp('### end splitting')\n if free_energy_improved(free_energy, new_free_energy, 0, opts)\n free_energy = new_free_energy;\n hp_posterior = new_hp_posterior;\n data = new_data;\n continue\n end\n if ~ opts.do_merge\n break\n end\n %%% merge\n disp(['### start merging'])\n q_of_z = mk_q_of_z(data, hp_posterior, hp_prior, opts); % N*K\n candidates_for_merging = mkcandidates_to_merge(q_of_z'); % 2*#pairs\n for i=1:min(c_max, size(candidates_for_merging,2))\n pair = candidates_for_merging(:,i);\n c1 = pair(1); c2 = pair(2);\n disp(sprintf('### start merging c1=%d, c2=%d ...', c1, c2))\n new_q_of_z = q_of_z;\n new_q_of_z(:,c1) = new_q_of_z(:,c1) + new_q_of_z(:,c2);\n new_q_of_z(:,c2) = zeros(size(new_q_of_z,1),1);\n new_hp_posterior = mk_hp_posterior(data, new_q_of_z, hp_prior, opts);\n [new_free_energy, new_hp_posterior] = update_posterior2(data, ...\n new_hp_posterior, ...\n hp_prior, opts);\n if free_energy_improved(free_energy, new_free_energy, 0, opts)\n disp(sprintf('### merging c1=%d, c2=%d improved the free energy. %0.5g -> %0.5g', ...\n c1, c2, free_energy, new_free_energy))\n break\n else\n disp(sprintf('### merging c1=%d, c2=%d did not improve the free energy.', c1, c2))\n end\n end\n disp(['### end merging'])\n if free_energy_improved(free_energy, new_free_energy, 0, opts)\n free_energy = new_free_energy;\n hp_posterior = new_hp_posterior;\n continue\n end\n break\nend % while 1\ndisp_status(free_energy, hp_posterior, opts);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction log_p_of_x_given_c = mk_map_log_p_of_x_given_c(data, clusters, hp_posterior, opts);\n% clusters: e.g [1:K]\n[D,N] = size(data);\nK = length(clusters);\nlog_p_of_x_given_c = zeros(K,N);\nfor i = 1:K\n c = clusters(i);\n m = hp_posterior.m(:,c);\n precision = hp_posterior.inv_B(:,:,c)*hp_posterior.eta(c);\n d = data - repmat(m, 1, N);\n log_p_of_x_given_c(i,:) = (-D*0.5)*log(2*pi)+0.5*detln(precision)-0.5*sum(d.*(precision*d),1);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [new_data, new_q_of_z, info] = split(c, data, q_of_z, ...\n hp_posterior, hp_prior, opts, update_kdtree)\n% q_of_z: N*K\nif nargin < 7\n update_kdtree = 1;\nend\nnew_data = data;\nif opts.use_kd_tree & update_kdtree\n [dummy, indices] = max(q_of_z,[],2);\n target_partitions = find(indices==c)';\n if ~ isempty(target_partitions)\n m = [data.kdtree(target_partitions).mean];\n log_p_of_m_given_c = mk_map_log_p_of_x_given_c(m, c, hp_posterior, opts); % 1*|target_partitions|\n [dummy, I] = sort(log_p_of_m_given_c, 2, 'descend');\n target_partitions = target_partitions(I(1:ceil(length(I)*opts.max_target_ratio)));\n % target_partitions = find(q_of_z(:,c)>0.01)';\n [new_data, q_of_z, updated_I] = expand_all_nodes(new_data, q_of_z, hp_posterior, ...\n hp_prior, target_partitions, opts);\n info.updated_I = updated_I;\n else\n info.updated_I = [];\n end\nend\nif isequal(opts.init_of_split, 'pc') % principal eigenvector\n if opts.use_kd_tree\n arg1_data = [new_data.kdtree(:).mean];\n else\n arg1_data = new_data.given_data;\n end\n dir = divide_by_principal_component(arg1_data, ...\n hp_posterior.B{c}/hp_posterior.eta(c), ...\n hp_posterior.m(:,c));\n q_of_z_c1 = zeros(size(q_of_z,1),1);\n q_of_z_c2 = q_of_z(:,c);\n I = find(dir>=0);\n q_of_z_c1(I) = q_of_z(I,c);\n q_of_z_c2(I) = 0;\nelse\n q_of_z_c = q_of_z(:,c);\n if isequal(opts.init_of_split, 'rnd') % random\n r = rand(size(q_of_z,1),1);\n elseif isequal(opts.init_of_split, 'rnd_close') % make close clusters\n r = 0.5 + (rand(size(q_of_z,1),1)-0.5)*0.01;\n elseif isequal(opts.init_of_split, 'close_f') % one is almost zero.\n r = 0.98 + rand(size(q_of_z,1),1)*0.01;\n else\n init_of_split = opts.init_of_split\n error('unknown option')\n end\n q_of_z_c1 = q_of_z_c.*r;\n q_of_z_c2 = q_of_z_c.*(1-r);\nend\nnew_q_of_z = zeros(size(q_of_z,1), size(q_of_z,2)+1);\nnew_q_of_z(:,[1:end-2 end]) = q_of_z;\nnew_q_of_z(:,c) = q_of_z_c1;\nnew_c = size(new_q_of_z, 2) - 1;\nnew_q_of_z(:,new_c) = q_of_z_c2;\ninfo.new_c = new_c;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [new_data, new_q_of_z, updated_I] = expand_all_nodes(data, ...\n q_of_z, hp_posterior, ...\n hp_prior, ...\n target_partitions, opts);\nif size(target_partitions, 1) ~= 1\n error('target_partitions must be a row vector.')\nend\nnew_data = data;\nfor a=target_partitions\n if isempty(data.kdtree(a).children)\n children = mk_children_of_partition(data.kdtree(a));\n data.kdtree(a).children = children;\n else\n children = data.kdtree(a).children;\n end\n if length(children) == 1\n continue\n end\n new_data.kdtree(a) = children(1);\n new_data.kdtree(end+1) = children(2);\nend % while a <= length(data.kdtree)\nupdated_I = [target_partitions length(data.kdtree)+1:length(new_data.kdtree)];\nsub_data.given_data = data.given_data;\nsub_data.kdtree = new_data.kdtree(updated_I);\nsub_q_of_z = mk_q_of_z(sub_data, hp_posterior, hp_prior, opts);\nnew_q_of_z = zeros(length(new_data.kdtree),size(q_of_z,2));\nnew_q_of_z(1:size(q_of_z,1),:) = q_of_z;\nnew_q_of_z(updated_I,:) = sub_q_of_z;\ndisp(['### building kd-tree done; #partition ' num2str(length(data.kdtree)) ...\n ' -> ' num2str(length(new_data.kdtree))])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [data, q_of_z] = expand_recursively_until_convergence(data, ...\n q_of_z, hp_posterior, ...\n hp_prior, opts);\nkdtree_size = length(data.kdtree);\nfor a=1:length(data.kdtree)\n [data, q_of_z] = expand_recursively_until_convergence2(data, a, ...\n q_of_z, hp_posterior, ...\n hp_prior, opts, ...\n opts.recursive_expanding_depth);\nend\n[prob, best_c] = max(q_of_z, [], 2);\n% for c=1:size(q_of_z,2);\n% I_n = \n% end\ndisp(['### building kd-tree done; #partition ' num2str(kdtree_size) ...\n ' -> ' num2str(length(data.kdtree))])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [data, q_of_z] = expand_recursively_until_convergence2(data, a, ...\n q_of_z, hp_posterior, ...\n hp_prior, opts, depth);\n% q_of_z : N*K\nif depth == 0\n return\nend\nif isempty(data.kdtree(a).children)\n children = mk_children_of_partition(data.kdtree(a));\n data.kdtree(a).children = children;\nelse\n children = data.kdtree(a).children;\nend\nif length(children) == 1\n return\nend\nsub_data.given_data = data.given_data;\nsub_data.kdtree = children;\nsub_q_of_z = mk_q_of_z(sub_data, hp_posterior, hp_prior, opts); % 2*K\ndiff = sub_q_of_z - repmat(q_of_z(a,:), 2, 1);\nif sum(sum(diff.*diff, 1), 2)/prod(size(sub_q_of_z)) < opts.recursive_expanding_threshold\n return\nend\nb = length(data.kdtree)+1;\ndata.kdtree(a) = children(1);\ndata.kdtree(b) = children(2);\nq_of_z([a b],:) = sub_q_of_z;\n[data, q_of_z] = expand_recursively_until_convergence2(data, a, ...\n q_of_z, hp_posterior, ...\n hp_prior, opts, depth-1);\n[data, q_of_z] = expand_recursively_until_convergence2(data, b, ...\n q_of_z, hp_posterior, ...\n hp_prior, opts, depth-1);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [free_energy, hp_posterior, data, q_of_z] = update_posterior2(data, hp_posterior, hp_prior, opts, upkdtree, ite, do_sort);\n% update q_of_z: N*K\ndisp(['### updating posterior ...'])\nfree_energy = inf;\nif nargin == 4\n upkdtree = 0;\nend\nif nargin < 6\n ite = inf;\nend\nif nargin < 7\n do_sort = 1;\nend\ni = 0;\nlast_Nc = 0;\nstart_sort = 0;\nwhile 1\n i = i+1;\n [new_free_energy, log_lambda] = mk_free_energy(data, hp_posterior, hp_prior, opts);\n disp_status(new_free_energy, hp_posterior, opts);\n if (~isinf(ite) && i>=ite) || ...\n (isinf(ite) && free_energy_improved(free_energy, new_free_energy, 0, opts) == 0)\n free_energy = new_free_energy;\n if do_sort && opts.do_sort && ~ start_sort\n start_sort = 1;\n else\n break\n end\n end\n last_Nc = hp_posterior.Nc;\n free_energy = new_free_energy;\n [q_of_z, data] = mk_q_of_z(data, hp_posterior, hp_prior, opts, log_lambda);\n freq = opts.recursive_expanding_frequency;\n if opts.use_kd_tree & upkdtree & (freq==1 | mod(i,freq)==1)\n [data, q_of_z] = expand_recursively_until_convergence(data, ...\n q_of_z, ...\n hp_posterior, ...\n hp_prior, opts);\n end\n % check if the last component is small enough\n if isequal(opts.algorithm, 'vdp') & sum(q_of_z(:,end)) > 1.0e-20\n q_of_z(:,end+1) = 0;\n end\n if start_sort\n q_of_z = sort_q_of_z(data, q_of_z, opts);\n end\n if isequal(opts.algorithm, 'vdp') & sum(q_of_z(:,end-1)) < 1.0e-10\n q_of_z(:,end-1) = [];\n end\n hp_posterior = mk_hp_posterior(data, q_of_z, hp_prior, opts);\nend\n% disp_status(free_energy, hp_posterior, opts);\ndisp(['### updating posterior ... done.'])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [q_of_z, I] = sort_q_of_z(data, q_of_z, opts);\ndisp('sorting...')\nif opts.use_kd_tree\n Nc = [data.kdtree(:).N]*q_of_z; % 1*K\nelse\n Nc = sum(q_of_z, 1); % 1*K\nend\nif isequal(opts.algorithm, 'vdp')\n [dummy,I] = sort(Nc(1:end-1), 2, 'descend');\n I(end+1) = length(Nc);\nelse\n [dummy,I] = sort(Nc, 2, 'descend');\nend\nq_of_z = q_of_z(:,I);\ndisp('sorting... done.')\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction disp_status(free_energy, hp_posterior, opts);\nif isequal(opts.algorithm, 'vdp')\n Nc = hp_posterior.true_Nc;\nelse\n Nc = hp_posterior.Nc;\nend\ndisp(['F=' num2str(free_energy) ...\n '; Nc=[' num2str(Nc, ' %0.5g ') ...\n '];'])\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction bool = free_energy_improved(free_energy, new_free_energy, warn_when_increasing, opts);\ndiff = new_free_energy - free_energy;\nif abs(diff/free_energy) < opts.threshold\n bool = 0;\nelseif diff > 0\n if warn_when_increasing\n if abs(diff/free_energy) > 1.0e-3\n error(['the free energy increased. the diff is ' num2str(new_free_energy-free_energy)])\n else\n warning(['the free energy increased. the diff is ' num2str(new_free_energy-free_energy)])\n end\n end\n bool = 0;\nelseif diff == 0\n bool = 0\nelse\n bool = 1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction partitions = init_kdtree_partitions(given_data, depth);\n[D,N] = size(given_data);\nroot = mk_kdtree_partition(given_data, [1:N]);\npartitions = expand_recursively(root, depth);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction partitions = expand_recursively(partition, depth);\nchildren = mk_children_of_partition(partition);\nif depth == 1 | length(children) == 1\n partitions = children;\nelse\n partitions1 = expand_recursively(children(1), depth-1);\n partitions2 = expand_recursively(children(2), depth-1);\n partitions = [partitions1 partitions2];\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction children = mk_children_of_partition(partition);\nif partition.N == 1\n children = partition;\n return\nend\ndir = divide_by_principal_component(partition.given_data(:,partition.indices), ...\n partition.sigma, ...\n partition.mean);\npositive_I = find(dir>=0);\nnegative_I = find(dir<0);\nif length(positive_I) == 0 | length(negative_I) == 0\n children = partition;\n return\nend\nchildren(1) = mk_kdtree_partition(partition.given_data, partition.indices(positive_I));\nchildren(2) = mk_kdtree_partition(partition.given_data, partition.indices(negative_I));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction direction = divide_by_principal_component(data, covariance, mean);\nN = size(data, 2);\nif size(data,1) <= 16\n [V,D] = eig(covariance);\n [eig_val, principal_component_i] = max(diag(D));\n principal_component = V(:,principal_component_i);\nelse\n [principal_component,eig_val] = power_method(covariance);\nend\ndirection = sum((data - repmat(mean, 1, N)).*repmat(principal_component, 1, N), 1);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction partition = mk_kdtree_partition(given_data, indices);\npartition.N = length(indices);\nif partition.N == 0\n error('indices must have at least one index.')\nend\ndata_a = given_data(:,indices);\npartition.given_data = given_data;\npartition.indices = indices;\npartition.sum_x = sum(data_a, 2); % D*1\nmean = partition.sum_x / partition.N; % D*1\npartition.mean = mean;\npartition.sum_xx = data_a*data_a'; % D*D\npartition.sigma = partition.sum_xx / partition.N - mean*mean';\npartition.children = [];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q_of_z = rand_q_of_z(data, K, opts);\n% q_of_z: N*K\nif opts.use_kd_tree\n N = length(data.kdtree);\nelse\n N = size(data.given_data, 2);\nend\nif isequal(opts.algorithm, 'vdp')\n q_of_z = zeros(N, K+1);\nelse\n q_of_z = zeros(N, K);\nend\nq_of_z(:,1:K) = rand(N, K);\nq_of_z = normalize(q_of_z, 2);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction hp_posterior = mk_hp_posterior(data, q_of_z, hp_prior, opts);\n% the last component of q_of_z represents the infinite rest of components\n% the last component is the prior.\n% q_of_z: N*K\n% q_of_z(:,end) is the rest of responsibilities.\nthreshold_for_N = 1.0e-200;\nK = size(q_of_z, 2);\nif opts.use_kd_tree\n N = length(data.kdtree);\n D = size(data.kdtree(1).sum_x, 1);\n Na = [data.kdtree(:).N];\n if isequal(opts.algorithm, 'vdp')\n true_Nc = Na*q_of_z; % 1*K\n q_of_z(:,end) = 0;\n end\n Nc = Na*q_of_z; % 1*K\n sum_x = [data.kdtree(:).sum_x] * q_of_z;\nelse\n [D,N] = size(data.given_data);\n if isequal(opts.algorithm, 'vdp')\n true_Nc = sum(q_of_z, 1); % 1*K\n q_of_z(:,end) = 0;\n end\n Nc = sum(q_of_z, 1); % 1*K\n sum_x = data.given_data * q_of_z;\nend\nI = find(Nc>threshold_for_N);\ninv_Nc = zeros(1,K);\ninv_Nc(I) = 1./Nc(I);\nhp_posterior.eta = hp_prior.eta0 + Nc;\nhp_posterior.xi = hp_prior.xi0 + Nc;\nmeans = sum_x .* repmat(inv_Nc, D, 1); % D*K\nhp_posterior.inv_B = zeros(D,D,K);\nif opts.use_kd_tree\n t1 = reshape([data.kdtree(:).sum_xx],D,D,N);\n for c=1:K\n v0 = means(:,c) - hp_prior.m0;\n q_of_z_c = reshape(q_of_z(:,c), 1, 1, N);\n S = sum(repmat(q_of_z_c,[D,D,1]).*t1, 3) - Nc(c)*means(:,c)*means(:,c)';\n hp_posterior.B{c} = hp_prior.B0 ...\n + S ...\n + Nc(c)*hp_prior.xi0*v0*v0'/(hp_posterior.xi(c)); % D*D\n end\nelse\n if opts.collapsed_means\n quad_term = mk_quad_term(data, q_of_z, hp_prior, opts);\n end\n for c=1:K\n if opts.collapsed_means\n hp_posterior.B{c} = hp_prior.B0 ...\n + (repmat(q_of_z(:,c),1,D)'.*data.given_data)*data.given_data' ...\n + quad_term(:,:,c);\n else\n v = data.given_data - repmat(means(:,c),1,N); % D*N\n v0 = means(:,c) - hp_prior.m0;\n hp_posterior.B{c} = hp_prior.B0 ...\n + (repmat(q_of_z(:,c),1,D)'.*v)*v' ...\n + Nc(c)*hp_prior.xi0*v0*v0'/(hp_posterior.xi(c)); % D*D\n end\n end\nend\nfor c=1:K\n hp_posterior.inv_B(:,:,c) = inv(hp_posterior.B{c});\nend\nhp_posterior.m = (sum_x + repmat(hp_prior.xi0*hp_prior.m0,1,K)) ...\n ./ repmat(Nc+hp_prior.xi0,D,1);\nif isequal(opts.algorithm, 'vdp')\n % gamma: 2*K\n hp_posterior.gamma = zeros(2,K);\n hp_posterior.gamma(1,:) = 1 + true_Nc;\n hp_posterior.gamma(2,:) = hp_prior.alpha + sum(true_Nc) - cumsum(true_Nc,2);\nelseif isequal(opts.algorithm, 'bj')\n hp_posterior.gamma = zeros(2,K-1);\n hp_posterior.gamma(1,:) = 1 + Nc(1:K-1);\n hp_posterior.gamma(2,:) = hp_prior.alpha + sum(Nc) - cumsum(Nc(1:K-1),2);\nelseif isequal(opts.algorithm, 'non_dp') | isequal(opts.algorithm, 'cdp')\n hp_posterior.tilde_alpha = hp_prior.alpha/K + Nc;\nelseif isequal(opts.algorithm, 'csb')\n 1;\nelse\n error('unknown algorithm')\nend\n\nhp_posterior.Nc = Nc; \nif isequal(opts.algorithm, 'vdp')\n hp_posterior.true_Nc = true_Nc;\nend\nhp_posterior.q_of_z = q_of_z; % q_of_z is a N by K matrix where N is\n % #given_data or #nodes in a kd-tree.\n\n\n\f\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction fc = mk_E_log_q_p_eta(data, hp_posterior, hp_prior, opts);\n% returns E[ log q(eta)/p(eta) ]_q\n% fc : 1 by K\nD = size(hp_posterior.m, 1);\nK = size(hp_posterior.eta, 2);\nlog_det_B = zeros(1,K);\nfor c=1:K\n log_det_B(c) = detln(hp_posterior.B{c});\n d = hp_posterior.m(:,c)-hp_prior.m0; % D*1\n term_eta(1,c) = sum(sum(hp_posterior.inv_B(:,:,c).*(hp_prior.xi0*d*d'),1),2);\n term_eta(2,c) = sum(sum(hp_posterior.inv_B(:,:,c).*hp_prior.B0,1),2) - D;\nend\nE_log_q_p_mean = ...\n + 0.5*D*(hp_prior.xi0./hp_posterior.xi ...\n - log(hp_prior.xi0./hp_posterior.xi) ...\n - 1) ...\n + 0.5*(hp_posterior.eta).* term_eta(1,:); \n\npsi_sum = sum(psi( (repmat(hp_posterior.eta+1,D,1) - repmat([1:D]',1,K))*0.5 ), 1); % 1*K\nE_log_q_p_cov = ...\n 0.5*hp_prior.eta0*(log_det_B-detln(hp_prior.B0)) ...\n + 0.5*hp_posterior.Nc.*psi_sum ...\n + 0.5*(hp_posterior.eta).* term_eta(2,:) ...\n + gamma_multivariate_ln(hp_prior.eta0*0.5,D) ...\n - gamma_multivariate_ln(hp_posterior.eta*0.5,D);\n\n%debug\nif length(find(E_log_q_p_mean<-1.0e-8,1)) > 0\n E_log_q_p_mean\n error('E_log_q_p_mean is negative.')\nend\nif length(find(E_log_q_p_cov<-1.0e-8,1)) > 0\n E_log_q_p_cov\n error('E_log_q_p_mean is negative.')\nend\n\nfc = E_log_q_p_mean + E_log_q_p_cov;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [free_energy, log_lambda] = mk_free_energy(data, hp_posterior, ...\n hp_prior, opts, ...\n fc, log_lambda);\nif nargin == 4\n fc = mk_E_log_q_p_eta(data, hp_posterior, hp_prior, opts); % 1*K\n log_lambda = mk_log_lambda(data, hp_posterior, hp_prior, opts); % N*K\nend\n[N,K] = size(log_lambda);\nif isequal(opts.algorithm, 'vdp') || isequal(opts.algorithm, 'bj')\n % note when bj, if full hp_posterior is given, len_gamma = K - 1.\n len_gamma = size(hp_posterior.gamma, 2);\n if isequal(opts.algorithm, 'bj') && len_gamma ~= K - 1\n error('invalid length')\n end\n E_log_p_of_V = ...\n gammaln(sum(hp_posterior.gamma, 1)) ...\n - gammaln(1+hp_prior.alpha) ...\n - sum(gammaln(hp_posterior.gamma), 1) ...\n + gammaln(hp_prior.alpha) ...\n + ((hp_posterior.gamma(1,:)-1) ...\n .*(psi(hp_posterior.gamma(1,:))-psi(sum(hp_posterior.gamma,1)))) ...\n + ((hp_posterior.gamma(2,:)-hp_prior.alpha) ...\n .*(psi(hp_posterior.gamma(2,:))-psi(sum(hp_posterior.gamma,1))));\n extra_term = sum(E_log_p_of_V);\nelseif isequal(opts.algorithm, 'non_dp')\n E_log_p_of_pi = ...\n sum(gammaln(hp_prior.alpha/K) ...\n - gammaln(hp_posterior.tilde_alpha) ...\n + hp_posterior.Nc.*(psi(hp_posterior.tilde_alpha) ...\n - psi(sum(hp_posterior.tilde_alpha)))) ...\n + gammaln(sum(hp_prior.alpha+size(data,2))) - gammaln(hp_prior.alpha);\n extra_term = E_log_p_of_pi;\nelseif isequal(opts.algorithm, 'cdp') || isequal(opts.algorithm, 'csb')\n E_log_p_of_z_given_other_z = ...\n mk_E_log_p_of_z_given_other_z(hp_posterior, hp_prior, opts); % N by K\n q_of_z = mk_q_of_z(data,hp_posterior,hp_prior,opts,log_lambda);\n% q_of_z = hp_posterior.q_of_z;\n E_Nc = hp_posterior.Nc;\n V_Nc = sum(q_of_z.*(1-q_of_z), 1); % 1 by K\n if isequal(opts.algorithm, 'cdp')\n E_log_p_of_z = gammaln(hp_prior.alpha) - gammaln(N+hp_prior.alpha) ...\n + sum(gammaln(hp_prior.alpha/K + E_Nc) ...\n - 0.5*psi(1, hp_prior.alpha/K + E_Nc).*V_Nc - gammaln(hp_prior.alpha/K));\n else % csb\n E_Nc_geq_to_i = cumsum(E_Nc, 2);\n q_of_z_geq_to_i = cumsum(q_of_z, 2);\n V_Nc_geq_to_i = sum(q_of_z_geq_to_i.*(1-q_of_z_geq_to_i), 1);\n\n E_Nc_greater_than_i = cumsum(E_Nc, 2) - E_Nc;\n q_of_z_greater_than_i = q_of_z_geq_to_i - q_of_z;\n V_Nc_greater_than_i = sum(q_of_z_greater_than_i.*(1-q_of_z_greater_than_i), 1);\n \n tmp = gammaln(1 + E_Nc) - 0.5*psi(1, 1 + E_Nc).*V_Nc ... % E[log p(1+Nc)]\n + (gammaln(1 + E_Nc_greater_than_i) ... % E[log p(1+N_{>c})]\n - 0.5*psi(1, 1 + E_Nc_greater_than_i).*V_Nc_greater_than_i) ...\n - (gammaln(1 + hp_prior.alpha + E_Nc_geq_to_i) ... % E[log p(1+alpha+N_{>=c})]\n - 0.5*psi(1, 1 + hp_prior.alpha + E_Nc_geq_to_i).*V_Nc_geq_to_i);\n E_log_p_of_z = sum(tmp(1:end-1));\n end\n extra_term = sum(sum(E_log_p_of_z_given_other_z.*q_of_z, 2), 1) - E_log_p_of_z;\nelse\n error('unknown algorithm')\nend\nif opts.use_kd_tree\n free_energy = extra_term + sum(fc) - [data.kdtree(:).N]*log_sum_exp(log_lambda, 2);\nelse\n free_energy = extra_term + sum(fc) - sum(log_sum_exp(log_lambda, 2), 1);\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction log_lambda = mk_log_lambda(data, hp_posterior, hp_prior, opts);\n% log_lambda: N*K\n% q(z_n=c|x_n) = lambda_n_c / sum_c lambda_n_c\n\nif isequal(opts.algorithm, 'vdp')\n if abs(hp_posterior.gamma(2,end) - hp_prior.alpha) > 1.0e-5\n hp_posterior.gamma(2,end)\n hp_prior.alpha\n diff = hp_prior.alpha - hp_posterior.gamma(2,end)\n error('must be alpha')\n end\nend\n\nif opts.use_kd_tree\n N = length(data.kdtree);\n D = size(data.kdtree(1).sum_x, 1);\nelse\n [D,N] = size(data.given_data);\nend\nK = size(hp_posterior.eta, 2);\n\npsi_sum = sum(psi( (repmat(hp_posterior.eta+1,D,1) - repmat([1:D]',1,K))*0.5 ), 1); % 1*K\nlog_lambda = zeros(N,K);\nif opts.use_kd_tree\n t1 = reshape([data.kdtree(:).sum_xx],D,D,N);\n sum_x = repmat(reshape([data.kdtree(:).sum_x],D,1,N),[1,D,1]);\n Na = repmat(reshape([data.kdtree(:).N],1,1,N),[D,D,1]);\nend\nif isequal(opts.algorithm, 'csb') | isequal(opts.algorithm, 'cdp')\n E_log_p_of_z_given_other_z = mk_E_log_p_of_z_given_other_z(hp_posterior, hp_prior, opts);\nend\nfor c=1:K\n% Precision = 0.5*hp_posterior.inv_B(:,:,c)*hp_posterior.eta(c);\n% if isequal(opts.algorithm, 'vdp')\n% constant = psi(hp_posterior.gamma(1,c)) - psi(sum(hp_posterior.gamma(:,c),1)) ...\n% + sum(psi(hp_posterior.gamma(2,[1:c-1])) - psi(sum(hp_posterior.gamma(:,[1:c-1]),1)), 2);\n% elseif isequal(opts.algorithm, 'bj')\n% if c < K\n% constant = psi(hp_posterior.gamma(1,c)) - psi(sum(hp_posterior.gamma(:,c),1)) ...\n% + sum(psi(hp_posterior.gamma(2,[1:c-1])) - psi(sum(hp_posterior.gamma(:,[1:c-1]),1)), 2);\n% else\n% constant = sum(psi(hp_posterior.gamma(2,[1:c-1])) - psi(sum(hp_posterior.gamma(:,[1:c-1]),1)), 2);\n% end\n% elseif isequal(opts.algorithm, 'non_dp')\n% % E[log pi] ; pi is the weight of mixtures.\n% constant = psi(hp_posterior.tilde_alpha(c)) - psi(sum(hp_posterior.tilde_alpha));\n% elseif isequal(opts.algorithm, 'cdp')\n% constant = 0;\n% elseif isequal(opts.algorithm, 'csb')\n% constant = 0;\n% else\n% error('unknown algorithm')\n% end\n% constant = constant - 0.5*D*log(pi) - 0.5*detln(hp_posterior.B{c}) ...\n% + 0.5*psi_sum(c) - 0.5*D/(hp_posterior.xi(c));\n% if opts.use_kd_tree\n% t2 = sum_x.*repmat(hp_posterior.m(:,c)',[D,1,N]);\n% term_dependent_on_n = (t1 - t2 - permute(t2,[2,1,3]))./Na + ...\n% repmat(hp_posterior.m(:,c)*hp_posterior.m(:,c)',[1,1,N]);\n% column_c = - sum(sum(repmat(Precision,[1,1,N]).*term_dependent_on_n,2),1) + constant;\n% else\n% d = data.given_data - repmat(hp_posterior.m(:,c),1,N);\n% column_c = - sum(d.*(Precision*d),1) + constant; % 1*N\n% end\n% if isequal(opts.algorithm, 'csb') | isequal(opts.algorithm, 'cdp')\n% column_c = column_c + E_log_p_of_z_given_other_z(:,c)';\n% end\n% log_lambda(:,c) = column_c;\n if isequal(opts.algorithm, 'vdp')\n E_log_p_of_z_given_other_z_c = ...\n psi(hp_posterior.gamma(1,c)) ...\n - psi(sum(hp_posterior.gamma(:,c),1)) ...\n + sum(psi(hp_posterior.gamma(2,[1:c-1])) - psi(sum(hp_posterior.gamma(:,[1:c-1]),1)), 2);\n elseif isequal(opts.algorithm, 'bj')\n if c < K\n E_log_p_of_z_given_other_z_c = ...\n psi(hp_posterior.gamma(1,c)) ...\n - psi(sum(hp_posterior.gamma(:,c),1)) ...\n + sum(psi(hp_posterior.gamma(2,[1:c-1])) - psi(sum(hp_posterior.gamma(:,[1:c-1]),1)), 2);\n else\n E_log_p_of_z_given_other_z_c = sum(psi(hp_posterior.gamma(2,[1:c-1])) ...\n - psi(sum(hp_posterior.gamma(:,[1:c-1]),1)), 2);\n end\n elseif isequal(opts.algorithm, 'non_dp')\n % E[log pi] ; pi is the weight of mixtures.\n E_log_p_of_z_given_other_z_c = psi(hp_posterior.tilde_alpha(c)) ...\n - psi(sum(hp_posterior.tilde_alpha));\n elseif isequal(opts.algorithm, 'csb') | isequal(opts.algorithm, 'cdp')\n E_log_p_of_z_given_other_z_c = E_log_p_of_z_given_other_z(:,c)';\n else\n error('unknown algorithm')\n end\n\n Precision = 0.5*hp_posterior.inv_B(:,:,c)*hp_posterior.eta(c);\n E_log_p_of_x = - 0.5*D*log(pi) - 0.5*detln(hp_posterior.B{c}) ...\n + 0.5*psi_sum(c) - 0.5*D/(hp_posterior.xi(c));\n if opts.use_kd_tree\n t2 = sum_x.*repmat(hp_posterior.m(:,c)',[D,1,N]);\n term_dependent_on_n = (t1 - t2 - permute(t2,[2,1,3]))./Na + ...\n repmat(hp_posterior.m(:,c)*hp_posterior.m(:,c)',[1,1,N]);\n E_log_p_of_x = - sum(sum(repmat(Precision,[1,1,N]).*term_dependent_on_n,2),1) + E_log_p_of_x;\n else\n d = data.given_data - repmat(hp_posterior.m(:,c),1,N);\n E_log_p_of_x = - sum(d.*(Precision*d),1) + E_log_p_of_x; % 1*N\n end\n log_lambda(:,c) = E_log_p_of_x + E_log_p_of_z_given_other_z_c;\nend\nif isequal(opts.algorithm, 'vdp')\n log_lambda(:,end) = log_lambda(:,end) - log(1- exp(psi(hp_prior.alpha) - psi(1+hp_prior.alpha)));\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [q_of_z, data, log_lambda] = mk_q_of_z(data, hp_posterior, hp_prior, opts, log_lambda);\n% q_of_z: N*K\nif nargin == 4\n log_lambda = mk_log_lambda(data, hp_posterior, hp_prior, opts);\nend\nq_of_z = exp(normalizeln(log_lambda, 1));\nif opts.weight ~= 1\n q_of_z = q_of_z .* repmat(opts.weight, 1, size(q_of_z,2));\nelse\n q_of_z = q_of_z;\nend\n\nfunction M =normalizeln(M ,dimension);\nM = lpt2lcpt(M, dimension);\n\nfunction lcpt=lpt2lcpt(lpt,dimension);\n% function lcpt=lpt2lcpt(lpt,dimension);\n%\n% make a log conditional probability table with log probability table\n%\n% lpt is a matrix.\n% dimension must be either 1 or 2.\n%\n% lcpt = log( exp(lpt) / sum(exp(lpt)) )\n% = lpt - log(sum(exp(lpt)))\n%\n\nthe_other_dimension=-(dimension-1.5)+1.5;\nlpt=permute(lpt,[dimension,the_other_dimension]);\n% now we can calculate as if dimension=1.\n\nlog_sum_exp_lpt = log_sum_exp(lpt,2); % Mx1\nlcpt = lpt - repmat(log_sum_exp_lpt,1,size(lpt,2));\n\nlcpt=permute(lcpt,[dimension,the_other_dimension]);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction hp_prior = mk_hp_prior(data, opts)\nif isfield(opts, 'xi0')\n hp_prior.xi0 = opts.xi0;\nelse\n hp_prior.xi0 = 0.01;\nend\nif isfield(opts, 'eta_p')\n eta_p = opts.eta_p;\nelse\n eta_p = 1;\nend\nif isfield(opts, 'alpha')\n hp_prior.alpha = opts.alpha;\nelse\n hp_prior.alpha = 1;\nend\n[D,N] = size(data.given_data);\nif opts.use_kd_tree\n sum_xx = sum(reshape([data.kdtree(:).sum_xx],D,D,length(data.kdtree)),3);\n sum_x = sum([data.kdtree(:).sum_x],2);\n covariance = sum_xx/N - sum_x*sum_x'/(N*N);\nelse\n covariance = cov(data.given_data');\nend\nhp_prior.m0 = mean(data.given_data, 2);\nif D > 16\n [dummy, max_eig] = power_method(covariance);\nelse\n max_eig = max(eig(covariance));\nend\nhp_prior.eta0 = eta_p * D + 1;\nhp_prior.B0 = hp_prior.eta0 * max_eig * eye(D) * hp_prior.xi0;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [vec,value]=power_method(A, start, precision)\n\nswitch nargin\n case 1\n start = ones(length(A),1);\n precision = 1e-10;\n case 2\n precision = 1e-10;\n case 3\n otherwise\n error 'invalid number of arguments'\nend\n\n%\n% xp = A^p * x\n% x(p+1) = lambda * xp when p is big enough\n% lambda = x(p+1)'*xp / xp'*xp\n% \ndiff=precision+1;\nx=start;\nn=norm(x)+diff;\ni = 0;\nwhile diff> precision\n i = i + 1;\n y=A*x;\n n2 = norm(x);\n diff=abs(n2-n);\n n=n2;\n if n < 1.0e-200\n x = zeros(length(A), 1);\n break\n else\n x=y/n;\n end\n if i > 100\n break\n end\nend\nn = norm(x);\nif n < 1.0e-200\n vec = zeros(length(A), 1);\nelse\n vec = x/n;\nend\nvalue=n;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction m=normalize(m,dim)\n% return m normalized with 'dimension'\n%\n% e.g.\n% m : i by j by k by ...\n% m = sum(normalize(m,2), 2);\n% m(i, :, k, ...) = ones(1, J, 1, ...)\n%\n\ndims = ones(1, ndims(m));\ndims(dim) = size(m, dim);\nm = m ./ repmat(sum(m, dim), dims);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [Y] = detln( X )\n% Y = logdet( X )\n% return a log determinant of X\n[d err] = chol(X);\nif err\n error('error in Choleski disposition for detln');\nend\nY = sum(log(diag(d))) *2;\n\n% Local Variables: ***\n% mode: matlab ***\n% End: ***\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/vdpgm-2010-06-01/vdpgm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.37729761127357875}} {"text": "function y = kron(X,Y)\n%KRON (overloaded)\n\nif isequal(X,1)\n y = Y;\n return;\nend\n\nif isequal(Y,1);\n y = X;\nend\n\nif (isa(X,'sdpvar') & isa(Y,'sdpvar'))\n y = [];\n s.type = '()';\n for i = 1:size(X,1)\n this_row = []; \n for j = 1:size(X,2);\n s.subs = {i,j};\n this_row = [this_row subsref(X,s)*Y];\n end\n y = [y;this_row];\n end \n return\nend\n\nif isa(X,'sdpvar')\n lmi_variables = getvariables(X);\n nv = length(lmi_variables);\n y = X;\n sparse_Y = sparse(Y);\n % This one used also for checking size\n temp = kron(getbasematrix(X,0),sparse_Y);\n if size(Y,2)==1\n % Special case\n % [kron([N1(:) N2(:)],vec(M))]=[vec(kron(N1,M)) vec(kron(N2,M))]\n y.basis = kron(X.basis,sparse_Y);\n else\n y.basis=temp(:);\n X_base = X.basis;\n for i = 1:nv\n % temp = kron(getbasematrix(X,lmi_variables(i)),sparse_Y); \n temp = kron(reshape(X_base(:,i+1),X.dim),sparse_Y);\n y.basis(:,i+1) = temp(:);\n end;\n end\nend\n\nif isa(Y,'sdpvar')\n lmi_variables = getvariables(Y);\n nv = length(lmi_variables);\n y = Y;\n sparse_X = sparse(X);\n % This one used also for checking size\n temp = kron(sparse_X,getbasematrix(Y,0));\n if size(X,1)==1\n % In this special case\n %[kron(vec(M),[N1(:) N2(:)])]==[vec(kron(M,N1)) vec(kron(M,N2))] \n y.basis = kron(sparse_X(:),Y.basis);\n else\n y.basis = temp(:);\n y.basis = spalloc(length(temp(:)),nv+1,0);\n y.basis(:,1) = temp(:);\n Y_base = Y.basis;\n for i = 1:nv\n % temp = kron(sparse_X,getbasematrix(Y,lmi_variables(i)));\n temp = kron(sparse_X,reshape(Y_base(:,i+1),Y.dim));\n y.basis(:,i+1) = temp(:);\n end\n end\nend\ny.dim(1) = size(temp,1);\ny.dim(2) = size(temp,2);\ny = clean(y);\n% Reset info about conic terms\nif isa(y,'sdpvar')\n y.conicinfo = [0 0];\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/kron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.37725490059787614}} {"text": "% sim_spinecho_xN.m\n% Robin Simpson and Jamie Near, 2014.\n% \n% USAGE:\n% out = sim_spinecho(n,sw,Bfield,linewidth,sys,tau,Nechoes)\n% \n% DESCRIPTION:\n% This function simulates a multi-echo spin-echo experiment with 'Nechoes' instantaneous RF pulses.\n% \n% INPUTS:\n% n = number of points in fid/spectrum\n% sw = desired spectral width in [Hz]\n% Bfield = main magnetic field strength in [T]\n% linewidth = linewidth in [Hz]\n% sys = spin system definition structure\n% tau = echo time in [ms]\n% Nechoes = number of spin echoes (optional. Default = 10);\n%\n% OUTPUTS:\n% out = simulated spectrum, in FID-A structure format, using multi-echo \n% spin-echo sequence.\n\nfunction out = sim_spinecho_xN(n,sw,Bfield,linewidth,sys,tau,Nechoes)\n\nif nargin<7\n Nechoes=10;\nend\n\n%Set water to centre\ncentreFreq=4.65;\nfor k=1:length(sys)\n sys(k).shifts=sys(k).shifts-centreFreq;\nend\n\n%Calculate Hamiltonian matrices and starting density matrix.\n[H,d]=sim_Hamiltonian(sys,Bfield);\n\ndelay=tau/(2*Nechoes);\n\n%BEGIN PULSE SEQUENCE************\nd=sim_excite(d,H,'x'); %EXCITE\nfor k=1:Nechoes\n d=sim_evolve(d,H,delay/1000); %Evolve by tau/2\n d=sim_rotate(d,H,180,'y'); %180 degree refocusing pulse about y' axis.\n d=sim_evolve(d,H,delay/1000); %Evolve by tau/2\nend\n[out,dout]=sim_readout(d,H,n,sw,linewidth,90); %Readout along y (90 degree phase);\n%END PULSE SEQUENCE**************\n\n%Correct the ppm scale:\nout.ppm=out.ppm-(4.65-centreFreq);\n\n%Fill in structure header fields:\nout.seq=['spinecho_x' num2str(Nechoes)];\nout.te=tau;\nout.sim='ideal';\n\n%Additional fields for compatibility with FID-A processing tools.\nout.sz=size(out.specs);\nout.date=date;\nout.dims.t=1;\nout.dims.coils=0;\nout.dims.averages=0;\nout.dims.subSpecs=0;\nout.dims.extras=0;\nout.averages=1;\nout.rawAverages=1;\nout.subspecs=1;\nout.rawSubspecs=1;\nout.flags.writtentostruct=1;\nout.flags.gotparams=1;\nout.flags.leftshifted=0;\nout.flags.filtered=0;\nout.flags.zeropadded=0;\nout.flags.freqcorrected=0;\nout.flags.phasecorrected=0;\nout.flags.averaged=1;\nout.flags.addedrcvrs=1;\nout.flags.subtracted=1;\nout.flags.writtentotext=0;\nout.flags.downsampled=0;\nout.flags.isFourSteps=0;\n\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/simulationTools/sim_spinecho_xN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.37716063435133335}} {"text": "%{\n * Copyright (C) 2020-2030, 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 difference = H_diff(H1, H2)\n difference = H1 \\ H2;\n logR = logm(difference(1:3,1:3));\n v = [-logR(1,2) logR(1,3) -logR(2,3) difference(1:3,4)'];\n difference = norm(v);\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/H_diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.37663760976798283}} {"text": " function [xs, info] = ir_pwls_os_rlalm(x, Ab, yi, R, varargin)\n%function [xs, info] = ir_pwls_os_rlalm(x, Ab, yi, R, [options])\n%|\n%| penalized weighted least squares estimation / image reconstruction\n%| using relaxed linearized augmented lagrangian method with\n%| (optionally relaxed) ordered subsets. (relaxed OS-LALM)\n%|\n%| See ?. 201? IEEE T-MI by Hung Nien & J A Fessler\n%| \"Relaxed linearized algorithms for faster X-ray CT image reconstruction\"\n%|\thttp://dx.doi.org/10.1109/TMI.201?\n%|\n%|\n%| cost(x) = (y-Ax)' W (y-Ax) / 2 + R(x)\n%|\n%| in\n%|\tx\t[np 1]\t\tinitial estimate\n%|\tAb\t[nd np]\t\tGblock object (needs abs(Ab) method)\n%|\t\t\t\tor sparse matrix (implies nsubset=1)\n%|\tyi\t[nb na]\t\tmeasurements (noisy sinogram data)\n%|\tR\tpenalty\t\tobject (see Reg1.m), can be []\n%|\n%| option\n%|\tniter\t\t\t# of iterations (default: 1)\n%|\twi\t[nb na]\t\tweighting sinogram (default: [] for uniform)\n%|\tpixmax\t[1] or [2]\tmax pixel value, or [min max] (default [0 inf])\n%|\tdenom\t[np 1]\t\tprecomputed denominator\n%|\taai\t[nb na]\t\tprecomputed row sums of |Ab|\n%|\trelax0\t[1] or [2]\trelax0 or (relax0, relax_rate) (default 1)\n%|\trho\t\t\tAL penalty parameter (default: [] for decreasing rho)\n%|\talpha\t\t\tover-relaxation parameter (default: 1.999)\n%|\tuserfun\t@\t\tuser-defined function handle (see default below)\n%|\t\t\t\t\ttaking arguments (x, userarg{:})\n%|\tuserarg\t{}\t\tuser arguments to userfun (default {})\n%|\tchat\n%|\n%| out\n%|\txs\t[np niter]\titerates\n%|\tinfo\t[niter 1]\ttime\n%|\n%| 2015-11-30, Hung Nien, based on ir_pwls_os_lalm\n%| 2015-11-30, tweaks by Jeff Fessler\n\nif nargin == 1 && streq(x, 'test'), ir_pwls_os_rlalm_test, return, end\nif nargin < 4, ir_usage, end\n\n% defaults\narg.niter = 1;\narg.isave = [];\narg.userfun = @userfun_default;\narg.userarg = {};\narg.pixmax = inf;\narg.chat = false;\narg.wi = [];\narg.aai = [];\narg.rho = []; % default: decreasing rho\narg.alpha = 1.999;\narg.relax0 = 1;\narg.denom = [];\narg.scale_nblock = true; % traditional scaling\narg.update_even_if_denom_0 = true;\narg = vararg_pair(arg, varargin);\n\narg.isave = iter_saver(arg.isave, arg.niter);\n\nAb = block_op(Ab, 'ensure'); % make it a block object (if not already)\nnblock = block_op(Ab, 'n');\nstarts = subset_start(nblock);\n\ncpu etic\n\nwi = arg.wi;\nif isempty(wi)\n\twi = ones(size(yi), class(yi));\nend\nif isempty(arg.aai) && isempty(arg.denom)\n\targ.aai = reshape(sum(abs(Ab)'), size(yi)); % a_i = sum_j |a_ij|\nend\n\n% check input sinogram sizes for OS\nif (ndims(yi) ~= 2) || (size(yi,2) == 1 && nblock > 1)\n\tfail 'bad yi size'\nend\nif (ndims(wi) ~= 2) || (size(wi,2) == 1 && nblock > 1)\n\tfail 'bad wi size'\nend\n\nrelax0 = arg.relax0(1);\nif length(arg.relax0) == 1\n\trelax_rate = 0;\nelseif length(arg.relax0) == 2\n\trelax_rate = arg.relax0(2);\nelse\n\terror relax\nend\n\nif length(arg.pixmax) == 2\n\tpixmin = arg.pixmax(1);\n\tpixmax = arg.pixmax(2);\nelseif length(arg.pixmax) == 1\n\tpixmin = 0;\n\tpixmax = arg.pixmax;\nelse\n\terror pixmax\nend\n\n% likelihood denom, if not provided\ndenom = arg.denom;\nif isempty(denom)\n\tdenom = abs(Ab)' * col(arg.aai .* wi); % needs abs(Ab)\n arg = rmfield(arg, 'aai'); % clear to save memory - not needed below\nend\nif ~arg.update_even_if_denom_0\n\t% todo: this may not work for LALM because \"denom\" appears in numerator!\n\tdenom(denom == 0) = inf; % trick: prevents pixels where denom=0 being updated\nend\n\nif isempty(R)\n\tpgrad = 0; % unregularized default\n\tRdenom = 0;\nend\n\nalpha = arg.alpha;\nif alpha<1 || alpha>2\n\tfail 'alpha should be between 1 and 2'\nend\n\nrho = arg.rho;\nif isempty(rho)\n\trho = @(k) pi/(alpha*k) * sqrt(1 - (pi/(2*(alpha*k)))^2) * (k>1) + (k==1);\nelse\n\trho = @(k) rho; % constant user-specified value\nend\n\n[nb na] = size(yi);\n\nx = x(:);\nnp = length(x);\nxs = zeros(np, length(arg.isave), 'single');\nif any(arg.isave == 0)\n\txs(:, arg.isave == 0) = single(x);\nend\n\n%info = zeros(niter,?); % do not initialize since size may change\n\n% initialization\niblock = nblock;\nia = iblock:nblock:na;\nli = Ab{iblock} * x;\nli = reshape(li, nb, length(ia));\nresid = wi(:,ia) .* (li - yi(:,ia));\nif arg.scale_nblock\n\tscale = nblock; % traditional way\nelse\n\tscale = na / numel(ia); % alternative - untested\nend\nzeta = scale * Ab{iblock}' * resid(:);\n\ng = rho(1) * zeta;\nh = denom .* x - zeta;\n\n% iterate\nfor iter = 1:arg.niter\n\tticker(mfilename, iter, arg.niter)\n\n\trelax = relax0 / (1 + relax_rate * (iter-1));\n\n\t% loop over subsets\n\tfor iset = 1:nblock\n\t\tk = nblock*(iter-1)+iset;\n\n\t\tnum = rho(k) * (denom .* x - h) + (1-rho(k)) * g;\n\t\tden = rho(k) * denom;\n\t\tif ~isempty(R)\n\t\t\tnum = num + R.cgrad(R, x);\n\t\t\tden = den + R.denom(R, x);\n\t\tend\n\t\tx = x - relax * num ./ den;\n\t\tx = max(x, pixmin);\n\t\tx = min(x, pixmax);\n\n\t\tiblock = starts(iset);\n\t\tia = iblock:nblock:na;\n\n\t\tli = Ab{iblock} * x;\n\t\tli = reshape(li, nb, length(ia));\n\t\tresid = wi(:,ia) .* (li - yi(:,ia));\n\n\t\tif arg.scale_nblock\n\t\t\tscale = nblock; % traditional way\n\t\telse\n\t\t\tscale = na / numel(ia); % alternative - untested\n\t\tend\n\n\t\tzeta = scale * Ab{iblock}' * resid(:); % A' * W * (y - A*x)\n\t\tg = (rho(k) * (alpha * zeta + (1-alpha) * g) + g) / (rho(k)+1);\n\t\th = alpha * (denom .* x - zeta) + (1-alpha) * h;\n\tend\n\n\tif any(arg.isave == iter)\n\t\txs(:, arg.isave == iter) = single(x);\n\tend\n\tinfo(iter,:) = arg.userfun(x, arg.userarg{:});\nend\n\n\n% default user function.\n% using this evalin('caller', ...) trick, one can compute anything of interest\nfunction out = userfun_default(x, varargin)\nchat = evalin('caller', 'arg.chat');\nif chat\n%\tx = evalin('caller', 'x');\n\tprintm('minmax(x) = %g %g', min(x), max(x))\nend\nout = cpu('etoc');\n\n\n% ir_pwls_os_rlalm_test()\n% test with small quadratic case 1/2 |y - A x|_2^2 + 1/2 |C x|_2^2\n% see also ir_ct_fan_beam_sqs_vs_lalm.m\nfunction ir_pwls_os_rlalm_test\nrng(0)\nnd = 99; np = 38;\nA = randn(nd,np);\nA = abs(A);\nR = Reg1(ones(np,1), 'type_penal', 'mat', 'type_diff', 'sparse', 'beta', 2^0);\nC = R.C;\nC = full(C);\nif 0 % try to make it so unit step size is reasonable?\n\tD = abs(A)' * (abs(A) * ones(np,1)) + abs(C)' * (abs(C) * ones(np,1));\n\tA = A * diag(sqrt(1 ./ D));\n\tC = C * diag(sqrt(1 ./ D));\nend\nH = A' * A + C' * C;\npr cond(H)\n\nxtrue = ones(np,1); xtrue(10:20) = 2;\nyi = A * xtrue; yi = yi + 0.01 * max(yi(:)) * randn(nd,1);\nxhat = H \\ (A' * yi);\n% nrms(xhat, xtrue)\n\nx0 = zeros(np,1);\nniter = 100;\n\nprintm 'Nesterov' % todo: replace with OGM\ngradfun = @(x) A' * (A * x - yi) + C' * (C * x);\nstep = abs(A') * (abs(A) * ones(np,1)) + abs(C)' * (abs(C) * ones(np,1));\nstep = 1 / max(step); % todo: use D\nxf = ir_fista(x0, 'gradfun', gradfun, 'step', step, 'niter', niter, ...\n\t'isave', 'all');\n\nprintm 'Relaxed LALM'\nxl = ir_pwls_os_rlalm(x0, Gmatrix(A), yi, R, 'niter', niter, 'isave', 'all');\n\nprintm 'CG'\nxc = qpwls_pcg1(x0, A, 1, yi, R.C, 'niter', niter, 'isave', 'all');\n\nif im\n\tim plc 1 2\n\tim subplot 1\n\tplot([xtrue xhat xl(:,end) xc(:,end) xf(:,end)])\n\tim subplot 2\n\txlabel 'iteration', ylabelf 'NRMSD $x^n$ vs $\\hat{x}$'\n\tplot(\t0:niter, nrms(xl, xhat), 'r-', ...\n\t\t0:niter, nrms(xf, xhat), 'g-', ...\n\t\t0:niter, nrms(xc, xhat), 'c-')\n\tlegend('Relaxed LALM', 'FGM', 'CG')\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/ir_pwls_os_rlalm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3765845219217833}} {"text": "function [a]=plus(b,c)\n%A=B+C\n% [A]=PLUS(B,C) A is the sum of TT-matrices B and C\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%---------------------------\nif ( isempty(b) )\n a=c;\n return\nelseif (isempty(c) )\n a=b;\n return\nend\n a=tt_matrix;\na.n=b.n;\na.m=b.m;\na.tt=b.tt+c.tt;\nreturn\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/@tt_matrix/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3765671062094402}} {"text": "%% Microstrip low-pass filter analysis using 3D FDTD code with UPML \n%% absorbing borders (ABC)\n%\n% Here we use FDTD 3D with UPML to calculate scattering coefficients S_{11} \n% and S_{21} for planar microstrip low-pass filter following by the original \n% paper by D. Sheen, S. Ali, M. Abouzahra, J. Kong \"Application of the \n% Three-Dimensional Finite-Difference Time-Domain Method to the Analysis of\n% planar Microstrip Circuits\", IEEE Trans. on Microwave Theory and Techniques\n% (http://dx.doi.org/10.1109/22.55775). \n% Also |S_{21}| dependence can be taken from the paper \"Computational\n% electromagnetic method for interconnects and small structures\" by C.\n% Balanis, A. Policarpou and S. Georgakopoulos \n% (http://dx.doi.org/10.1006/spmi.2000.0865)\n%% Current code includes some improvements in comparison with the original \n%% calculations:\n% 1) imposing UPML instead of Mur ABCs;\n% 2) using real metal (copper) as a patch conductor material instead of PEC;\n% 3) applying matched load at the ends of filter's transmission microstrip\n% lines to prevent physical reflections;\n% 4) no \"magnetic wall\" or \"electric wall\" conditions at the Ez source plane.\n%\nfunction FDTD_3D_Lowpass\nclose all; clear; clc;\n%% Physical constants\n epsilon0 = 8.85418782e-12; mu0 = 1.25663706e-6;\n c = 1.0/sqrt(mu0*epsilon0);\n\n%% Gaussian half-width\n t_half = 15.0e-12;\n\n%% Microstrip transmission lines parameters\n lineW = 2.413e-3; \n lineH = 1.0e-3;\n lineEr = 2.2;\n Z0 = 49.2526;\n\n%% End time\n t_end = 1.5e-9;\n\n%% Total mesh dimensions and grid cells sizes (without PML)\n nx = 80; ny = 100; nz = 16;\n dx = 0.4064e-3; dy = 0.4233e-3; dz = 0.2650e-3;\n\n%% Number of PML layers\n PML = 5;\n\n%% Matrix of material's constants\n number_of_materials = 4;\n % For material of number x = 1,2,3... :\n % Material(x,1) - relative permittivity, Material(x,2) - relative permeability,\n % Material(x,3) - specific conductivity\n % Vacuum\n Material(1,1) = 1.0; Material(1,2) = 1.0; Material(1,3) = 0.0;\n % Metal (Copper)\n Material(2,1) = 1.0; Material(2,2) = 1.0; Material(2,3) = 5.88e+7;\n % Substrate material (RT/Duroid 5880)\n Material(3,1) = lineEr; Material(3,2) = 1.0; Material(3,3) = 0.0;\n % Matched load material is calculated from transmission line parameters\n Material(4,1) = 1.0; Material(4,2) = 1.0; Material(4,3) = lineH/(Z0*lineW*dy);\n\n% Add PML layers\n nx = nx + 2*PML; ny = ny + 2*PML; nz = nz + 2*PML;\n% Calculate dt \n dt = (1.0/c/sqrt( 1.0/(dx^2) + 1.0/(dy^2) + 1.0/(dz^2)))*0.9999;\n number_of_iterations = ceil(t_end/dt);\n\n%% 3D array for geometry\n Index = ones(nx, ny, nz);\n\n%% Define of low-pass filter geometry\n % Ground plane \n Index((1+PML):(nx-PML), (1+PML):(ny-PML), PML+1) = 2;\n % Rectangular patch (one cell thickness)\n Index((nx/2-25):(nx/2+25), (ny/2-3):(ny/2+3), PML+5) = 2;\n % Transmission line from port 1 to rectangular patch\n Index((nx/2-10):(nx/2-5), (PML+1):ny/2, PML+5) = 2;\n % Transmission line from rectangular patch to port 2\n Index((nx/2+5):(nx/2+10), ny/2:(ny-PML), PML+5) = 2;\n % Dielectric substrate between ground plane and filter patch\n Index((1+PML):(nx-PML), (1+PML):(ny-PML), (PML+2):(PML+4)) = 3;\n % Matched load before port 1\n Index((nx/2-10):(nx/2-5), PML+1, (PML+2):(PML+4)) = 4;\n % Matched load after port 2\n Index((nx/2+5):(nx/2+10), ny-PML, (PML+2):(PML+4)) = 4;\n \n%% 3D FDTD physical (fields) and additional arrays are defined as 'single' \n%% to increase performance\n Ex = zeros(nx, ny+1, nz+1, 'single'); \n Gx = zeros(nx, ny+1, nz+1, 'single'); \n Fx = zeros(nx, ny+1, nz+1, 'single'); \n Ey = zeros(nx+1, ny, nz+1, 'single'); \n Gy = zeros(nx+1, ny, nz+1, 'single'); \n Fy = zeros(nx+1, ny, nz+1, 'single');\n Ez = zeros(nx+1, ny+1, nz, 'single'); \n Gz = zeros(nx+1, ny+1, nz, 'single'); \n Fz = zeros(nx+1, ny+1, nz, 'single');\n Hx = zeros(nx+1, ny, nz, 'single'); \n Bx = zeros(nx+1, ny, nz, 'single'); \n Hy = zeros(nx, ny+1, nz, 'single');\n By = zeros(nx, ny+1, nz, 'single'); \n Hz = zeros(nx, ny, nz+1, 'single'); \n Bz = zeros(nx, ny, nz+1, 'single');\n\n%% FDTD PML coefficients arrays. Here they are already filled with values \n%% corresponding to free space \n m = 4; ka_max = 1.0; R_err = 1.0e-16;\n eta = sqrt(mu0/epsilon0*Material(1,1)/Material(1,2));\n k_Ex_c = ones(nx, ny, nz, 'single')*2.0*epsilon0; \n k_Ex_d = ones(nx, ny, nz, 'single')*(-2.0*epsilon0);\n k_Ey_a = ones(nx+1, ny, nz, 'single');\n k_Ey_b = ones(nx+1, ny, nz, 'single')/(2.0*epsilon0);\n k_Gz_a = ones(nx+1, ny, nz, 'single');\n k_Gz_b = ones(nx+1, ny, nz, 'single');\n k_Hy_a = ones(nx, ny, nz, 'single'); \n k_Hy_b = ones(nx, ny, nz, 'single')/(2.0*epsilon0);\n k_Hx_c = ones(nx+1, ny, nz, 'single')*2.0*epsilon0/mu0;\n k_Hx_d = ones(nx+1, ny, nz, 'single')*(-2.0*epsilon0/mu0);\n k_Bz_a = ones(nx, ny, nz, 'single');\n k_Bz_b = ones(nx, ny, nz, 'single')*dt;\n k_Gx_a = ones(nx, ny+1, nz, 'single');\n k_Gx_b = ones(nx, ny+1, nz, 'single');\n k_Ey_c = ones(nx, ny, nz, 'single')*2.0*epsilon0; \n k_Ey_d = ones(nx, ny, nz, 'single')*(-2.0*epsilon0);\n k_Ez_a = ones(nx, ny+1, nz, 'single'); \n k_Ez_b = ones(nx, ny+1, nz, 'single')/(2.0*epsilon0);\n k_Bx_a = ones(nx, ny, nz, 'single'); \n k_Bx_b = ones(nx, ny, nz, 'single')*dt;\n k_Hy_c = ones(nx, ny+1, nz, 'single')*2.0*epsilon0/mu0;\n k_Hy_d = ones(nx, ny+1, nz, 'single')*(-2.0*epsilon0/mu0);\n k_Hz_a = ones(nx, ny, nz, 'single');\n k_Hz_b = ones(nx, ny, nz, 'single')/(2.0*epsilon0);\n k_Ex_a = ones(nx, ny, nz+1, 'single');\n k_Ex_b = ones(nx, ny, nz+1, 'single')/(2.0*epsilon0);\n k_Gy_a = ones(nx, ny, nz+1, 'single'); \n k_Gy_b = ones(nx, ny, nz+1, 'single');\n k_Ez_c = ones(nx, ny, nz, 'single')*2.0*epsilon0;\n k_Ez_d = ones(nx, ny, nz, 'single')*(-2.0*epsilon0);\n k_Hx_a = ones(nx, ny, nz, 'single');\n k_Hx_b = ones(nx, ny, nz, 'single')/(2.0*epsilon0);\n k_By_a = ones(nx, ny, nz, 'single'); \n k_By_b = ones(nx, ny, nz, 'single')*dt;\n k_Hz_c = ones(nx, ny, nz+1, 'single')*2.0*epsilon0/mu0; \n k_Hz_d = ones(nx, ny, nz+1, 'single')*(-2.0*epsilon0/mu0);\n\n%% General FDTD coefficients \n I = 1:number_of_materials;\n K_a(I) = (2.0*epsilon0*Material(I,1) - Material(I,3)*dt)./...\n (2.0*epsilon0*Material(I,1) + Material(I,3)*dt);\n K_b(I) = 2.0*dt./(2.0*epsilon0*Material(I,1) + Material(I,3)*dt);\n K_c(I) = Material(I,2);\n Ka = single(K_a(Index)); Kb = single(K_b(Index)); Kc = single(K_c(Index));\n \n%% PML coefficients along x-axis\n sigma_max = -(m + 1.0)*log(R_err)/(2.0*eta*PML*dx);\n for I=0:(PML-1)\n sigma_x = sigma_max*((PML - I)/PML)^m;\n ka_x = 1.0 + (ka_max - 1.0)*((PML - I)/PML)^m;\n k_Ey_a(I+1,:,:) = (2.0*epsilon0*ka_x - sigma_x*dt)/...\n (2.0*epsilon0*ka_x + sigma_x*dt);\n k_Ey_a(nx-I,:,:) = k_Ey_a(I+1,:,:);\n k_Ey_b(I+1,:,:) = 1.0/(2.0*epsilon0*ka_x + sigma_x*dt);\n k_Ey_b(nx-I,:,:) = k_Ey_b(I+1,:,:);\n k_Gz_a(I+1,:,:) = (2.0*epsilon0*ka_x - sigma_x*dt)/...\n (2.0*epsilon0*ka_x + sigma_x*dt);\n k_Gz_a(nx-I,:,:) = k_Gz_a(I+1,:,:);\n k_Gz_b(I+1,:,:) = 2.0*epsilon0/(2.0*epsilon0*ka_x + sigma_x*dt);\n k_Gz_b(nx-I,:,:) = k_Gz_b(I+1,:,:);\n k_Hx_c(I+1,:,:) = (2.0*epsilon0*ka_x + sigma_x*dt)/mu0;\n k_Hx_c(nx-I,:,:) = k_Hx_c(I+1,:,:);\n k_Hx_d(I+1,:,:) = -(2.0*epsilon0*ka_x - sigma_x*dt)/mu0;\n k_Hx_d(nx-I,:,:) = k_Hx_d(I+1,:,:);\n\n sigma_x = sigma_max*((PML - I - 0.5)/PML)^m;\n ka_x = 1.0 + (ka_max - 1.0)*((PML - I - 0.5)/PML)^m;\n k_Ex_c(I+1,:,:) = 2.0*epsilon0*ka_x + sigma_x*dt;\n k_Ex_c(nx-I-1,:,:) = k_Ex_c(I+1,:,:);\n k_Ex_d(I+1,:,:) = -(2.0*epsilon0*ka_x - sigma_x*dt);\n k_Ex_d(nx-I-1,:,:) = k_Ex_d(I+1,:,:);\n k_Hy_a(I+1,:,:) = (2.0*epsilon0*ka_x - sigma_x*dt)/...\n (2.0*epsilon0*ka_x + sigma_x*dt);\n k_Hy_a(nx-I-1,:,:) = k_Hy_a(I+1,:,:);\n k_Hy_b(I+1,:,:) = 1.0/(2.0*epsilon0*ka_x + sigma_x*dt);\n k_Hy_b(nx-I-1,:,:) = k_Hy_b(I+1,:,:);\n k_Bz_a(I+1,:,:) = (2.0*epsilon0*ka_x - sigma_x*dt)/...\n (2.0*epsilon0*ka_x + sigma_x*dt);\n k_Bz_a(nx-I-1,:,:) = k_Bz_a(I+1,:,:);\n k_Bz_b(I+1,:,:) = 2.0*epsilon0*dt/(2.0*epsilon0*ka_x + sigma_x*dt);\n k_Bz_b(nx-I-1,:,:) = k_Bz_b(I+1,:,:);\n end\n\n%% PML coefficients along y-axis\n sigma_max = -(m + 1.0)*log(R_err)/(2.0*eta*PML*dy);\n for J=0:(PML-1)\n sigma_y = sigma_max*((PML - J)/PML)^m;\n ka_y = 1.0 + (ka_max - 1.0)*((PML - J)/PML)^m;\n k_Gx_a(:,J+1,:) = (2.0*epsilon0*ka_y - sigma_y*dt)/...\n (2.0*epsilon0*ka_y + sigma_y*dt);\n k_Gx_a(:,ny-J,:) = k_Gx_a(:,J+1,:);\n k_Gx_b(:,J+1,:) = 2.0*epsilon0/(2.0*epsilon0*ka_y + sigma_y*dt);\n k_Gx_b(:,ny-J,:) = k_Gx_b(:,J+1,:);\n k_Ez_a(:,J+1,:) = (2.0*epsilon0*ka_y - sigma_y*dt)/...\n (2.0*epsilon0*ka_y + sigma_y*dt);\n k_Ez_a(:,ny-J,:) = k_Ez_a(:,J+1,:);\n k_Ez_b(:,J+1,:) = 1.0/(2.0*epsilon0*ka_y + sigma_y*dt);\n k_Ez_b(:,ny-J,:) = k_Ez_b(:,J+1,:);\n k_Hy_c(:,J+1,:) = (2.0*epsilon0*ka_y + sigma_y*dt)/mu0;\n k_Hy_c(:,ny-J,:) = k_Hy_c(:,J+1,:);\n k_Hy_d(:,J+1,:) = -(2.0*epsilon0*ka_y - sigma_y*dt)/mu0;\n k_Hy_d(:,ny-J,:) = k_Hy_d(:,J+1,:);\n\n sigma_y = sigma_max*((PML - J - 0.5)/PML)^m;\n ka_y = 1.0 + (ka_max - 1.0)*((PML - J - 0.5)/PML)^m;\n k_Ey_c(:,J+1,:) = 2.0*epsilon0*ka_y+sigma_y*dt;\n k_Ey_c(:,ny-J-1,:) = k_Ey_c(:,J+1,:);\n k_Ey_d(:,J+1,:) = -(2.0*epsilon0*ka_y-sigma_y*dt);\n k_Ey_d(:,ny-J-1,:) = k_Ey_d(:,J+1,:);\n k_Bx_a(:,J+1,:) = (2.0*epsilon0*ka_y-sigma_y*dt)/...\n (2.0*epsilon0*ka_y+sigma_y*dt);\n k_Bx_a(:,ny-J-1,:) = k_Bx_a(:,J+1,:);\n k_Bx_b(:,J+1,:) = 2.0*epsilon0*dt/(2.0*epsilon0*ka_y+sigma_y*dt);\n k_Bx_b(:,ny-J-1,:) = k_Bx_b(:,J+1,:);\n k_Hz_a(:,J+1,:) = (2.0*epsilon0*ka_y-sigma_y*dt)/...\n (2.0*epsilon0*ka_y+sigma_y*dt);\n k_Hz_a(:,ny-J-1,:) = k_Hz_a(:,J+1,:);\n k_Hz_b(:,J+1,:) = 1.0/(2.0*epsilon0*ka_y+sigma_y*dt);\n k_Hz_b(:,ny-J-1,:) = k_Hz_b(:,J+1,:);\n end\n\n%% PML coefficients along z-axis \n sigma_max = -(m + 1.0)*log(R_err)/(2.0*eta*PML*dz);\n for K=0:(PML-1)\n sigma_z = sigma_max*((PML - K)/PML)^m;\n ka_z = 1.0 + (ka_max - 1.0)*((PML-K)/PML)^m;\n k_Ex_a(:,:,K+1) = (2.0*epsilon0*ka_z - sigma_z*dt)/...\n (2.0*epsilon0*ka_z + sigma_z*dt);\n k_Ex_a(:,:,nz-K) = k_Ex_a(:,:,K+1);\n k_Ex_b(:,:,K+1) = 1.0/(2.0*epsilon0*ka_z + sigma_z*dt);\n k_Ex_b(:,:,nz-K) = k_Ex_b(:,:,K+1);\n k_Gy_a(:,:,K+1) = (2.0*epsilon0*ka_z - sigma_z*dt)/...\n (2.0*epsilon0*ka_z + sigma_z*dt);\n k_Gy_a(:,:,nz-K) = k_Gy_a(:,:,K+1);\n k_Gy_b(:,:,K+1) = 2.0*epsilon0/(2.0*epsilon0*ka_z + sigma_z*dt);\n k_Gy_b(:,:,nz-K) = k_Gy_b(:,:,K+1);\n k_Hz_c(:,:,K+1) = (2.0*epsilon0*ka_z + sigma_z*dt)/mu0;\n k_Hz_c(:,:,nz-K) = k_Hz_c(:,:,K+1);\n k_Hz_d(:,:,K+1) = -(2.0*epsilon0*ka_z - sigma_z*dt)/mu0;\n k_Hz_d(:,:,nz-K) = k_Hz_d(:,:,K+1);\n\n sigma_z = sigma_max*((PML - K - 0.5)/PML)^m;\n ka_z = 1.0 + (ka_max - 1.0)*((PML - K - 0.5)/PML)^m;\n k_Ez_c(:,:,K+1) = 2.0*epsilon0*ka_z + sigma_z*dt;\n k_Ez_c(:,:,nz-K-1) = k_Ez_c(:,:,K+1);\n k_Ez_d(:,:,K+1) = -(2.0*epsilon0*ka_z - sigma_z*dt);\n k_Ez_d(:,:,nz-K-1) = k_Ez_d(:,:,K+1);\n k_Hx_a(:,:,K+1) = (2.0*epsilon0*ka_z - sigma_z*dt)/...\n (2.0*epsilon0*ka_z + sigma_z*dt);\n k_Hx_a(:,:,nz-K-1) = k_Hx_a(:,:,K+1);\n k_Hx_b(:,:,K+1) = 1.0/(2.0*epsilon0*ka_z + sigma_z*dt);\n k_Hx_b(:,:,nz-K-1) = k_Hx_b(:,:,K+1);\n k_By_a(:,:,K+1) = (2.0*epsilon0*ka_z - sigma_z*dt)/...\n (2.0*epsilon0*ka_z + sigma_z*dt);\n k_By_a(:,:,nz-K-1) = k_By_a(:,:,K+1);\n k_By_b(:,:,K+1) = 2.0*epsilon0*dt/(2.0*epsilon0*ka_z + sigma_z*dt);\n k_By_b(:,:,nz-K-1) = k_By_b(:,:,K+1);\n end\n \n%% Main 3D FDTD+UPML routine (operates with 'singles' to increase speed) \n hhh = waitbar(0, 'Calculations in progress...');\n tic;\n for T=0:(number_of_iterations-1)\n %% Calculate Fx -> Gx -> Ex\n I = 1:nx; J = 2:ny; K = 2:nz;\n Fx_r = Fx(I,J,K);\n Fx(I,J,K) = Ka(I,J,K).*Fx(I,J,K) + Kb(I,J,K).*...\n ((Hz(I,J,K) - Hz(I,J-1,K))/dy - (Hy(I,J,K) - Hy(I,J,K-1))/dz);\n Gx_r = Gx(I,J,K);\n Gx(I,J,K) = k_Gx_a(I,J,K).*Gx(I,J,K) + k_Gx_b(I,J,K).*(Fx(I,J,K) - Fx_r);\n Ex(I,J,K) = k_Ex_a(I,J,K).*Ex(I,J,K) + k_Ex_b(I,J,K).*...\n (k_Ex_c(I,J,K).*Gx(I,J,K) + k_Ex_d(I,J,K).*Gx_r);\n\n %% Calculate Fy -> Gy -> Ey\n I = 2:nx; J = 1:ny; K = 2:nz;\n Fy_r = Fy(I,J,K);\n Fy(I,J,K) = Ka(I,J,K).*Fy(I,J,K) + Kb(I,J,K).*...\n ((Hx(I,J,K) - Hx(I,J,K-1))/dz - (Hz(I,J,K) - Hz(I-1,J,K))/dx);\n Gy_r = Gy(I,J,K);\n Gy(I,J,K) = k_Gy_a(I,J,K).*Gy(I,J,K) + k_Gy_b(I,J,K).*(Fy(I,J,K) - Fy_r);\n Ey(I,J,K) = k_Ey_a(I,J,K).*Ey(I,J,K) + k_Ey_b(I,J,K).*...\n (k_Ey_c(I,J,K).*Gy(I,J,K) + k_Ey_d(I,J,K).*Gy_r);\n\n %% Calculate Fz -> Gz -> Ez\n I = 2:nx; J = 2:ny; K = 1:nz;\n Fz_r = Fz(I,J,K);\n Fz(I,J,K) = Ka(I,J,K).*Fz(I,J,K) + Kb(I,J,K).*...\n ((Hy(I,J,K) - Hy(I-1,J,K))/dx - (Hx(I,J,K) - Hx(I,J-1,K))/dy);\n Gz_r = Gz(I,J,K);\n Gz(I,J,K) = k_Gz_a(I,J,K).*Gz(I,J,K) + k_Gz_b(I,J,K).*(Fz(I,J,K) - Fz_r);\n Ez(I,J,K) = k_Ez_a(I,J,K).*Ez(I,J,K) + k_Ez_b(I,J,K).*...\n (k_Ez_c(I,J,K).*Gz(I,J,K) + k_Ez_d(I,J,K).*Gz_r);\n\n %% Source of vertical electric field Ez applied to the whole face \n %% plane at the port 1\n if (T*dt<=10.0*t_half)\n Ez((nx/2-10):(nx/2-5), PML+2, (PML+2):(PML+4)) = Source(t_half, 1.0, T*dt);\n end\n\n %% Save reflected Ez at port 1, passed through Ez at port 2 and Ez \n %% distribution between electrodes\n Incident(T+1) = Source(t_half, 1.0, T*dt); \n Reflected(T+1) = Ez(nx/2-7, PML+2, PML+3) - Incident(T+1);\n Passed(T+1) = Ez(nx/2+7, ny-PML-1, PML+3);\n Ez_saved(1:(ny-2*PML-1), 1:(nx-2*PML-1), T+1) = ...\n Ez((PML+1):(nx-PML-1), (PML+1):(ny-PML-1), PML+3)';\n\n %% Calculate Bx -> Hx\n I = 2:nx; J = 1:ny; K = 1:nz;\n Bx_r = Bx(I,J,K);\n Bx(I,J,K) = k_Bx_a(I,J,K).*Bx(I,J,K) + k_Bx_b(I,J,K).*...\n ((Ey(I,J,K+1) - Ey(I,J,K))/dz - (Ez(I,J+1,K) - Ez(I,J,K))/dy);\n Hx(I,J,K) = k_Hx_a(I,J,K).*Hx(I,J,K) + k_Hx_b(I,J,K).*...\n (k_Hx_c(I,J,K).*Bx(I,J,K) + k_Hx_d(I,J,K).*Bx_r)./Kc(I,J,K);\n \n %% Calculate By -> Hy\n I = 1:nx; J = 2:ny; K = 1:nz;\n By_r = By(I,J,K);\n By(I,J,K) = k_By_a(I,J,K).*By(I,J,K) + k_By_b(I,J,K).*...\n ((Ez(I+1,J,K) - Ez(I,J,K))/dx - (Ex(I,J,K+1) - Ex(I,J,K))/dz);\n Hy(I,J,K) = k_Hy_a(I,J,K).*Hy(I,J,K) + k_Hy_b(I,J,K).*...\n (k_Hy_c(I,J,K).*By(I,J,K) + k_Hy_d(I,J,K).*By_r)./Kc(I,J,K);\n\n %% Calculate Bz -> Hz\n I = 1:nx; J = 1:ny; K = 2:nz;\n Bz_r = Bz(I,J,K);\n Bz(I,J,K) = k_Bz_a(I,J,K).*Bz(I,J,K) + k_Bz_b(I,J,K).*...\n ((Ex(I,J+1,K) - Ex(I,J,K))/dy - (Ey(I+1,J,K) - Ey(I,J,K))/dx);\n Hz(I,J,K) = k_Hz_a(I,J,K).*Hz(I,J,K) + k_Hz_b(I,J,K).*...\n (k_Hz_c(I,J,K).*Bz(I,J,K) + k_Hz_d(I,J,K).*Bz_r)./Kc(I,J,K);\n \n %% Progress bar updates at every time percent\n if ( mod(T, ceil(number_of_iterations/100)) == 0 )\n waitbar((T+1)/number_of_iterations, hhh);\n end\n \n end\n toc\n close(hhh);\n \n%% Plots: signals, scattering parameters and Ez field between plates\n figure('units','normalized','outerposition',[0 0 1 1]);\n set(gcf, 'doublebuffer', 'on'); \n % Input signal, reflected (at port 1) and passed through (port 2)\n subplot(2,2,1);\n plot(1e9*dt*(0:T), Incident, 'k-', 1e9*dt*(0:T), Reflected, 'r-', 1e9*dt*(0:T), Passed, 'b-', 'LineWidth', 2);\n title('Input, reflected (Port 1) and passed (Port 2) signals', 'FontSize', 18);\n xlabel('Time, [ns]', 'FontSize', 16);\n ylabel('Strength, [V/cm]', 'FontSize', 16);\n legend('Incident (Port 1)' ,'Reflected (Port 1)', 'Passed (Port 2)');\n grid on;\n % |S_11| and |S_21|\n NFFT = 2^nextpow2(T);\n S_11 = fft(Reflected, NFFT)./fft(Incident, NFFT);\n S_21 = fft(Passed, NFFT)./fft(Incident, NFFT);\n subplot(2,2,3);\n f = (0.5/dt)*linspace(0, 1, NFFT/2);\n plot(f*1e-9, 20*log10(abs(S_11(1:NFFT/2))), 'r', ...\n f*1e-9, 20*log10(abs(S_21(1:NFFT/2))), 'b', 'LineWidth', 2);\n title('Scattering parameters - |S_{11}| and |S_{21}|', 'FontSize', 18);\n xlabel('Frequency, [GHz]', 'FontSize', 16);\n ylabel('Magnitude, [dB]', 'FontSize', 16);\n legend('Reflected (Port 1)', 'Passed (Port 2)', 'Location', 'SouthEast');\n xlim([0 20]);\n grid on;\n % Electric field strength Ez between electrodes\n for T=1:20:number_of_iterations\n subplot(2,2,[2 4]);\n contour(1e3*dx*(1:(nx-2*PML-1)), 1e3*dy*(1:(ny-2*PML-1)), ...\n Index((PML+1):(nx-PML-1), (PML+1):(ny-PML-1), PML+5)', 1);\n hold on;\n subplot(2,2,[2 4]);\n pcolor(1e3*dx*(1:(nx-2*PML-1)), 1e3*dy*(1:(ny-2*PML-1)), double(Ez_saved(:, :, T)));\n title(['Time t = ', num2str(round(T*dt*1e12)),' ps'], 'FontSize', 18);\n xlabel('[mm]', 'FontSize', 16);\n ylabel('[mm]', 'FontSize', 16);\n shading interp;\n axis image;\n caxis([-1 1]);\n colorbar;\n drawnow;\n end\n\n%% Gauss function for voltage source\nfunction [res] = Source(t_half, amplitude, t)\n% Pulse delay\nt0 = 3.0*t_half;\nres = amplitude*exp(-0.5*((t-t0)/(t_half/2.35482))^2.0);\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/43337-microstrip-low-pass-filter-analysis-using-3d-fdtd-code-with-upml/FDTD_3D_Lowpass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.37650857226428514}} {"text": "function tapas_hgf_binary_mab_plotTraj(r)\n% Plots the estimated or generated trajectories for the binary HGF perceptual model for multi-armed\n% bandit situations.\n%\n% Usage example: est = tapas_fitModel(responses, inputs); tapas_hgf_binary_plotTraj(est);\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Optional plotting of standard deviations (true or false)\nplotsd = true;\n\n% Optional plotting of responses (true or false)\nploty = true;\n\n% Set up display\nscrsz = get(0,'screenSize');\nouterpos = [0.2*scrsz(3),0.2*scrsz(4),0.8*scrsz(3),0.8*scrsz(4)];\nfigure(...\n 'OuterPosition', outerpos,...\n 'Name', 'HGF trajectories');\n\n% Set up colors\ncolors = [1 0 0; 0.67 0 1; 0 0.67 1; 0.67 1 0];\n\n% Number of bandits\nb = r.c_prc.n_bandits;\n\n% Number of trials\nn = size(r.u,1);\n\n% Time axis\nif size(r.u,2) > 1\n t = r.u(:,end)';\nelse\n t = ones(1,n);\nend\n\nts = cumsum(t);\nts = [0, ts];\n\n% Number of levels\ntry\n l = r.c_prc.n_levels;\ncatch\n l = (length(r.p_prc.p)+1)/5;\nend\n\n% Upper levels\nfor j = 1:l-2\n\n % Subplots\n subplot(l,1,j);\n\n if plotsd == true\n upperprior = r.p_prc.mu_0(l-j+1) +sqrt(r.p_prc.sa_0(l-j+1));\n lowerprior = r.p_prc.mu_0(l-j+1) -sqrt(r.p_prc.sa_0(l-j+1));\n upper = [upperprior; r.traj.mu(:,l-j+1,1)+sqrt(r.traj.sa(:,l-j+1,1))];\n lower = [lowerprior; r.traj.mu(:,l-j+1,1)-sqrt(r.traj.sa(:,l-j+1,1))];\n \n plot(0, upperprior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'ob', 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\n plot(ts, [r.p_prc.mu_0(l-j+1); r.traj.mu(:,l-j+1,1)], 'b', 'LineWidth', 2);\n hold all;\n plot(0, r.p_prc.mu_0(l-j+1), 'ob', 'LineWidth', 2); % prior\n xlim([0 ts(end)]);\n title(['Posterior expectation of x_' num2str(l-j+1)], 'FontWeight', 'bold');\n ylabel(['\\mu_', num2str(l-j+1)]);\nend\n\n% Second level\nsubplot(l,1,l-1)\n\n\nif plotsd == true\n for j=1:b\n upperprior = r.p_prc.mu_0(2) +sqrt(r.p_prc.sa_0(2));\n lowerprior = r.p_prc.mu_0(2) -sqrt(r.p_prc.sa_0(2));\n upper = [upperprior; r.traj.mu(:,2,j)+sqrt(r.traj.sa(:,2,j))];\n lower = [lowerprior; r.traj.mu(:,2,j)-sqrt(r.traj.sa(:,2,j))];\n \n plot(0, upperprior, 'o', 'Color', colors(j,:), 'LineWidth', 1);\n hold all;\n plot(0, lowerprior, 'o', 'Color', colors(j,:), 'LineWidth', 1);\n fill([ts, fliplr(ts)], [(upper)', fliplr((lower)')], ...\n colors(j,:), 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\nend\nfor j=1:b\n plot(ts, [r.p_prc.mu_0(1); r.traj.mu(:,2,j)], 'Color', colors(j,:), 'LineWidth', 2);\n hold all;\n plot(0, r.p_prc.mu_0(1), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior\nend\nxlim([0 ts(end)]);\ntitle('Posterior expectations of x_2', 'FontWeight', 'bold');\nylabel('\\mu_2');\n\n% Input level\nsubplot(l,1,l);\n\nfor j=1:b\n plot(ts, [tapas_sgm(r.p_prc.mu_0(2), 1); tapas_sgm(r.traj.mu(:,2,j), 1)], 'Color', colors(j,:), 'LineWidth', 2);\n hold all;\n plot(0, tapas_sgm(r.p_prc.mu_0(2), 1), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior\nend\nplot(ts(2:end), r.u(:,1), '.', 'Color', [0 0 0]); % inputs\nplot(ts(2:end), r.traj.wt(:,1), 'k') % implied learning rate \nif (ploty == true) && ~isempty(find(strcmp(fieldnames(r),'y'))) && ~isempty(r.y)\n y = r.y(:,1);\n if ~isempty(find(strcmp(fieldnames(r),'irr')))\n y(r.irr) = NaN; % weed out irregular responses\n plot(ts(r.irr)+1, 1.08.*ones([1 length(r.irr)]), 'x', 'Color', [1 0.7 0], 'Markersize', 11, 'LineWidth', 2); % irregular responses\n end\n for j=1:b\n plot(find(y==j), 1.08*ones([1 length(find(y==j))]), '.', 'Color', colors(j,:)); % responses\n end\n title(['Response y, input u (black dots), learning rate (fine black line), and posterior expectation of reward s(\\mu_2) ', ...\n '(colour coded) for \\rho=', num2str(r.p_prc.rho(2:end)), ', \\kappa=', ...\n num2str(r.p_prc.ka(2:end)), ', \\omega=', num2str(r.p_prc.om(2:end))], ...\n 'FontWeight', 'bold');\n ylabel('y, u, s(\\mu_2)');\n axis([0 ts(end) -0.15 1.15]);\nelse\n title(['Input u (black dots), learning rate (fine black line), and posterior expectation of input s(\\mu_2) ', ...\n '(red) for \\rho=', num2str(r.p_prc.rho(2:end)), ', \\kappa=', ...\n num2str(r.p_prc.ka(2:end)), ', \\omega=', num2str(r.p_prc.om(2:end))], ...\n 'FontWeight', 'bold');\n ylabel('u, s(\\mu_2)');\n axis([0 ts(end) -0.1 1.1]);\nend\nplot(ts(2:end), 0.5, 'k');\nxlabel('Trial number');\nhold off;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_binary_mab_plotTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.37615442490866435}} {"text": "function options = spset(varargin)\n% SPSET Create/alter sparse interpolation OPTIONS structure\n% OPTIONS = SPSET('NAME1',VALUE1,'NAME2',VALUE2,...) creates an\n% options structure OPTIONS in which the named properties have\n% the specified values. Any unspecified properties have default\n% values. It is sufficient to type only the leading characters\n% that uniquely identify the property. Case is ignored for\n% property names. \n% \n% OPTIONS = SPSET(OLDOPTS,'NAME1',VALUE1,...) alters an existing\n% options structure OLDOPTS.\n% \n% OPTIONS = SPSET(OLDOPTS,NEWOPTS) combines an existing options\n% structure OLDOPTS with a new options structure NEWOPTS. Any new\n% properties overwrite corresponding old properties. \n% \n% SPSET with no input arguments displays all property names and\n% their possible values. \n% \n% See also SPGET, SPINTERP, SPVALS.\n%\n%\n% SPSET PROPERTIES\n%\n% GridType - Sparse grid type and basis functions to use \n% [ {Clenshaw-Curtis} | Maximum | NoBoundary | Chebyshev |\n% Gauss-Patterson ]. For an illustration of the grid types, \n% run CMPGRIDS.\n%\n% RelTol - Relative error tolerance [ positive scalar {1e-2} ]\n% A relative error tolerance that applies to all hierarchical\n% surpluses of the sparse grid representation. The grid is\n% further refined until all hierarchical surpluses are less than\n% max(RelTol*(max(fevalRange)-min(fevalRange)),AbsTol), with\n% fevalRange containing all results evaluating FUN up to\n% that point. \n% \n% AbsTol - Absolute error tolerance [ positive scalar {1e-6} ]\n% Used by the error control stated under RelTol.\n%\n% Vectorized - Vectorized function FUN [ on | {off} ]\n% Indicates if FUN is available for vectorized evaluation. \n% Vectorized coding of FUN can significantly reduce the\n% computation time used by SPVALS. For an example using a\n% vectorized function, please see SPDEMO.\n%\n% MinDepth - Minimum interpolation depth [ integer {2} ]\n% Minimum number of hierarchical interpolation levels n to\n% compute. \n%\n% MaxDepth - Maximum interpolation depth [ integer {8} ]\n% Maximum number of hierarchical interpolation levels n to\n% compute. The maximum supported depth (and the default) is 6\n% for the Gauss-Patterson grid.\n%\n% VariablePositions - Position of the ranges to interpolate in the\n% argument list when FUN is evaluated. [ 1xD vector {[]} ] \n% By setting VariablePositions, SPVALS will evaluate FUN with respect\n% to some of its input parameters, but not necessarily the first\n% D ones. With VARPOS, the actual position of each variable may\n% be set. VARPOS must be a 1xD array.\n% \n% NumberOfOutputs - Number of outputs [ integer {1} ]\n% If FUN produces multiple outputs (all must be scalar), indicate\n% this here to perform the sparse grid computation for many\n% output variables at once. Also see the example SPDEMOVAROUT.\n%\n% PrevResults - Previous sparse grid representation [ struct {[]} ]\n% An existing result structure obtained from SPVALS may be\n% provided to further refine an existing sparse grid.\n%\n% FunctionArgType - Function argument type [ {list} | vector ]\n% Indicates whether the objective function takes the input\n% parameters as a comma-separated list (default) or as a vector.\n%\n% KeepFunctionValues - Keep the function evaluations [ {off} | on ]\n% If this parameter is set, a structure field 'fvals' is\n% returned, containing a cell array with the function values at\n% the sparse grid points.\n%\n% KeepGrid - Keep the sparse grid points [ {off} | on ]\n% If this parameter is set, a structure field 'grid' is\n% returned, containing a cell array with the the sparse grid\n% points. \n%\n% DimensionAdaptive - Set dimension adaptivity option [ {off} | on ]\n% Dimension-adaptive grids try to adaptively find important\n% dimensions and adjust the sparse grid structure\n% accordingly. The implementation of dimension-adaptive sparse\n% grids follows the approach by Gerstner/Griebel.\n%\n% MinPoints - Minimum number of support nodes [ integer {100} ]\n% This parameter only applies to dimension-adaptive sparse grids,\n% and indicates the minimum number of support nodes\n% (i.e. function evaluations to perform).\n%\n% MaxPoints - Maximum number of support nodes [ integer {10000} ]\n% This parameter only applies to dimension-adaptive sparse grids.\n% The dimension-adaptive algorithm is aborted once the function\n% evaluation count exceeds this number.\n%\n% DimadaptDegree - Fine-tuning parameter to alter the degree of\n% dimension-adaptivity [ positive scalar {0.9} ]. A value of 1\n% places complete emphasis on the error estimates, and thus leads\n% to \"greedy\" dimension-adaptivity. A value of 0 disregards the\n% error estimates, and constructs a conventional sparse grid\n% based on the amount of work involved. \n%\n% DegreeStrategy - [ {balancing} | depth ] Strategy for the degree\n% of dimensional adaptivity. \n% The 'balancing' strategy balances the number of grid points \n% generated according to the greedy, error estimate-based refine-\n% ment rule compared to the number of points generated by the \n% conventional (regular) sparse grid refinement rule. I.e., a \n% DimadaptDegree value of 0.9 would mean that around 90% of the \n% grid points are generated by the error estimate-based rule, and\n% the remaining points are selected according to the regular \n% rule.\n% The 'depth' strategy makes sure that the maximum level depth\n% reached by the error estimate-based refinement in one dimension\n% does not get too deep compared to the depth reached in the other\n% dimensions. This measurement degree strategy is the one used \n% prior to version 5.1.0 of the toolbox, and is described on page\n% 61 of A. Klimke, \"Uncertainty modeling using fuzzy arithmetic \n% and sparse grids\". This approach is still supported but no \n% the default strategy.\n%\n% SparseIndices - [ {auto} | on | off ] Manually turn the efficient\n% sparse storage scheme (new feature since version 3.0) of the \n% multi-index arrays on or off. The default switch auto uses the\n% new scheme for the ClenshawCurtis and the Chebyshev grid, and \n% the old (full) storage scheme from version 2.x for the Maximum \n% and the NoBoundary grid (the sparse grid storage scheme is not\n% supported for these two grid types).\n%\n% DropTol - Drop tolerance [ {auto} | off | 1x2 double vector ]\n% During the sparse grid construction progress, the spvals \n% algorithm may add subgrids with hierarchical surpluses that are \n% all close to zero or of negligible magnitude compared to the \n% surpluses of other sub-grids. In particular, this occurs when\n% additive structure is present in the objective function. \n% To increase the performance of the spinterp algorithm, \n% subgrids where all (absolute) hierarchical surpluses are less \n% than max(relDropTol*(max(fevalRange)-min(fevalRange),absDropTol))\n% can be omitted from the interpolation process by running the\n% sppurge algoritm (see help sppurge).\n% You may specify the absolute and the relative drop tolerance \n% as a vector [ absDropTol, relDropTol ], or turn it off completely\n% (= behavior of version 3.0 and earlier). The switch 'auto' uses \n% the values absDropTol = 0, relDropTol = 100*eps, that is, by \n% default, only a relative drop tolerance is used.\n%\n% EnableDCT - [ {on} | off ] Use the DCT when constructing the\n% Chebyshev-Gauss-Lobatto type sparse grid. \n\n% Author : Andreas Klimke, Universitaet Stuttgart\n% Version: 1.9\n% Date : November 18, 2007\n\t\n% Change log:\n% V1.0 : Sep 23, 2003\n% Initial release\n% V1.1 : Dec 23, 2003\n% Added FunctionArgType handling for more flexibility in\n% defining the objective function.\n% V1.2 : Jan 07, 2004\n% Added KeepFunctionValues property to allow the user to\n% access the function values at the sparse grid points.\n% V1.3 : Jan 08, 2004\n% Added KeepGrid property to allow the user to access the\n% sparse grid points.\n% V1.4 : Apr 22, 2004\n% Added options for dimension-adaptive sparse grids.\n% V1.5 : Feb 22, 2005\n% Added handling of sparse sets of indices (useful for\n% high-dimensional interpolation)\n% V1.6 : January 13, 2006\n% Added documentation of SparseIndices property\n% V1.7 : February 2, 2006\n% Added DropTol property\n% V1.8 : March 1, 2006\n% Added DCT feature\n% V1.9 : November 18, 2007\n% Added new grid type : Gauss-Patterson\n% V2.0 : January 20, 2007\n% Added new parameter for dimensional adaptivity degree\n% strategy.\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\n% Note: SPSET is similar in syntax and code the the options\n% handling with ODEGET and ODESET of the MATLAB ODE suite by Marc\n% Reichelt and Lawrence Shampine.\n\n% Print out possible values of properties.\nif (nargin == 0) && (nargout == 0)\n fprintf([' GridType: [ {Clenshaw-Curtis} | Maximum |' ...\n\t\t\t\t\t ' NoBoundary | Chebyshev | Gauss-Patterson ]\\n']);\n fprintf(' RelTol: [ positive scalar {1e-2} ]\\n');\n fprintf(' AbsTol: [ positive scalar {1e-6} ]\\n');\n fprintf(' Vectorized: [ {off} | on ]\\n');\n\tfprintf(' MinDepth: [ positive integer {2} ]\\n');\n\tfprintf(' MaxDepth: [ positive integer {8} ] (6 for Gauss-Patt.)\\n');\n fprintf(' VariablePositions: [ double matrix {[]} ]\\n');\n fprintf(' NumberOfOutputs: [ positive integer {1} ]\\n');\n fprintf(' PrevResults: [ struct {[]} ]\\n');\n\tfprintf(' FunctionArgType: [ {list} | vector ]\\n');\n\tfprintf('KeepFunctionValues: [ {off} | on ]\\n');\n\tfprintf(' KeepGrid: [ {off} | on ]\\n');\n\tfprintf(' DimensionAdaptive: [ {off} | on ]\\n');\n\tfprintf(' MinPoints: [ positive integer {100} ]\\n');\n\tfprintf(' MaxPoints: [ positive integer {10000} ]\\n');\n\tfprintf(' DimadaptDegree: [ positive scalar in [0,1] {0.9} ]\\n');\n\tfprintf(' DegreeStrategy: [ {balancing} | depth ]\\n');\n\tfprintf(' SparseIndices: [ {auto} | on | off ]\\n');\n\tfprintf([' DropTol: [ {auto} | off |' ...\n\t\t\t\t\t ' [absTol, relTol] (pos. scalars)]\\n']);\n\tfprintf(' EnableDCT: [ {on} | off ]\\n');\n fprintf('\\n');\n return;\nend\n\nNames = {'GridType', 'RelTol', 'AbsTol', 'Vectorized', 'MinDepth', ...\n\t\t\t\t 'MaxDepth', 'VariablePositions', 'NumberOfOutputs', ...\n\t\t\t\t 'PrevResults', 'FunctionArgType', 'KeepFunctionValues', ...\n\t\t\t\t 'KeepGrid', 'DimensionAdaptive', 'MinPoints', ...\n\t\t\t\t 'MaxPoints', 'DimadaptDegree', 'DegreeStrategy', ...\n\t\t\t\t 'SparseIndices', 'DropTol', 'EnableDCT'};\n\n\nm = length(Names);\nnames = cell(m,1);\nfor k = 1:m\n\tnames{k} = lower(Names{k});\nend\n\n% Combine all leading options structures o1, o2, ... in odeset(o1,o2,...).\noptions = [];\nfor k = 1:m\n options.(Names{k}) = [];\nend\n\nk = 1;\nwhile k <= nargin\n arg = varargin{k};\n if ischar(arg) % arg is an option name\n break;\n end\n if ~isempty(arg) % [] is a valid options argument\n if ~isa(arg,'struct')\n msg = sprintf(['Expected argument %d to be a string property' ...\n\t\t\t\t\t\t\t\t\t\t ' name or an options structure\\ncreated with' ...\n\t\t\t\t\t\t\t\t\t\t ' SPSET.'], k);\n error(msg); \n end\n for l = 1:m\n if any(strcmp(fieldnames(arg),Names{l}))\n val = arg.(Names{l});\n else\n val = [];\n end\n if ~isempty(val)\n options.(Names{l}) = val;\n end\n end\n\t\tk = k + 1;\n else\n\t\tk = k + 1;\n\t\tbreak;\n\tend\nend\n\n% now process the name-value pairs.\nif rem(nargin-k+1,2) ~= 0\n error('Arguments must occur in name-value pairs.');\nend\n\nexpectval = 0; % start expecting a name, not a\n % value\nwhile k <= nargin\n arg = varargin{k};\n \n if ~expectval\n if ~ischar(arg)\n msg = sprintf(['Expected argument %d to be a string property' ...\n\t\t\t\t\t\t\t\t\t\t ' name.'], k);\n error(msg); \n end\n lowArg = lower(arg);\n matched = strmatch(lowArg,names);\n if isempty(matched)\n msg = sprintf('Unrecognized property name ''%s''.', arg);\n error(msg);\n elseif length(matched) > 1\n msg = sprintf('Ambiguous property name ''%s'' ', arg);\n msg = [msg '(' Names{matched(1)}];\n for l = matched(2:length(matched))'\n msg = [msg ', ' Names{l}];\n end\n msg = sprintf('%s).', msg);\n error(msg);\n end\n expectval = 1; % we expect a value next\n \n else\n options.(Names{matched}) = arg;\n expectval = 0;\n \n end\n k = k + 1;\nend\n\nif expectval\n msg = sprintf('Expected value for property ''%s''.', arg);\n error(msg);\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/spinterp/spset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3759230141871729}} {"text": "function boundary = p11_boundary_nearest ( m, n, point )\n\n%*****************************************************************************80\n%\n%% P11_BOUNDARY_NEAREST returns a nearest boundary point in problem 11.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real POINT(M,N), the coordinates of the points.\n%\n% Output, real BOUNDARY(M,N), points on the boundary\n% that are nearest to each point.\n%\n q1 = [ ...\n 0.00, 0.00; ...\n 1.00, 0.00; ...\n 0.75, 0.25; ...\n 0.25, 0.25 ]';\n q2 = [ ...\n 0.00, 0.00; ...\n 0.25, 0.25; ...\n 0.25, 0.75; ...\n 0.00, 1.00 ]';\n q3 = [ ...\n 0.50, 0.50; ...\n 0.50, 0.25; ...\n 0.75, 0.25; ...\n 1.00, 0.50 ]';\n q4 = [ ...\n 0.50, 0.50; ...\n 0.25, 0.50; ...\n 0.25, 0.25; ...\n 0.50, 0.25 ]';\n q5 = [ ...\n 0.50, 0.50; ...\n 0.50, 1.00; ...\n 0.25, 0.75; ...\n 0.25, 0.50 ]';\n t1 = [ ...\n 1.00, 0.00; ...\n 1.00, 0.50; ...\n 0.75, 0.25 ]';\n t2 = [ ...\n 0.00, 1.00; ...\n 0.25, 0.25; ...\n 0.50, 1.00 ]';\n t3 = [ ...\n 0.50, 0.50; ...\n 1.00, 0.50; ...\n 1.00, 1.00 ]';\n t4 = [ ...\n 0.50, 0.50; ...\n 1.00, 1.00; ...\n 0.50, 1.00 ]';\n\n x1 = 0.0;\n x2 = 0.5;\n x3 = +1.0;\n y1 = 0.0;\n y2 = 0.5;\n y3 = +1.0;\n\n for j = 1 : n\n\n if ( point(1,j) <= x1 & point(2,j) <= y1 )\n\n boundary(1,j) = x1;\n boundary(2,j) = y1;\n\n elseif ( point(1,j) <= x1 & point(2,j) <= y3 )\n\n boundary(1,j) = x1;\n boundary(2,j) = point(2,j);\n\n elseif ( point(1,j) <= x1 & y3 <= point(2,j) )\n\n boundary(1,j) = x1;\n boundary(2,j) = y3;\n\n elseif ( point(1,j) <= x3 & point(2,j) <= y1 )\n\n boundary(1,j) = point(1,j);\n boundary(2,j) = y1;\n\n elseif ( quad_contains_point_2d ( q1, point(1:2,j) ) )\n\n boundary(1,j) = point(1,j);\n boundary(2,j) = y1;\n\n elseif ( quad_contains_point_2d ( q2, point(1:2,j) ) )\n\n boundary(1,j) = x1;\n boundary(2,j) = point(2,j);\n\n elseif ( triangle_contains_point_2d ( t1, point(1:2,j) ) )\n\n boundary(1,j) = x3;\n boundary(2,j) = point(2,j);\n\n elseif ( quad_contains_point_2d ( q3, point(1:2,j) ) )\n\n boundary(1,j) = point(1,j);\n boundary(2,j) = y2;\n\n elseif ( quad_contains_point_2d ( q4, point(1:2,j) ) )\n\n boundary(1,j) = x2;\n boundary(2,j) = y2;\n\n elseif ( quad_contains_point_2d ( q5, point(1:2,j) ) )\n\n boundary(1,j) = x2;\n boundary(2,j) = point(2,j);\n\n elseif ( triangle_contains_point_2d ( t2, point(1:2,j) ) )\n\n boundary(1,j) = point(1,j);\n boundary(2,j) = y3;\n\n elseif ( x1 <= point(1,j) & point(1,j) <= x2 & y3 <= point(2,j) )\n\n boundary(1,j) = point(1,j);\n boundary(2,j) = y3;\n\n elseif ( triangle_contains_point_2d ( t3, point(1:2,j) ) )\n\n boundary(1,j) = point(1,j);\n boundary(2,j) = y2;\n\n elseif ( triangle_contains_point_2d ( t4, point(1:2,j) ) )\n\n boundary(1,j) = x2;\n boundary(2,j) = point(2,j);\n\n elseif ( x2 <= point(1,j) & point(1,j) <= x3 & y3 <= point(2,j) )\n\n boundary(1,j) = x2;\n boundary(2,j) = y3;\n\n elseif ( x3 <= point(1,j) & point(2,j) <= y1 )\n\n boundary(1,j) = x3;\n boundary(2,j) = y1;\n\n elseif ( x3 <= point(1,j) & y1 <= point(2,j) & point(2,j) <= y2 )\n\n boundary(1,j) = x3;\n boundary(2,j) = point(2,j);\n\n elseif ( x3 <= point(1,j) & y2 <= point(2,j) & point(2,j) <= y3 )\n\n boundary(1,j) = x3;\n boundary(2,j) = y2;\n\n elseif ( x3 <= point(1,j) & y3 <= point(2,j) & point(2,j) <= point(1,j) )\n\n boundary(1,j) = x3;\n boundary(2,j) = y2;\n\n elseif ( x3 <= point(1,j) & y3 <= point(2,j) & point(1,j) <= point(2,j) )\n\n boundary(1,j) = x2;\n boundary(2,j) = y3;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P11_BOUNDARY_NEAREST - Fatal error!\\n' );\n fprintf ( 1, ' Orphan point = ( %f, %f )\\n', point(1:2,j) );\n error ( 'P11_BOUNDARY_NEAREST - Fatal error!' );\n\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/test_triangulation/p11_boundary_nearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3756611517523899}} {"text": "function [high_fissure_indices, ref_image] = PTKGetMaxFissurePoints(fissure_approximation, lung_mask, fissureness, image_roi, image_size)\n % PTKGetMaxFissurePoints. function for finding candidate points of high\n % fissureness given an initial fissure approximation.\n %\n % PTKGetMaxFissurePoints is an intermediate stage in segmenting the\n % lobes. It is not intended to be a general-purpose algorithm. \n %\n % For more information, see \n % [Doel et al., Pulmonary lobe segmentation from CT images using\n % fissureness, airways, vessels and multilevel B-splines, 2012]\n %\n % Licence\n % -------\n % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n % Author: Tom Doel, 2012. www.tomdoel.com\n % Distributed under the GNU GPL v3 licence. Please see website for details.\n %\n\n data_points_indices = find(fissure_approximation);\n \n bin_size = 2;\n\n [high_fissure_indices, ref_image] = GetFissurePoints(data_points_indices, image_size, lung_mask, fissureness, image_roi, bin_size);\nend\n\n\nfunction [maximum_fissureness_indices, ref_image] = GetFissurePoints(indices_for_model, image_size, lung_segmentation, fissureness, image_roi, bin_size)\n\n % Get the coordinates of every voxel in the lung segmentation\n candidate_indices = find(lung_segmentation.RawImage);\n \n % An image for debugging\n ref_image = zeros(image_size, 'uint8');\n ref_image(candidate_indices) = 2;\n\n % Remove points with low fissureness\n max_fissureness = max(fissureness.RawImage(candidate_indices));\n fissureness_threshold = max_fissureness/3;\n intensity_threshold_hu = -900;\n intensity_threshold = image_roi.HounsfieldToGreyscale(intensity_threshold_hu);\n candidate_indices = candidate_indices((fissureness.RawImage(candidate_indices) > fissureness_threshold) & (image_roi.RawImage(candidate_indices) > intensity_threshold));\n ref_image(candidate_indices) = 4;\n\n if isempty(candidate_indices)\n maximum_fissureness_indices = [];\n return;\n end\n \n % Find a rotation matrix\n [eigv, m] = GetRotationMatrix(indices_for_model, image_size);\n \n [x_all, y_all, z_all] = MimImageCoordinateUtilities.FastInd2sub(image_size, candidate_indices);\n X_all = [x_all(:), y_all(:), z_all(:)]';\n \n % Transform to new basis\n em_all = X_all - m(:, ones(1, size(X_all, 2)));\n em_all = eigv*em_all;\n \n % We allocate each point to a bin according to the x-y coordinates in the\n % transformed domain\n x1_all = em_all(1, :);\n y1_all = em_all(2, :);\n\n % Get the coordinates of each of the model points\n [x_model, y_model, z_model] = MimImageCoordinateUtilities.FastInd2sub(image_size, indices_for_model); \n X_model = [x_model(:), y_model(:), z_model(:)]';\n \n % Transform to new basis\n em_model = X_model - m(:, ones(1, size(X_model, 2)));\n em_model = eigv*em_model;\n \n % We allocate each point to a bin according to the x-y coordinates in the\n % transformed domain\n x1_model = em_model(1, :);\n y1_model = em_model(2, :);\n \n % Project the candidate points onto the fissure plane, and remove those that\n % are not within the convex hull formed by the model points on the plane. In\n % effect, we are using the model coordinates (the initial guess) as a bound\n % for the x-y coordinates used to construct the fissure surface.\n xy_coords_model = [x1_model', y1_model'];\n dt = DelaunayTri(xy_coords_model);\n simplex_index = pointLocation(dt, x1_all', y1_all');\n is_valid = ~isnan(simplex_index);\n candidate_indices_ok = candidate_indices(is_valid);\n \n if isempty(candidate_indices_ok)\n maximum_fissureness_indices = [];\n return;\n end\n \n % Turn into x,y,z vectors\n [x_all, y_all, z_all] = MimImageCoordinateUtilities.FastInd2sub(image_size, candidate_indices_ok);\n X_all = [x_all(:), y_all(:), z_all(:)]'; \n\n % Transform to new basis\n em_all = X_all - m(:, ones(1, size(X_all, 2)));\n em_all = eigv*em_all;\n \n % We allocate each point to a bin according to the x-y coordinates in the\n % transformed domain\n x1_all = em_all(1, :);\n y1_all = em_all(2, :); \n \n [maximum_fissureness_indices, all_maxima] = SortIntoBins(x1_all, y1_all, candidate_indices_ok, fissureness, bin_size, image_size);\n \n ref_image(all_maxima) = 6;\n ref_image(maximum_fissureness_indices) = 3;\n\n % Remove non-connected points (outliers)\n [x_all, y_all, z_all] = MimImageCoordinateUtilities.FastInd2sub(image_size, maximum_fissureness_indices);\n points_coords = ArraysToPoints(x_all(:), y_all(:), z_all(:));\n \n min_dilate_size_mm = 2.5;\n max_dilate_size_mm = 2.5;\n \n dilate_size_mm = min_dilate_size_mm;\n \n calculate_again = true;\n target_number_of_points = round(numel(x_all)/2);\n \n % Perform the removal of connected points with a variable dilation size\n while calculate_again\n points_coords_new = RemoveNonConnectedPoints(points_coords, lung_segmentation, image_size, dilate_size_mm);\n number_of_found_points = numel(points_coords_new);\n if (number_of_found_points >= target_number_of_points) || (dilate_size_mm > max_dilate_size_mm)\n calculate_again = false;\n else\n dilate_size_mm = dilate_size_mm + 0.5;\n end\n \n end\n \n [x_all, y_all, z_all] = PointsToArrays(points_coords_new);\n maximum_fissureness_indices = MimImageCoordinateUtilities.FastSub2ind(image_size, x_all(:), y_all(:), z_all(:));\n ref_image(maximum_fissureness_indices) = 1;\n \nend\n\n\nfunction [rot_matrix, m] = GetRotationMatrix(indices, image_size)\n [x, y, z] = ind2sub(image_size, indices);\n X = [x, y, z]';\n\n % Find a suitable basis for these points using PCA\n m = mean(X, 2);\n em = X - m(:, ones(1, size(X, 2)));\n eigv = pts_pca(em);\n \n rot_matrix = eigv';\nend\n\n\nfunction [maximum_fissureness_indices, all_maxima] = SortIntoBins(x1, y1, candidate_indices, fissureness, bin_size, image_size)\n binx = floor(x1/bin_size);\n binx = binx - min(binx);\n biny = floor(y1/bin_size);\n biny = biny - min(biny);\n \n % bin is an array containing the bin to which each element of indices has been allocated\n bin = binx + (max(binx)+1)*biny;\n \n % Now sort the indices and bins by fissureness\n fissureness_at_indices = fissureness.RawImage(candidate_indices);\n \n is_maxima = GetMaxima(candidate_indices, bin, fissureness_at_indices, fissureness, image_size);\n all_maxima = candidate_indices(is_maxima);\n bin = bin(is_maxima);\n candidate_indices = candidate_indices(is_maxima);\n\n fissureness_at_indices = fissureness.RawImage(candidate_indices);\n \n [~, sorted_indices] = sort(fissureness_at_indices, 'descend');\n indices_sorted_by_fissureness = candidate_indices(sorted_indices);\n bins_sorted_by_fissureness = bin(sorted_indices);\n\n % Use unique to obtain the first indices corresponding to each bin - this\n % will be the point with the largest fissureness\n maximum_fissureness_indices = [];\n for selection_index = 1 : 1\n [~, bin_indices, ~] = unique(bins_sorted_by_fissureness, 'first');\n maximum_fissureness_indices = [maximum_fissureness_indices; indices_sorted_by_fissureness(bin_indices)];\n \n bins_sorted_by_fissureness(bin_indices) = [];\n indices_sorted_by_fissureness(bin_indices) = [];\n end\n \n maximum_fissureness_indices = maximum_fissureness_indices(fissureness.RawImage(maximum_fissureness_indices) > 0);\n\nend\n\nfunction is_maxima = GetMaxima(candidate_indices, bin, fissureness_at_indices, fissureness, image_size)\n bin_allocation = zeros(image_size, 'int32');\n bin_allocation(candidate_indices) = bin;\n \n [linear_offsets, ~] = MimImageCoordinateUtilities.GetLinearOffsets(image_size);\n neighbours = repmat(int32(candidate_indices), 1, 6) + repmat(int32(linear_offsets), length(candidate_indices), 1);\n fissureness_neighbours = fissureness.RawImage(neighbours);\n bins_neighbours = bin_allocation(neighbours);\n bins_match = bins_neighbours == repmat(bin', 1, 6);\n fissureness_centre = repmat(fissureness_at_indices, 1, 6);\n \n % Force neighbouring points in different bins to have a lower fissureness\n fissureness_neighbours(~bins_match) = fissureness_centre(~bins_match) - 1;\n fissureness_less = fissureness_neighbours < fissureness_centre;\n sums = sum(fissureness_less, 2);\n is_maxima = sums == 6;\nend\n\n\nfunction points_coords = RemoveNonConnectedPoints(points_coords, template_image, image_size, dilate_size_mm)\n voxel_volume = prod(template_image.VoxelSize);\n min_component_size_mm3 = 300;\n min_component_size_voxels = round(min_component_size_mm3/voxel_volume);\n\n \n image_mask = false(image_size);\n indices = sub2ind(image_size, points_coords(:,1), points_coords(:,2), points_coords(:,3));\n image_mask(indices) = true;\n \n tci = template_image.BlankCopy;\n tci.ChangeRawImage(image_mask);\n tci.BinaryMorph(@imdilate, dilate_size_mm);\n connected_image = tci.RawImage;\n \n connected_components = bwconncomp(connected_image, 26);\n num_components = connected_components.NumObjects;\n for component = 1 : num_components\n pixels = connected_components.PixelIdxList{component};\n if length(pixels) < min_component_size_voxels\n connected_image(pixels) = false;\n end\n end\n image_mask = image_mask & connected_image;\n indices = find(image_mask(:));\n [i2_coords, j2_coords, k2_coords] = ind2sub(image_size, indices);\n points_coords = ArraysToPoints(i2_coords, j2_coords, k2_coords);\nend\n\n\nfunction points = ArraysToPoints(i, j, k)\n points = [i(:), j(:), k(:), ones(size(i(:)))];\nend\n\n\nfunction [is, js, ks] = PointsToArrays(points)\n is = points(:, 1);\n js = points(:, 2);\n ks = points(:, 3);\nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Lobes/PTKGetMaxFissurePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3756611517523898}} {"text": "function [nodes, edges, faces] = gcontour3d(img)\n%GCONTOUR3D Create contour graph of a 3D binary image.\n%\n%\n%\n% ---------\n%\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 28/06/2004.\n%\n\nnodes = zeros([0 3]); % 3 coordinates vertices\nedges = zeros([0 2]); % first node and second nodes\nfaces = zeros([0 4]); % indices of 4 corners of each square face\n\nD1 = size(img, 1);\nD2 = size(img, 2);\nD3 = size(img, 3);\n\n% first direction for image\nfor y = 1:D2 \n for z = 1:D3\n % find transitions between the two phases\n ind = find(img(1:D1-1, y, z)~=img(2:D1, y, z));\n \n % process each transition in direction 1\n for i2 = 1:length(ind)\n \n % coordinates of each node\n n1 = [ind(i2)+.5 y-.5 z-.5];\n n2 = [ind(i2)+.5 y-.5 z+.5];\n n3 = [ind(i2)+.5 y+.5 z+.5];\n n4 = [ind(i2)+.5 y+.5 z-.5];\n \n % add the face (and edges) with the 4 given nodes\n [nodes, edges, faces] = addFace(nodes, edges, faces, [n1; n2; n3; n4]);\n end \n end\nend\n\n% second direction for image\nfor x=1:D1 \n for z=1:D3\n % find transitions between the two phases\n ind = find(img(x, 1:D2-1, z)~=img(x, 2:D2, z));\n \n % process each transition in direction 1\n for i2 = 1:length(ind)\n \n % coordinates of each node\n n1 = [x-.5 ind(i2)+.5 z-.5];\n n2 = [x-.5 ind(i2)+.5 z+.5];\n n3 = [x+.5 ind(i2)+.5 z+.5];\n n4 = [x+.5 ind(i2)+.5 z-.5]; \n \n % add the face (and edges) with the 4 given nodes\n [nodes, edges, faces] = addFace(nodes, edges, faces, [n1; n2; n3; n4]);\n end \n end\nend\n\n% third direction for image\nfor x=1:D1 \n for y=1:D2\n % find transitions between the two phases\n ind = find(img(x, y, 1:D3-1)~=img(x, y, 2:D3));\n \n % process each transition in direction 1\n for i2 = 1:length(ind)\n \n % coordinates of each node\n n1 = [x-.5 y-.5 ind(i2)+.5];\n n2 = [x-.5 y+.5 ind(i2)+.5];\n n3 = [x+.5 y+.5 ind(i2)+.5];\n n4 = [x+.5 y-.5 ind(i2)+.5];\n \n % add the face (and edges) with the 4 given nodes\n [nodes, edges, faces] = addFace(nodes, edges, faces, [n1; n2; n3; n4]);\n end \n end\nend\n\n\n\nreturn;\n\n\n\nfunction [nodes, edges, faces] = addFace(nodes, edges, faces, faceNodes)\n% add given nodes and coresponding face to the graph.\n\n\nn1 = faceNodes(1,:);\nn2 = faceNodes(2,:);\nn3 = faceNodes(3,:);\nn4 = faceNodes(4,:);\n\n% search indices of each nodes\nind1 = find(ismember(nodes, n1, 'rows')); \nind2 = find(ismember(nodes, n2, 'rows'));\nind3 = find(ismember(nodes, n3, 'rows')); \nind4 = find(ismember(nodes, n4, 'rows'));\n\n% if nodes are not in the list, we add them\nif isempty(ind1)\n nodes = [nodes; n1];\n ind1 = size(nodes, 1);\nend\nif isempty(ind2)\n nodes = [nodes; n2];\n ind2 = size(nodes, 1);\nend\nif isempty(ind3)\n nodes = [nodes; n3];\n ind3 = size(nodes, 1);\nend\nif isempty(ind4)\n nodes = [nodes; n4];\n ind4 = size(nodes, 1);\nend\n\n% add current face to the list\nfaces(size(faces, 1)+1, 1:4) = [ind1(1) ind2(1) ind3(1) ind4(1)];\n\n% create edges of the face \n% (first index is the smallest one, by convention)\ne1 = [min(ind1, ind2) max(ind1, ind2)];\ne2 = [min(ind2, ind3) max(ind2, ind3)];\ne3 = [min(ind3, ind4) max(ind3, ind4)];\ne4 = [min(ind4, ind1) max(ind4, ind1)];\n\n % if nodes are not in the list, we add them\nif isempty(find(ismember(edges, e1, 'rows'), 1))\n edges = [edges; e1];\nend\nif isempty(find(ismember(edges, e2, 'rows'), 1))\n edges = [edges; e2];\nend\nif isempty(find(ismember(edges, e3, 'rows'), 1))\n edges = [edges; e3];\nend\nif isempty(find(ismember(edges, e4, 'rows'), 1))\n edges = [edges; e4];\nend\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/graphs/gcontour3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3754011155526398}} {"text": "function [y, x] = max(f, flag, dim)\n%MAX Maximum value of a CHEBFUN.\n% MAX(F) and MAX(F, 'global') return the maximum value of the CHEBFUN F.\n%\n% [Y, X] = MAX(F) returns also a point X such that F(X) = Y.\n%\n% [Y, X] = MAX(F, 'local') returns not just the global maximum value but all\n% of the local maxima.\n%\n% If F is complex-valued, absolute values are taken to determine the maxima,\n% but the resulting values correspond to those of the original function.\n%\n% If F is array-valued, then the columns of X and Y correspond to the columns\n% of F. NaNs are used to pad Y and X when the 'local' flag is used and the\n% columns are not of the same length.\n%\n% H = MAX(F, G), where F and G are CHEBFUNs defined on the same domain,\n% returns a CHEBFUN H such that H(x) = max(F(x), G(x)) for all x in the\n% domain of F and G. Alternatively, either F or G may be a scalar.\n%\n% MAX(F, [], DIM) computes the maximum of the CHEBFUN F in the dimension DIM.\n% If DIM = 1 and F is a column CHEBFUN or DIM = 2 and F is a row CHEBFUN, this\n% is equivalent to MAX(F). Otherwise, MAX(F, [], DIM) returns a CHEBFUN which\n% is the maximum across the discrete dimension of F. For example, if F is a\n% quasimatrix with two columns, MAX(F, [], 2) = MAX(F(:,1), F(:,2)).\n%\n% See also MIN, MINANDMAX, ROOTS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Trivial empty case.\nif ( isempty(f) )\n x = [];\n y = [];\n return\nend\n\nif ( nargin == 3 )\n if ( ~any(dim == [1 2]) )\n error('CHEBFUN:CHEBFUN:max:badDim', ...\n 'DIM input to CHEBFUN MAX must be 1 or 2.');\n end\n\n if ( dim ~= 1 + f(1).isTransposed )\n % Take max across discrete dimension of a quasimatrix:\n f = cheb2cell(f);\n y = -realmax;\n for k = 1:numel(f)\n y = maxOfTwoChebfuns(y, f{k});\n end\n y = merge(y);\n return\n end\nend\n\nif ( (nargin > 2) && isempty(flag) )\n % MAX(F, [], 1).\n flag = 'global';\nend\n\nif ( (nargin == 1) || strcmp(flag, 'global') ) \n % MAX(F) or MAX(F, 'global')\n [y, x] = globalMax(f); \n \nelseif ( isa(flag, 'chebfun') || isnumeric(flag) )\n % MAX(F, G)\n y = maxOfTwoChebfuns(f, flag);\n \nelseif ( strcmp(flag, 'local') )\n % MAX(F, 'local')\n [y, x] = localMax(f);\n \nelse\n error('CHEBFUN:CHEBFUN:max:flag', 'Unrecognized flag.');\n \nend\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% GLOBAL MAXIMUM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [y, x] = globalMax(f)\n\n% Call MINANDMAX():\n[y, x] = minandmax(f);\n\n% Extract the maximum:\ny = y(2,:);\nx = x(2,:);\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% LOCAL MAXIMA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [y, x] = localMax(f)\n\n% Call MINANDMAX():\n[y, x] = minandmax(f, 'local');\n\n% Determine which are maxima.\n\nends = f(1).domain([1, end]).'; % Endpoints of the domain are special.\nf = mat2cell(f); % Convert f into a cell of scalar-valued CHEBFUNs.\n\n% Loop over the FUNs:\nfor k = 1:numel(f)\n % Compute 1st and 2nd derivatives.\n dfk = diff(f{k});\n dfk2 = diff(dfk);\n\n % For interior extrema, look at 2nd derivative:\n maximaLoc = feval(diff(f{k}, 2), x(:,k)) < 0;\n\n % For end-points, look at 1st derivative:\n dfk_ends = feval(dfk, ends);\n endptMaxLoc = dfk_ends.*[1, -1]' < 0;\n\n % If 1st derivative is small at an endpoint, assume it's zero and try to\n % use 2nd derivative to determine if it's a minimum:\n %\n % [TODO]: What if the 2nd derivative is zero, so that rounding error\n % precludes us from accurately determining the sign?\n smallEndDer = abs(dfk_ends) < 1e3*vscale(dfk)*eps;\n endptMaxLoc(smallEndDer) = feval(dfk2, ends(smallEndDer)) < 0;\n\n maximaLoc(1) = endptMaxLoc(1);\n maximaLoc(x(:,k) == ends(2)) = endptMaxLoc(2);\n\n % Set points corresponding to local maxima to NaN:\n y(~maximaLoc,k) = NaN;\n x(~maximaLoc,k) = NaN;\n\n % Sort the result\n [x(:,k), maximaLoc] = sort(x(:,k));\n y(:,k) = y(maximaLoc,k);\nend\n\n% Remove any rows which contain only NaNs.\nx(all(isnan(x), 2),:) = []; \ny(all(isnan(y), 2),:) = [];\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%% MAX(F, G) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction h = maxOfTwoChebfuns(f, g)\n% Return the function h(x) = max(f(x), g(x)) for all x. \n\n% If one is complex, use abs(f) and abs(g) to determine which function values to\n% keep. (experimental feature)\nif ( isreal(f) && isreal(g) && (nargin < 3) )\n\tS = sign(f - g);\nelse\n\tS = sign(abs(f) - abs(g));\nend\n\n% Heaviside function (0 where f > g, 1 where f < g);\nH = 0.5*(S + 1);\nnotH = 0.5*(1 - S); % ~H.\n\n% Combine for output:\nh = H.*f + notH.*g;\n\n% [TODO]: Enforce continuity?\n\n% TODO: Why simplify?\n% Simplify:\nh = simplify(h);\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/@chebfun/max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3754011155526398}} {"text": "function polar_info_esti = FastSCL_decoder(llr, L, info_bits, lambda_offset, llr_layer_vec, bit_layer_vec, psi_vec, node_type_matrix, H_crc)\n%2018.1.7.14:16 Yu Y. R.\n%LLR-based SCL deocoder\n%Systematic polar code used\n%4 nodes are identified and decoded, i.e., rate0, rate1, rep, spc,\n%No BLER loss, while using fast algorithms.\n%const\nN = length(llr);\nm = log2(N);\n%memory declared\nP = zeros(N - 1, L); %llr is public-used, so N - 1 is enough.\nC = zeros(2 * N - 1, 2 * L);\nPM = zeros(L, 1);\nactivepath = zeros(L, 1);\nlazy_copy = zeros(m, L); \n%initialize the 1st SC decoder\nactivepath(1) = 1;\nlazy_copy(:, 1) = 1;\n%decoding starts\n%default: in the case of path clone in REP and leaf node,\n%origianl always corresponds to bit 0s, while the new path bit 1s.\nfor i_node = 1 : size(node_type_matrix, 1)\n current_index = node_type_matrix(i_node, 1);\n llr_layer = llr_layer_vec(current_index);\n M = node_type_matrix(i_node, 2);%number of leaf nodes in this constituent node\n reduced_layer = log2(M); %For LLR recursion, this reduced layer denotes where to stop; For Bit recursion, this denotes where to start.\n psi = psi_vec(i_node);%This psi is used for bits recursion\n psi_mod_2 = mod(psi, 2);%To decide whether the bit recuision should continue. 1 : continue; 0 : stop.\n for l_index = 1 : L\n if activepath(l_index) == 0\n continue;\n end\n switch current_index\n case 1\n index_1 = lambda_offset(m);\n for beta = 0 : index_1 - 1\n P(beta + index_1, l_index) = sign(llr(beta + 1)) * sign(llr(beta + index_1 + 1)) * min(abs(llr(beta + 1)), abs(llr(beta + index_1 + 1)));\n end\n for i_layer = m - 2 : -1 : reduced_layer\n index_1 = lambda_offset(i_layer + 1);\n index_2 = lambda_offset(i_layer + 2);\n for beta = index_1 : index_2 - 1\n P(beta, l_index) = sign(P(beta + index_1, l_index)) * sign(P(beta + index_2, l_index)) * ...\n min(abs(P(beta + index_1, l_index)), abs(P(beta + index_2, l_index)));\n end\n end\n case N/2 + 1\n index_1 = lambda_offset(m);\n for beta = 0 : index_1 - 1\n x_tmp = C(beta + index_1, 2 * l_index - 1);\n P(beta + index_1, l_index) = (1 - 2 * x_tmp) * llr(beta + 1) + llr(beta + index_1 + 1);\n end\n for i_layer = m - 2 : -1 : reduced_layer\n index_1 = lambda_offset(i_layer + 1);\n index_2 = lambda_offset(i_layer + 2);\n for beta = index_1 : index_2 - 1\n P(beta, l_index) = sign(P(beta + index_1, l_index)) * sign(P(beta + index_2, l_index)) * ...\n min(abs(P(beta + index_1, l_index)), abs(P(beta + index_2, l_index)));\n end\n end\n otherwise\n index_1 = lambda_offset(llr_layer + 1);\n index_2 = lambda_offset(llr_layer + 2);\n for beta = index_1 : index_2 - 1\n %lazy copy\n P(beta, l_index) = (1 - 2 * C(beta, 2 * l_index - 1)) * P(beta + index_1, lazy_copy(llr_layer + 2, l_index)) + P(beta + index_2, lazy_copy(llr_layer + 2, l_index));\n end\n for i_layer = llr_layer - 1 : -1 : reduced_layer\n index_1 = lambda_offset(i_layer + 1);\n index_2 = lambda_offset(i_layer + 2);\n for beta = index_1 : index_2 - 1\n P(beta, l_index) = sign(P(beta + index_1, l_index)) * sign(P(beta + index_2, l_index)) * ...\n min(abs(P(beta + index_1, l_index)), abs(P(beta + index_2, l_index)));\n end\n end\n end\n end%LLR calculations. You may fold thiis code block.\n index_vec = M : 2 * M - 1;\n switch node_type_matrix(i_node, 3)\n case -1%****RATE 0*****\n x = zeros(M, 1);\n for l_index = 1 : L\n if activepath(l_index) == 0\n continue;\n end\n C(index_vec, psi_mod_2 + 2 * l_index - 1) = x;\n PM(l_index) = PM(l_index) + sum(log(1 + exp(-P(index_vec, l_index)))); \n %Do not forget updating path metric in rate 0 nodes\n %No copy in Rate 0 node\n end\n case 1%*****RATE 1*****\n %input LLR: P(index_vec, :)\n [PM, activepath, selected_subcodeword, lazy_copy] = Rate1(M, P(index_vec, :), activepath, PM, L, lazy_copy);\n %output: estimated sub polar codeword: 'selected_subcodeword'.\n for l_index = 1 : L\n if activepath(l_index) == 0\n continue\n end\n C(index_vec, 2 * l_index - 1 + psi_mod_2) = selected_subcodeword(:, l_index);\n end\n case 2%*****REP*****\n [PM, activepath, lazy_copy, selected_subcodeword] = Rep(PM, P(index_vec, :), activepath, L, M, lazy_copy);\n for l_index = 1 : L\n if activepath(l_index) == 0\n continue\n end\n C(index_vec, 2 * l_index - 1 + psi_mod_2) = selected_subcodeword(:, l_index);\n end\n case 3%*******SPC*******\n [PM, activepath, selected_subcodeword, lazy_copy] = SPC(index_vec, P(index_vec, :), activepath, PM, L, lazy_copy);\n for l_index = 1 : L\n if activepath(l_index) == 0\n continue\n end\n C(index_vec, 2 * l_index - 1 + psi_mod_2) = selected_subcodeword(:, l_index);\n end\n end\n %Internal Bits Update for each active path\n bit_layer = bit_layer_vec(current_index + M - 1);\n for l_index = 1 : L\n if activepath(l_index) == 0\n continue;\n end\n if psi_mod_2 == 1%right child of its mother\n for i_layer = reduced_layer : bit_layer - 1\n index_1 = lambda_offset(i_layer + 1);\n index_2 = lambda_offset(i_layer + 2);\n for beta = index_1 : index_2 - 1\n C(beta + index_1, 2 * l_index) = mod(C(beta, 2 * lazy_copy(i_layer + 1, l_index) - 1) + C(beta, 2 * l_index), 2);\n C(beta + index_2, 2 * l_index) = C(beta, 2 * l_index);\n end\n end\n index_1 = lambda_offset(bit_layer + 1);\n index_2 = lambda_offset(bit_layer + 2);\n for beta = index_1 : index_2 - 1\n C(beta + index_1, 2 * l_index - 1) = mod(C(beta, 2 * lazy_copy(bit_layer + 1, l_index) - 1) + C(beta, 2 * l_index), 2);\n C(beta + index_2, 2 * l_index - 1) = C(beta, 2 * l_index);\n end\n end\n end\n %lazy copy\n if i_node < size(node_type_matrix, 1)\n for i_layer = 1 : llr_layer_vec(current_index + M) + 1\n for l_index = 1 : L\n lazy_copy(i_layer, l_index) = l_index;\n end\n end\n end\nend\n%select the best path\n[~, path_ordered] = sort(PM);\nfor l_index = 1 : L\n path_num = path_ordered(l_index);\n x = C(end - N + 1 : end, 2 * path_num - 1);\n info_with_crc = x(info_bits);\n err = sum(mod(H_crc * info_with_crc, 2));\n if err == 0\n polar_info_esti = info_with_crc;\n break;\n else\n if l_index == L\n x = C(end - N + 1 : end, 2 * path_ordered(1) - 1);\n polar_info_esti = x(info_bits);\n end\n end\nend\nend", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/FastSCL_decoder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3748880783340613}} {"text": "function n = gqu_order ( l )\n\n%*****************************************************************************80\n%\n%% GQU_ORDER computes the order of a GQU rule from the level.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 June 2012\n%\n% Author:\n%\n% John Burkardt.\n%\n% Parameters:\n%\n% Input, integer L, the level of the rule. \n% 1 <= L.\n%\n% Output, integer N, the order of the rule.\n%\n if ( l < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GQU_ORDER - Fatal error!\\n' );\n fprintf ( 1, ' 1 <= L required.\\n' );\n fprintf ( 1, ' Input L = %d\\n', l );\n error ( 'GQU_ORDER - Fatal error!' );\n elseif ( l <= 25 )\n n = l;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GQU_ORDER - Fatal error!\\n' );\n fprintf ( 1, ' L <= 25 required.\\n' );\n fprintf ( 1, ' Input L = %d\\n', l );\n error ( 'GQU_ORDER - Fatal error!' );\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/sparse_grid_hw/gqu_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3748367861197163}} {"text": "function [y]=tt_rc2(d,n,elem_fun,eps,varargin)\n%[Y]=TT_RC2(D,N,ARR,ELEM_FUN,EPS,[OPTIONS])\n%The TT-Renormalization-Cross algorithm\n%input is: the dimension of the array d, the \n%size vector n, the function that computes the prescribed element\n%of an array, accuracy parameter eps\n%and also additional arguments specified as 'rmax',10,'nswp',10\n%'verb',true and so on\n% 'x0', x0\n%The elem function has syntax elem_fun(ind); all other additional\n%information\n%has to be passed as \"anonymous\" arguments\n\n%The algorithm. It needs left & right index sets to be initialized.\n%It needs supecores to be precomputed\n%It is a good idea to store also the supercores (there will be d-1,\n%i think) & update them; also certain indices maybe removed from the\n%index set?? we will not do that; \n%Two possibilities: current index contains maxvol submatrix;\n%If not, increase, increase & increase (maybe even beyond the rank!)\n%rank one subtraction can be made very stable\n\n\n%Default parameters\nif ( numel(n) == 1 )\n n=n*ones(1,d);\nend\nnswp=10;\nrmax=1000;\nx0=[];\nverb=true;\nvec=false; %If there is a vectorization in options, i.e. if elem_fun\n%supports vectorized computations of many elements at once\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'rmax'\n rmax=lower(varargin{i+1});\n case 'x0'\n x0=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'vec'\n vec=varargin{i+1};\n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\nend\n\n%The initial setup is done. \n\n%We need initial index sets. Say, the vector of all ones (he-he)\n%i_left;\n%r_left;\n%i_right;\n%r_right;\ni_left=cell(d,1);\ni_right=cell(d,1);\nr_left=cell(d,1);\nr_right=cell(d,1);\nry=ones(d+1,1); %Initial ranks\n%Find fiber maximum\nind=2*ones(d,1);\nind=find_fiber_maximum(elem_fun,ind);\nfor i=1:d\n i_left{i}=ind(i);\n i_right{i}=ind(i);\n r_left{i}=1;\n r_right{i}=1;\nend\n\n%Before we get the multiindex sets (helps to compute s-u-p-e-r-c-o-r-e-s)\n\nind_left=get_multi_left(i_left,r_left,ry);\nind_right=get_multi_right(i_right,r_right,ry);\n\n%Now we have to compute s-u-p-e-r-c-o-r-e-s (not cores!) using ind_left &\n%ind_right\nsuper_core=cell(d-1,1);\nfor i=1:d-1 %There are d-1 s-u-p-e-r-c-o-r-e-s\n %Compute the index set for the i-th one\n index_set=zeros(d,ry(i),n(i),n(i+1),ry(i+2));\n if ( i == 1 )\n ileft=zeros(1,0);\n else\n ileft=ind_left{i-1}; \n end\n if ( i == d - 1 )\n iright = zeros(1,0);\n else\n iright=ind_right{i+2};\n end\n for s1=1:ry(i)\n for s2=1:ry(i+2)\n for i1=1:n(i)\n for i2=1:n(i+1)\n index_set(:,s1,i1,i2,s2)=[ileft(s1,:),i1,i2,iright(s2,:)];\n end\n end\n end\n end\n M=ry(i)*n(i)*n(i+1)*ry(i+2);\n index_set=reshape(index_set,[d,M]);\n if ( vec ) \n super_core{i}=reshape(elem_fun(index_set),[ry(i),n(i),n(i+1),ry(i+2)]);\n else\n cur_core=zeros(M,1);\n for k=1:M\n cur_core(k)=elem_fun(index_set(:,k));\n end\n super_core{i}=reshape(cur_core,[ry(i),n(i),n(i+1),ry(i+2)]);\n end\n \nend\n%Initialization is done. \n%Now to the main iteration\n\n%Through all the s-u-p-e-r-c-o-r-e-s\nswp=1;\ndir='lr';\ni=1;\nwhile ( swp <= nswp )\n %The method acts as follows.\n %1) Test if the current supercore is well approximated by the\n %current cross\n %2) If yes, do nothing. \n %3) If no, add the required indices to the cross and perform\n %modifications of the s-u-p-e-r-c-o-r-e-s\n \n %Nikrena ne soobrajau\n %Bilo: (i1,i2,i3,i4,i5) \n %Pofiksili (i1,i2), uvelichili r2. Rashirilos' mnojestvo (i2,i3,i4,i5)\n %(nikomu ne nujno)\n %V seredine: (i1,i2) (i3,i4,i5)+ - uvelichilos' mojectvo\n %Kogda uvelichili (i3,i4,i5) viros ry(3), uvelichilos 1 superyadro\n cur_core=super_core{i}; \n %we have to convert the pair i_left{i} & r_left{i} to the \n %index set for the matrix cur_core\n \n cur_core=reshape(cur_core,[ry(i)*n(i),n(i+1)*ry(i+2)]);\n %i1=get_full_ind(i_left{i},r_left{i});\n %i2=get_full_ind(i_right{i+1},r_right{i+1});\n %ry(i)*n(i)\n \n i1=r_left{i}+(i_left{i}-1)*ry(i); \n i2=i_right{i+1}+(r_right{i+1}-1)*n(i+1);\n % if ( numel(i1)==2)\n % if ( i1(1) == 2 && i1(2) == 2 )\n % keyboard;\n % end\n % end\n [i1,i2]=new_cross(cur_core,i1,i2,eps); \n %Increase i_left{i} & i_right{i+1}\n [radd_left,iadd_left]=ind2sub([ry(i);n(i)],i1);\n [iadd_right,radd_right]=ind2sub([n(i+1);ry(i+2)],i2);\n i_left{i}=iadd_left;\n r_left{i}=radd_left;\n %if ( i == 8 )\n % keyboard\n %end\n i_right{i+1}=iadd_right;\n r_right{i+1}=radd_right;\n ry(i+1)=numel(i1);\n %Zaglushka\n ind_left=get_multi_left(i_left,r_left,ry);\n \n ind_right=get_multi_right(i_right,r_right,ry);\n \n % fprintf('Index set in question: \\n');\n % ind_left{3}\n % if ( i == 3 && swp == 2 )\n % keyboard;\n % end\n %keyboard;\n if ( i > 1 ) \n %Recompute supercore{i-1} \n super_core{i-1}=compute_supercore(i-1,elem_fun,d,n,ry,ind_left,ind_right,vec);\n end\n if ( i < d - 1)\n super_core{i+1}=compute_supercore(i+1,elem_fun,d,n,ry,ind_left,ind_right,vec);\n %Recompute supercore{i+1}; \n end\n\n %Convert iadd1 to i_left and i_right format; compute new\n %ind_left{i+1},ind_right{i+1}\n if ( strcmp(dir,'lr') )\n if ( i == d-1 )\n dir='rl';\n else\n i=i+1;\n end\n else\n if ( i == 1 )\n dir ='lr';\n swp=swp+1;\n else\n i=i-1;\n end\n end\n fprintf('Step %d sweep %d rank=%3.1f \\n',i,swp,mean(ry));\nend\nfprintf('Done! \\n');\nkeyboard;\n\n\n\n\n\n\n\nreturn\nend\n\nfunction [super_core]=compute_supercore(i,elem_fun,d,n,ry,ind_left,ind_right,vec)\n%[super_core]=compute_supercore(i,elem_fun,n,ry,ind_left,ind_right)\n index_set=zeros(d,ry(i),n(i),n(i+1),ry(i+2));\n if ( i == 1 )\n ileft=zeros(1,0);\n else\n ileft=ind_left{i-1}; \n end\n if ( i == d - 1 )\n iright = zeros(1,0);\n else\n iright=ind_right{i+2};\n end\n for s1=1:ry(i)\n for s2=1:ry(i+2)\n for i1=1:n(i)\n for i2=1:n(i+1)\n index_set(:,s1,i1,i2,s2)=[ileft(s1,:),i1,i2,iright(s2,:)];\n end\n end\n end\n end\n M=ry(i)*n(i)*n(i+1)*ry(i+2);\n index_set=reshape(index_set,[d,M]);\n if ( vec ) \n super_core=reshape(elem_fun(index_set),[ry(i),n(i),n(i+1),ry(i+2)]);\n else\n cur_core=zeros(M,1);\n for k=1:M\n cur_core(k)=elem_fun(index_set(:,k));\n end\n super_core=reshape(cur_core,[ry(i),n(i),n(i+1),ry(i+2)]);\n end\n \n\nreturn\nend\n\nfunction [i1,i2]=new_cross(mat,i1,i2,eps)\n%[i1,i2]=enlarge_cross(mat,i1,i2,eps) \n%Tests whether the current index set gives a reasonable approximation\n%to the matrix, and enlarges the basis if necessary.\n%The method acts as follows. \n\n%A-C*A11^{-1} R\n\n%sbm=mat(i1,i2); \n%[u,s,v]=svd(sbm,'econ');\n%nrm=norm(mat);s=diag(s); \n%r=numel(find(\n%mat_save=mat;\ni1=[];\ni2=[];\ndesirata=eps*norm(mat,'fro');\ner=norm(mat,'fro');\nwhile ( er > desirata )\n %Find maximal element in mat\n [~,ind]=max(abs(mat(:)));\n ind=tt_ind2sub(size(mat),ind);\n i=ind(1); j=ind(2);\n i1=[i1;i];\n i2=[i2;j];\n u1=mat(:,j); u2=mat(i,:);\n u1=u1/mat(i,j);\n mat=mat-u1*u2;\n er=norm(mat,'fro');\nend\n% i0=[i1;iadd1]; j0=[i2;iadd2];\n% sbm=mat_save(i0,j0);\n% ss=svd(sbm);\n% fprintf('%10.10e \\n',ss)\n% sbm=mat_save(i1,i2);\n% fprintf('AND PREVIOUS \\n');\n% ss=svd(sbm);\n% fprintf('%10.10e \\n',ss)\n\nreturn\nend\n\nfunction [ind_left]=get_multi_left(i_left,r_left,ry)\n%[ind_left]=get_multi_left(i_left,r_left,ry)\n%Computes (all) left multiindex sets for a given compact representation\n d=numel(i_left);\n ind_left=cell(d,1);\n ind_left{1}=i_left{1};\n for i=2:d\n %ind_cur=zeros(\n %ind_cur is an array of size ry(i-1) x i\n ind_cur=zeros(ry(i+1),i);\n r_prev=r_left{i};\n ind_prev=ind_left{i-1};\n i_prev=i_left{i};\n for s=1:ry(i+1)\n %ind_prev(p1(s\n ind_cur(s,:)=[ind_prev(r_prev(s),:),i_prev(s)];\n end\n ind_left{i}=ind_cur;\n end\nreturn\nend\n\nfunction [ind_right]=get_multi_right(i_right,r_right,ry)\n%[ind_right]=get_multi_right(i_right,r_right,ry)\n%Computes (all) right multiindex sets for a given compact representation\n d=numel(i_right);\n ind_right=cell(d,1);\n ind_right{d}=i_right{d};\n for i=d-1:-1:1\n %ind_cur=zeros(\n %ind_cur is an array of size ry(i) x i\n ind_cur=zeros(ry(i),d-i+1);\n r_prev=r_right{i};\n ind_prev=ind_right{i+1};\n i_prev=i_right{i};\n for s=1:ry(i)\n ind_cur(s,:)=[i_prev(s), ind_prev(r_prev(s),:)];\n end\n ind_right{i}=ind_cur;\n end\n\nreturn\nend\n\nfunction [ind]=find_fiber_maximum(elem_fun,ind)\n%[ind]=find_fiber_maximum(elem_fun,ind)\n%Simple ALS method to compute (approximate) maximum in a tensor\n%In fact, need some non-zero\n%fact=2; %If the new one <= fact times larger than the previous, stop\n\nreturn\nend\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/cross/oldcross/tt_rc2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.374836778090798}} {"text": "function cy = zcopy ( n, cx, incx, cy, incy )\n\n%*****************************************************************************80\n%\n%% ZCOPY copies a complex vector X to a vector Y.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 May 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979.\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 elements in CX and CY.\n%\n% Input, complex CX(*), the first vector.\n%\n% Input, integer INCX, the increment between successive entries of CX.\n%\n% Input, complex CY(*), the second vector.\n%\n% Input, integer INCY, the increment between successive entries of CY.\n%\n% Output, complex CY(*), the second vector, with certain elements\n% copied from CX.\n%\n cy(1:incy:1+(n-1)*incy) = 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_z/zcopy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.37466060905163096}} {"text": "%SerialLink.IKINEM Numerical inverse kinematics by minimization\n%\n% Q = R.ikinem(T) is the joint coordinates corresponding to the robot\n% end-effector pose T which is a homogenenous transform.\n%\n% Q = R.ikinem(T, Q0, OPTIONS) specifies the initial estimate of the joint\n% coordinates.\n%\n% In all cases if T is 4x4xM it is taken as a homogeneous transform sequence\n% and R.ikinem() returns the joint coordinates corresponding to each of the\n% transforms in the sequence. Q is MxN where N is the number of robot joints.\n% The initial estimate of Q for each time step is taken as the solution\n% from the previous time step.\n%\n% Options::\n% 'pweight',P weighting on position error norm compared to rotation\n% error (default 1)\n% 'stiffness',S Stiffness used to impose a smoothness contraint on joint\n% angles, useful when N is large (default 0)\n% 'qlimits' Enforce joint limits\n% 'ilimit',L Iteration limit (default 1000)\n% 'nolm' Disable Levenberg-Marquadt\n%\n% Notes::\n% - PROTOTYPE CODE UNDER DEVELOPMENT, intended to do numerical inverse kinematics\n% with joint limits\n% - The inverse kinematic solution is generally not unique, and\n% depends on the initial guess Q0 (defaults to 0).\n% - The function to be minimized is highly nonlinear and the solution is\n% often trapped in a local minimum, adjust Q0 if this happens.\n% - The default value of Q0 is zero which is a poor choice for most\n% manipulators (eg. puma560, twolink) since it corresponds to a kinematic\n% singularity.\n% - Such a solution is completely general, though much less efficient\n% than specific inverse kinematic solutions derived symbolically, like\n% ikine6s or ikine3.% - Uses Levenberg-Marquadt minimizer LMFsolve if it can be found,\n% if 'nolm' is not given, and 'qlimits' false\n% - The error function to be minimized is computed on the norm of the error \n% between current and desired tool pose. This norm is computed from distances\n% and angles and 'pweight' can be used to scale the position error norm to\n% be congruent with rotation error norm.\n% - This approach allows a solution to obtained at a singularity, but\n% the joint angles within the null space are arbitrarily assigned.\n% - Joint offsets, if defined, are added to the inverse kinematics to\n% generate Q.\n% - Joint limits become explicit contraints if 'qlimits' is set.\n%\n% See also fminsearch, fmincon, SerialLink.fkine, SerialLink.ikine, tr2angvec.\n\n\n\n\n% Copyright (C) 1993-2017, 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 qt = ikinem(robot, tr, varargin)\n \n opt.pweight = 1;\n opt.stiffness = 0;\n opt.qlimits = false;\n opt.ilimit = 1000;\n opt.lm = true;\n opt.col = 2;\n \n [opt,args] = tb_optparse(opt, varargin);\n \n % check if optional argument is a valid q\n q0 = args{1};\n if numel(q0) ~= robot.n\n error('q0 length must match number of joints in robot');\n end\n \n \n for i=1:size(tr,3)\n T = tr(:,:,i);\n \n if opt.qlimits\n % constrained optimization to handle joint limits\n options = optimset('MaxIter', opt.ilimit);\n qlim = robot.qlim;\n \n [q, ef, exflag, output] = fmincon( @(x) costfun(x, robot, T, opt), q0, ...\n [], [], [], [], ...\n qlim(:,1), qlim(:,2), ...\n [], options);\n \n if opt.verbose\n fprintf('final error %f, %d iterations, %d evalations\\n', ...\n ef, output.iterations, output.funcCount);\n end\n \n else\n % no joint limits, unconstrained optimization\n if exist('LMFsolve') == 2 && opt.lm\n [q, ef, count] = LMFsolve( @(x) costfun(x, robot, T, opt), q0, 'MaxIter', opt.ilimit);\n q = q';\n if opt.verbose\n fprintf('final error %f, %d iterations\\n', ...\n ef, count);\n end\n else\n options = optimset('MaxIter', opt.ilimit);\n [q, ef, exflag, output] = fminsearch( @(x) costfun(x, robot, T, opt), q0, options);\n \n if opt.verbose\n fprintf('final error %f, %d iterations, %d evalations\\n', ...\n ef, output.iterations, output.funcCount);\n end\n end\n end\n \n qt(i,:) = q;\n end\n \n if opt.verbose\n robot.fkine(qt)\n end\nend\n\n% The cost function, this is the value to be minimized\nfunction E = costfun(q, robot, T, opt)\n \n Tq = robot.fkine(q);\n % find the pose error in SE(3)\n dT = transl(T) - transl(Tq);\n \n % translation error\n E = norm(dT) * opt.pweight;\n \n % rotation error\n % find dot product of \n dd = dot(T(1:3,opt.col), Tq(1:3,opt.col));\n %E = E + (1 - dd)^2*100000 ;\n E = E + acos(dd)^2*1000 ;\n \n \n if opt.stiffness > 0\n % enforce a continuity constraint on joints, minimum bend\n E = E + sum( diff(q).^2 ) * opt.stiffness;\n end\nend\n \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/ikinem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.3744674775104047}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%% %%%%%\n%%%% IEEE PES Power Grid Library - Optimal Power Flow - v21.07 %%%%%\n%%%% (https://github.com/power-grid-lib/pglib-opf) %%%%%\n%%%% Benchmark Group - Active Power Increase %%%%%\n%%%% 29 - July - 2021 %%%%%\n%%%% %%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction mpc = pglib_opf_case24_ieee_rts__api\nmpc.version = '2';\nmpc.baseMVA = 100.0;\n\n%% area data\n%\tarea\trefbus\nmpc.areas = [\n\t1\t 1;\n\t2\t 3;\n\t3\t 8;\n\t4\t 6;\n];\n\n%% bus data\n%\tbus_i\ttype\tPd\tQd\tGs\tBs\tarea\tVm\tVa\tbaseKV\tzone\tVmax\tVmin\nmpc.bus = [\n\t1\t 2\t 207.30\t 22.00\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t2\t 2\t 186.19\t 20.00\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t3\t 1\t 345.50\t 37.00\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t4\t 1\t 142.04\t 15.00\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t5\t 1\t 136.28\t 14.00\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t6\t 1\t 261.04\t 28.00\t 0.0\t -100.0\t 2\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t7\t 2\t 239.93\t 25.00\t 0.0\t 0.0\t 2\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t8\t 1\t 328.23\t 35.00\t 0.0\t 0.0\t 2\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t9\t 1\t 335.90\t 36.00\t 0.0\t 0.0\t 1\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t10\t 1\t 374.29\t 40.00\t 0.0\t 0.0\t 2\t 1.00000\t 0.00000\t 138.0\t 1\t 1.05000\t 0.95000;\n\t11\t 1\t 0.0\t 0.0\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t12\t 1\t 0.0\t 0.0\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t13\t 3\t 508.65\t 54.00\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t14\t 2\t 372.37\t 39.00\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t15\t 2\t 608.47\t 64.00\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t16\t 2\t 191.94\t 20.00\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t17\t 1\t 0.0\t 0.0\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t18\t 2\t 639.18\t 68.00\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t19\t 1\t 347.42\t 37.00\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t20\t 1\t 245.69\t 26.00\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t21\t 2\t 0.0\t 0.0\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t22\t 2\t 0.0\t 0.0\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t23\t 2\t 0.0\t 0.0\t 0.0\t 0.0\t 3\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n\t24\t 1\t 0.0\t 0.0\t 0.0\t 0.0\t 4\t 1.00000\t 0.00000\t 230.0\t 1\t 1.05000\t 0.95000;\n];\n\n%% generator data\n%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin\nmpc.gen = [\n\t1\t 43.5\t 0.0\t 40.0\t -40.0\t 1.0\t 100.0\t 1\t 79\t 8.0; % PEL\n\t1\t 109.5\t 0.0\t 106.0\t -106.0\t 1.0\t 100.0\t 1\t 211\t 8.0; % PEL\n\t1\t 41.3\t 0.0\t 38.0\t -38.0\t 1.0\t 100.0\t 1\t 75\t 7.6; % PEL\n\t1\t 42.8\t 0.0\t 39.0\t -39.0\t 1.0\t 100.0\t 1\t 78\t 7.6; % NG\n\t2\t 98.0\t 0.0\t 94.0\t -94.0\t 1.0\t 100.0\t 1\t 188\t 8.0; % NG\n\t2\t 95.0\t 0.0\t 91.0\t -91.0\t 1.0\t 100.0\t 1\t 182\t 8.0; % PEL\n\t2\t 91.8\t 0.0\t 88.0\t -88.0\t 1.0\t 100.0\t 1\t 176\t 7.6; % NG\n\t2\t 335.3\t 0.0\t 332.0\t -332.0\t 1.0\t 100.0\t 1\t 663\t 7.6; % COW\n\t7\t 221.25\t 0.0\t 215.0\t -215.0\t 1.0\t 100.0\t 1\t 430\t 12.5; % NG\n\t7\t 82.75\t 0.0\t 77.0\t -77.0\t 1.0\t 100.0\t 1\t 153\t 12.5; % NG\n\t7\t 303.75\t 0.0\t 298.0\t -298.0\t 1.0\t 100.0\t 1\t 595\t 12.5; % COW\n\t13\t 289.25\t 0.0\t 272.0\t -272.0\t 1.0\t 100.0\t 1\t 544\t 34.5; % NG\n\t13\t 288.25\t 0.0\t 271.0\t -271.0\t 1.0\t 100.0\t 1\t 542\t 34.5; % NG\n\t13\t 321.75\t 0.0\t 305.0\t -305.0\t 1.0\t 100.0\t 1\t 609\t 34.5; % COW\n\t14\t 0.0\t 0.0\t 252.0\t -252.0\t 1.0\t 100.0\t 1\t 0\t 0.0; % SYNC\n\t15\t 80.1\t 0.0\t 94.8\t -94.8\t 1.0\t 100.0\t 1\t 159\t 1.2; % NG\n\t15\t 103.6\t 0.0\t 103.0\t -103.0\t 1.0\t 100.0\t 1\t 206\t 1.2; % COW\n\t15\t 98.1\t 0.0\t 98.0\t -98.0\t 1.0\t 100.0\t 1\t 195\t 1.2; % NG\n\t15\t 81.6\t 0.0\t 94.8\t -94.8\t 1.0\t 100.0\t 1\t 162\t 1.2; % NG\n\t15\t 70.1\t 0.0\t 94.8\t -94.8\t 1.0\t 100.0\t 1\t 139\t 1.2; % NG\n\t15\t 116.575\t 0.0\t 103.0\t -103.0\t 1.0\t 100.0\t 1\t 206\t 27.15; % NG\n\t16\t 308.075\t 0.0\t 295.0\t -295.0\t 1.0\t 100.0\t 1\t 589\t 27.15; % NG\n\t18\t 216.0\t 4.5\t 200.0\t -191.0\t 1.0\t 100.0\t 1\t 382\t 50.0; % NG\n\t21\t 362.5\t 0.0\t 338.0\t -338.0\t 1.0\t 100.0\t 1\t 675\t 50.0; % COW\n\t22\t 113.5\t 0.0\t 111.0\t -111.0\t 1.0\t 100.0\t 1\t 222\t 5.0; % NG\n\t22\t 94.5\t 0.0\t 92.0\t -92.0\t 1.0\t 100.0\t 1\t 184\t 5.0; % NG\n\t22\t 75.5\t 0.0\t 73.0\t -73.0\t 1.0\t 100.0\t 1\t 146\t 5.0; % NG\n\t22\t 119.0\t 0.0\t 117.0\t -117.0\t 1.0\t 100.0\t 1\t 233\t 5.0; % COW\n\t22\t 110.5\t 0.0\t 108.0\t -108.0\t 1.0\t 100.0\t 1\t 216\t 5.0; % NG\n\t22\t 44.0\t 0.0\t 42.0\t -42.0\t 1.0\t 100.0\t 1\t 83\t 5.0; % NG\n\t23\t 224.075\t 0.0\t 211.0\t -211.0\t 1.0\t 100.0\t 1\t 421\t 27.15; % NG\n\t23\t 159.575\t 0.0\t 146.0\t -146.0\t 1.0\t 100.0\t 1\t 292\t 27.15; % COW\n\t23\t 226.0\t 0.0\t 191.0\t -191.0\t 1.0\t 100.0\t 1\t 382\t 70.0; % NG\n];\n\n%% generator cost data\n%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\nmpc.gencost = [\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 130.000000\t 400.684900; % PEL\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 130.000000\t 400.684900; % PEL\n\t2\t 1500.0\t 0.0\t 3\t 0.014142\t 16.081100\t 212.307600; % PEL\n\t2\t 1500.0\t 0.0\t 3\t 0.014142\t 16.081100\t 212.307600; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 130.000000\t 400.684900; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 130.000000\t 400.684900; % PEL\n\t2\t 1500.0\t 0.0\t 3\t 0.014142\t 16.081100\t 212.307600; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.014142\t 16.081100\t 212.307600; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.052672\t 43.661500\t 781.521000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.052672\t 43.661500\t 781.521000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.052672\t 43.661500\t 781.521000; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.007170\t 48.580400\t 832.757500; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.007170\t 48.580400\t 832.757500; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.007170\t 48.580400\t 832.757500; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.000000\t 0.000000; % SYNC\n\t2\t 1500.0\t 0.0\t 3\t 0.328412\t 56.564000\t 86.385200; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.328412\t 56.564000\t 86.385200; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.328412\t 56.564000\t 86.385200; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.328412\t 56.564000\t 86.385200; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.328412\t 56.564000\t 86.385200; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.008342\t 12.388300\t 382.239100; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.008342\t 12.388300\t 382.239100; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000213\t 4.423100\t 395.374900; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000213\t 4.423100\t 395.374900; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.001000\t 0.001000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.001000\t 0.001000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.001000\t 0.001000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.001000\t 0.001000; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.001000\t 0.001000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.000000\t 0.001000\t 0.001000; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.008342\t 12.388300\t 382.239100; % NG\n\t2\t 1500.0\t 0.0\t 3\t 0.008342\t 12.388300\t 382.239100; % COW\n\t2\t 1500.0\t 0.0\t 3\t 0.004895\t 11.849500\t 665.109400; % NG\n];\n\n%% branch data\n%\tfbus\ttbus\tr\tx\tb\trateA\trateB\trateC\tratio\tangle\tstatus\tangmin\tangmax\nmpc.branch = [\n\t1\t 2\t 0.0026\t 0.0139\t 0.4611\t 175.0\t 193.0\t 200.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t1\t 3\t 0.0546\t 0.2112\t 0.0572\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t1\t 5\t 0.0218\t 0.0845\t 0.0229\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t2\t 4\t 0.0328\t 0.1267\t 0.0343\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t2\t 6\t 0.0497\t 0.192\t 0.052\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t3\t 9\t 0.0308\t 0.119\t 0.0322\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t3\t 24\t 0.0023\t 0.0839\t 0.0\t 400.0\t 510.0\t 600.0\t 1.03\t 0.0\t 1\t -30.0\t 30.0;\n\t4\t 9\t 0.0268\t 0.1037\t 0.0281\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t5\t 10\t 0.0228\t 0.0883\t 0.0239\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t6\t 10\t 0.0139\t 0.0605\t 2.459\t 175.0\t 193.0\t 200.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t7\t 8\t 0.0159\t 0.0614\t 0.0166\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t8\t 9\t 0.0427\t 0.1651\t 0.0447\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t8\t 10\t 0.0427\t 0.1651\t 0.0447\t 175.0\t 208.0\t 220.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t9\t 11\t 0.0023\t 0.0839\t 0.0\t 400.0\t 510.0\t 600.0\t 1.03\t 0.0\t 1\t -30.0\t 30.0;\n\t9\t 12\t 0.0023\t 0.0839\t 0.0\t 400.0\t 510.0\t 600.0\t 1.03\t 0.0\t 1\t -30.0\t 30.0;\n\t10\t 11\t 0.0023\t 0.0839\t 0.0\t 400.0\t 510.0\t 600.0\t 1.02\t 0.0\t 1\t -30.0\t 30.0;\n\t10\t 12\t 0.0023\t 0.0839\t 0.0\t 400.0\t 510.0\t 600.0\t 1.02\t 0.0\t 1\t -30.0\t 30.0;\n\t11\t 13\t 0.0061\t 0.0476\t 0.0999\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t11\t 14\t 0.0054\t 0.0418\t 0.0879\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t12\t 13\t 0.0061\t 0.0476\t 0.0999\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t12\t 23\t 0.0124\t 0.0966\t 0.203\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t13\t 23\t 0.0111\t 0.0865\t 0.1818\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t14\t 16\t 0.005\t 0.0389\t 0.0818\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t15\t 16\t 0.0022\t 0.0173\t 0.0364\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t15\t 21\t 0.0063\t 0.049\t 0.103\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t15\t 21\t 0.0063\t 0.049\t 0.103\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t15\t 24\t 0.0067\t 0.0519\t 0.1091\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t16\t 17\t 0.0033\t 0.0259\t 0.0545\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t16\t 19\t 0.003\t 0.0231\t 0.0485\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t17\t 18\t 0.0018\t 0.0144\t 0.0303\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t17\t 22\t 0.0135\t 0.1053\t 0.2212\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t18\t 21\t 0.0033\t 0.0259\t 0.0545\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t18\t 21\t 0.0033\t 0.0259\t 0.0545\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t19\t 20\t 0.0051\t 0.0396\t 0.0833\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t19\t 20\t 0.0051\t 0.0396\t 0.0833\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t20\t 23\t 0.0028\t 0.0216\t 0.0455\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t20\t 23\t 0.0028\t 0.0216\t 0.0455\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n\t21\t 22\t 0.0087\t 0.0678\t 0.1424\t 500.0\t 600.0\t 625.0\t 0.0\t 0.0\t 1\t -30.0\t 30.0;\n];\n\n% INFO : === Translation Options ===\n% INFO : Load Model: from file ./pglib_opf_case24_ieee_rts.m.api.sol\n% INFO : Gen Active Capacity Model: stat\n% INFO : Gen Reactive Capacity Model: al50ag\n% INFO : Gen Active Cost Model: stat\n% INFO : \n% INFO : === Load Replacement Notes ===\n% INFO : Bus 1\t: Pd=108.0, Qd=22.0 -> Pd=207.30, Qd=22.00\n% INFO : Bus 2\t: Pd=97.0, Qd=20.0 -> Pd=186.19, Qd=20.00\n% INFO : Bus 3\t: Pd=180.0, Qd=37.0 -> Pd=345.50, Qd=37.00\n% INFO : Bus 4\t: Pd=74.0, Qd=15.0 -> Pd=142.04, Qd=15.00\n% INFO : Bus 5\t: Pd=71.0, Qd=14.0 -> Pd=136.28, Qd=14.00\n% INFO : Bus 6\t: Pd=136.0, Qd=28.0 -> Pd=261.04, Qd=28.00\n% INFO : Bus 7\t: Pd=125.0, Qd=25.0 -> Pd=239.93, Qd=25.00\n% INFO : Bus 8\t: Pd=171.0, Qd=35.0 -> Pd=328.23, Qd=35.00\n% INFO : Bus 9\t: Pd=175.0, Qd=36.0 -> Pd=335.90, Qd=36.00\n% INFO : Bus 10\t: Pd=195.0, Qd=40.0 -> Pd=374.29, Qd=40.00\n% INFO : Bus 13\t: Pd=265.0, Qd=54.0 -> Pd=508.65, Qd=54.00\n% INFO : Bus 14\t: Pd=194.0, Qd=39.0 -> Pd=372.37, Qd=39.00\n% INFO : Bus 15\t: Pd=317.0, Qd=64.0 -> Pd=608.47, Qd=64.00\n% INFO : Bus 16\t: Pd=100.0, Qd=20.0 -> Pd=191.94, Qd=20.00\n% INFO : Bus 18\t: Pd=333.0, Qd=68.0 -> Pd=639.18, Qd=68.00\n% INFO : Bus 19\t: Pd=181.0, Qd=37.0 -> Pd=347.42, Qd=37.00\n% INFO : Bus 20\t: Pd=128.0, Qd=26.0 -> Pd=245.69, Qd=26.00\n% INFO : \n% INFO : === Generator Setpoint Replacement Notes ===\n% INFO : Gen at bus 1\t: Pg=18.0, Qg=5.0 -> Pg=73.0, Qg=1.0\n% INFO : Gen at bus 1\t: Pg=18.0, Qg=5.0 -> Pg=73.0, Qg=1.0\n% INFO : Gen at bus 1\t: Pg=45.6, Qg=2.5 -> Pg=72.0, Qg=1.0\n% INFO : Gen at bus 1\t: Pg=45.6, Qg=2.5 -> Pg=72.0, Qg=1.0\n% INFO : Gen at bus 2\t: Pg=18.0, Qg=5.0 -> Pg=157.0, Qg=31.0\n% INFO : Gen at bus 2\t: Pg=18.0, Qg=5.0 -> Pg=157.0, Qg=31.0\n% INFO : Gen at bus 2\t: Pg=45.6, Qg=2.5 -> Pg=156.0, Qg=31.0\n% INFO : Gen at bus 2\t: Pg=45.6, Qg=2.5 -> Pg=156.0, Qg=31.0\n% INFO : Gen at bus 7\t: Pg=62.5, Qg=30.0 -> Pg=126.0, Qg=42.0\n% INFO : Gen at bus 7\t: Pg=62.5, Qg=30.0 -> Pg=126.0, Qg=42.0\n% INFO : Gen at bus 7\t: Pg=62.5, Qg=30.0 -> Pg=126.0, Qg=42.0\n% INFO : Gen at bus 13\t: Pg=133.0, Qg=40.0 -> Pg=410.0, Qg=105.0\n% INFO : Gen at bus 13\t: Pg=133.0, Qg=40.0 -> Pg=410.0, Qg=105.0\n% INFO : Gen at bus 13\t: Pg=133.0, Qg=40.0 -> Pg=410.0, Qg=105.0\n% INFO : Gen at bus 14\t: Pg=0.0, Qg=75.0 -> Pg=0.0, Qg=210.0\n% INFO : Gen at bus 15\t: Pg=7.2, Qg=3.0 -> Pg=132.0, Qg=79.0\n% INFO : Gen at bus 15\t: Pg=7.2, Qg=3.0 -> Pg=132.0, Qg=79.0\n% INFO : Gen at bus 15\t: Pg=7.2, Qg=3.0 -> Pg=132.0, Qg=79.0\n% INFO : Gen at bus 15\t: Pg=7.2, Qg=3.0 -> Pg=132.0, Qg=79.0\n% INFO : Gen at bus 15\t: Pg=7.2, Qg=3.0 -> Pg=132.0, Qg=79.0\n% INFO : Gen at bus 15\t: Pg=104.65, Qg=15.0 -> Pg=184.0, Qg=79.0\n% INFO : Gen at bus 16\t: Pg=104.65, Qg=15.0 -> Pg=522.0, Qg=-34.0\n% INFO : Gen at bus 18\t: Pg=250.0, Qg=75.0 -> Pg=301.0, Qg=32.0\n% INFO : Gen at bus 21\t: Pg=250.0, Qg=75.0 -> Pg=203.0, Qg=-118.0\n% INFO : Gen at bus 22\t: Pg=30.0, Qg=3.0 -> Pg=68.0, Qg=-9.0\n% INFO : Gen at bus 22\t: Pg=30.0, Qg=3.0 -> Pg=68.0, Qg=-9.0\n% INFO : Gen at bus 22\t: Pg=30.0, Qg=3.0 -> Pg=68.0, Qg=-9.0\n% INFO : Gen at bus 22\t: Pg=30.0, Qg=3.0 -> Pg=68.0, Qg=-9.0\n% INFO : Gen at bus 22\t: Pg=30.0, Qg=3.0 -> Pg=68.0, Qg=-9.0\n% INFO : Gen at bus 22\t: Pg=30.0, Qg=3.0 -> Pg=68.0, Qg=-9.0\n% INFO : Gen at bus 23\t: Pg=104.65, Qg=15.0 -> Pg=237.0, Qg=15.0\n% INFO : Gen at bus 23\t: Pg=104.65, Qg=15.0 -> Pg=237.0, Qg=15.0\n% INFO : Gen at bus 23\t: Pg=245.0, Qg=62.5 -> Pg=323.0, Qg=15.0\n% INFO : \n% INFO : === Generator Reactive Capacity Atleast Setpoint Value Notes ===\n% INFO : Gen at bus 1\t: Qg 1.0, Qmin 0.0, Qmax 10.0 -> Qmin -1.2, Qmax 10.0\n% INFO : Gen at bus 1\t: Qg 1.0, Qmin 0.0, Qmax 10.0 -> Qmin -1.2, Qmax 10.0\n% INFO : Gen at bus 2\t: Qg 31.0, Qmin 0.0, Qmax 10.0 -> Qmin -37.2, Qmax 37.2\n% INFO : Gen at bus 2\t: Qg 31.0, Qmin 0.0, Qmax 10.0 -> Qmin -37.2, Qmax 37.2\n% INFO : Gen at bus 2\t: Qg 31.0, Qmin -25.0, Qmax 30.0 -> Qmin -37.2, Qmax 37.2\n% INFO : Gen at bus 2\t: Qg 31.0, Qmin -25.0, Qmax 30.0 -> Qmin -37.2, Qmax 37.2\n% INFO : Gen at bus 7\t: Qg 42.0, Qmin 0.0, Qmax 60.0 -> Qmin -50.4, Qmax 60.0\n% INFO : Gen at bus 7\t: Qg 42.0, Qmin 0.0, Qmax 60.0 -> Qmin -50.4, Qmax 60.0\n% INFO : Gen at bus 7\t: Qg 42.0, Qmin 0.0, Qmax 60.0 -> Qmin -50.4, Qmax 60.0\n% INFO : Gen at bus 13\t: Qg 105.0, Qmin 0.0, Qmax 80.0 -> Qmin -126.0, Qmax 126.0\n% INFO : Gen at bus 13\t: Qg 105.0, Qmin 0.0, Qmax 80.0 -> Qmin -126.0, Qmax 126.0\n% INFO : Gen at bus 13\t: Qg 105.0, Qmin 0.0, Qmax 80.0 -> Qmin -126.0, Qmax 126.0\n% INFO : Gen at bus 14\t: Qg 210.0, Qmin -50.0, Qmax 200.0 -> Qmin -252.0, Qmax 252.0\n% INFO : Gen at bus 15\t: Qg 79.0, Qmin 0.0, Qmax 6.0 -> Qmin -94.8, Qmax 94.8\n% INFO : Gen at bus 15\t: Qg 79.0, Qmin 0.0, Qmax 6.0 -> Qmin -94.8, Qmax 94.8\n% INFO : Gen at bus 15\t: Qg 79.0, Qmin 0.0, Qmax 6.0 -> Qmin -94.8, Qmax 94.8\n% INFO : Gen at bus 15\t: Qg 79.0, Qmin 0.0, Qmax 6.0 -> Qmin -94.8, Qmax 94.8\n% INFO : Gen at bus 15\t: Qg 79.0, Qmin 0.0, Qmax 6.0 -> Qmin -94.8, Qmax 94.8\n% INFO : Gen at bus 15\t: Qg 79.0, Qmin -50.0, Qmax 80.0 -> Qmin -94.8, Qmax 80.0\n% INFO : Gen at bus 21\t: Qg -118.0, Qmin -50.0, Qmax 200.0 -> Qmin -141.6, Qmax 200.0\n% INFO : \n% INFO : === Generator Classification Notes ===\n% INFO : PEL 4 - 6.70\n% INFO : SYNC 1 - 0.00\n% INFO : COW 7 - 23.79\n% INFO : NG 21 - 69.51\n% INFO : \n% INFO : === Generator Active Capacity Stat Model Notes ===\n% INFO : Gen at bus 1 - PEL\t: Pg=73.0, Pmax=20.0 -> Pmax=79 samples: 7\n% INFO : Gen at bus 1 - PEL\t: Pg=73.0, Pmax=20.0 -> Pmax=211 samples: 1\n% INFO : Gen at bus 1 - PEL\t: Pg=72.0, Pmax=76.0 -> Pmax=75 samples: 9\n% INFO : Gen at bus 1 - NG\t: Pg=72.0, Pmax=76.0 -> Pmax=78 samples: 2\n% INFO : Gen at bus 2 - NG\t: Pg=157.0, Pmax=20.0 -> Pmax=188 samples: 1\n% WARNING : Failed to find a generator capacity within (157.0-785.0) after 100 samples, using percent increase model\n% INFO : Gen at bus 2 - PEL\t: Pg=157.0, Pmax=20.0 -> Pmax=182 samples: 100\n% INFO : Gen at bus 2 - NG\t: Pg=156.0, Pmax=76.0 -> Pmax=176 samples: 1\n% INFO : Gen at bus 2 - COW\t: Pg=156.0, Pmax=76.0 -> Pmax=663 samples: 3\n% INFO : Gen at bus 7 - NG\t: Pg=126.0, Pmax=100.0 -> Pmax=430 samples: 2\n% INFO : Gen at bus 7 - NG\t: Pg=126.0, Pmax=100.0 -> Pmax=153 samples: 1\n% INFO : Gen at bus 7 - COW\t: Pg=126.0, Pmax=100.0 -> Pmax=595 samples: 1\n% INFO : Gen at bus 13 - NG\t: Pg=410.0, Pmax=197.0 -> Pmax=544 samples: 18\n% INFO : Gen at bus 13 - NG\t: Pg=410.0, Pmax=197.0 -> Pmax=542 samples: 17\n% INFO : Gen at bus 13 - COW\t: Pg=410.0, Pmax=197.0 -> Pmax=609 samples: 2\n% INFO : Gen at bus 14 - SYNC\t: Pg=0.0, Pmax=0.0 -> Pmax=0 samples: 0\n% INFO : Gen at bus 15 - NG\t: Pg=132.0, Pmax=12.0 -> Pmax=159 samples: 4\n% INFO : Gen at bus 15 - COW\t: Pg=132.0, Pmax=12.0 -> Pmax=206 samples: 2\n% INFO : Gen at bus 15 - NG\t: Pg=132.0, Pmax=12.0 -> Pmax=195 samples: 3\n% INFO : Gen at bus 15 - NG\t: Pg=132.0, Pmax=12.0 -> Pmax=162 samples: 10\n% INFO : Gen at bus 15 - NG\t: Pg=132.0, Pmax=12.0 -> Pmax=139 samples: 1\n% INFO : Gen at bus 15 - NG\t: Pg=184.0, Pmax=155.0 -> Pmax=206 samples: 1\n% WARNING : Failed to find a generator capacity within (522.0-2610.0) after 100 samples, using percent increase model\n% INFO : Gen at bus 16 - NG\t: Pg=522.0, Pmax=155.0 -> Pmax=589 samples: 100\n% INFO : Gen at bus 18 - NG\t: Pg=301.0, Pmax=400.0 -> Pmax=382 samples: 10\n% INFO : Gen at bus 21 - COW\t: Pg=203.0, Pmax=400.0 -> Pmax=675 samples: 2\n% INFO : Gen at bus 22 - NG\t: Pg=68.0, Pmax=50.0 -> Pmax=222 samples: 2\n% INFO : Gen at bus 22 - NG\t: Pg=68.0, Pmax=50.0 -> Pmax=184 samples: 1\n% INFO : Gen at bus 22 - NG\t: Pg=68.0, Pmax=50.0 -> Pmax=146 samples: 2\n% INFO : Gen at bus 22 - COW\t: Pg=68.0, Pmax=50.0 -> Pmax=233 samples: 1\n% INFO : Gen at bus 22 - NG\t: Pg=68.0, Pmax=50.0 -> Pmax=216 samples: 1\n% INFO : Gen at bus 22 - NG\t: Pg=68.0, Pmax=50.0 -> Pmax=83 samples: 1\n% INFO : Gen at bus 23 - NG\t: Pg=237.0, Pmax=155.0 -> Pmax=421 samples: 2\n% INFO : Gen at bus 23 - COW\t: Pg=237.0, Pmax=155.0 -> Pmax=292 samples: 3\n% INFO : Gen at bus 23 - NG\t: Pg=323.0, Pmax=350.0 -> Pmax=382 samples: 35\n% INFO : \n% INFO : === Generator Active Capacity LB Model Notes ===\n% INFO : Gen at bus 1\t: Pmin=16.0 -> Pmin=8.0 \n% INFO : Gen at bus 1\t: Pmin=16.0 -> Pmin=8.0 \n% INFO : Gen at bus 1\t: Pmin=15.2 -> Pmin=7.6 \n% INFO : Gen at bus 1\t: Pmin=15.2 -> Pmin=7.6 \n% INFO : Gen at bus 2\t: Pmin=16.0 -> Pmin=8.0 \n% INFO : Gen at bus 2\t: Pmin=16.0 -> Pmin=8.0 \n% INFO : Gen at bus 2\t: Pmin=15.2 -> Pmin=7.6 \n% INFO : Gen at bus 2\t: Pmin=15.2 -> Pmin=7.6 \n% INFO : Gen at bus 7\t: Pmin=25.0 -> Pmin=12.5 \n% INFO : Gen at bus 7\t: Pmin=25.0 -> Pmin=12.5 \n% INFO : Gen at bus 7\t: Pmin=25.0 -> Pmin=12.5 \n% INFO : Gen at bus 13\t: Pmin=69.0 -> Pmin=34.5 \n% INFO : Gen at bus 13\t: Pmin=69.0 -> Pmin=34.5 \n% INFO : Gen at bus 13\t: Pmin=69.0 -> Pmin=34.5 \n% INFO : Gen at bus 15\t: Pmin=2.4 -> Pmin=1.2 \n% INFO : Gen at bus 15\t: Pmin=2.4 -> Pmin=1.2 \n% INFO : Gen at bus 15\t: Pmin=2.4 -> Pmin=1.2 \n% INFO : Gen at bus 15\t: Pmin=2.4 -> Pmin=1.2 \n% INFO : Gen at bus 15\t: Pmin=2.4 -> Pmin=1.2 \n% INFO : Gen at bus 15\t: Pmin=54.3 -> Pmin=27.15 \n% INFO : Gen at bus 16\t: Pmin=54.3 -> Pmin=27.15 \n% INFO : Gen at bus 18\t: Pmin=100.0 -> Pmin=50.0 \n% INFO : Gen at bus 21\t: Pmin=100.0 -> Pmin=50.0 \n% INFO : Gen at bus 22\t: Pmin=10.0 -> Pmin=5.0 \n% INFO : Gen at bus 22\t: Pmin=10.0 -> Pmin=5.0 \n% INFO : Gen at bus 22\t: Pmin=10.0 -> Pmin=5.0 \n% INFO : Gen at bus 22\t: Pmin=10.0 -> Pmin=5.0 \n% INFO : Gen at bus 22\t: Pmin=10.0 -> Pmin=5.0 \n% INFO : Gen at bus 22\t: Pmin=10.0 -> Pmin=5.0 \n% INFO : Gen at bus 23\t: Pmin=54.3 -> Pmin=27.15 \n% INFO : Gen at bus 23\t: Pmin=54.3 -> Pmin=27.15 \n% INFO : Gen at bus 23\t: Pmin=140.0 -> Pmin=70.0 \n% INFO : \n% INFO : === Generator Reactive Capacity Atleast Max 50 Percent Active Model Notes ===\n% INFO : Gen at bus 1 - PEL\t: Pmax 79.0, Qmin -1.2, Qmax 10.0 -> Qmin -40.0, Qmax 40.0\n% INFO : Gen at bus 1 - PEL\t: Pmax 211.0, Qmin -1.2, Qmax 10.0 -> Qmin -106.0, Qmax 106.0\n% INFO : Gen at bus 1 - PEL\t: Pmax 75.0, Qmin -25.0, Qmax 30.0 -> Qmin -38.0, Qmax 38.0\n% INFO : Gen at bus 1 - NG\t: Pmax 78.0, Qmin -25.0, Qmax 30.0 -> Qmin -39.0, Qmax 39.0\n% INFO : Gen at bus 2 - NG\t: Pmax 188.0, Qmin -37.2, Qmax 37.2 -> Qmin -94.0, Qmax 94.0\n% INFO : Gen at bus 2 - PEL\t: Pmax 182.0, Qmin -37.2, Qmax 37.2 -> Qmin -91.0, Qmax 91.0\n% INFO : Gen at bus 2 - NG\t: Pmax 176.0, Qmin -37.2, Qmax 37.2 -> Qmin -88.0, Qmax 88.0\n% INFO : Gen at bus 2 - COW\t: Pmax 663.0, Qmin -37.2, Qmax 37.2 -> Qmin -332.0, Qmax 332.0\n% INFO : Gen at bus 7 - NG\t: Pmax 430.0, Qmin -50.4, Qmax 60.0 -> Qmin -215.0, Qmax 215.0\n% INFO : Gen at bus 7 - NG\t: Pmax 153.0, Qmin -50.4, Qmax 60.0 -> Qmin -77.0, Qmax 77.0\n% INFO : Gen at bus 7 - COW\t: Pmax 595.0, Qmin -50.4, Qmax 60.0 -> Qmin -298.0, Qmax 298.0\n% INFO : Gen at bus 13 - NG\t: Pmax 544.0, Qmin -126.0, Qmax 126.0 -> Qmin -272.0, Qmax 272.0\n% INFO : Gen at bus 13 - NG\t: Pmax 542.0, Qmin -126.0, Qmax 126.0 -> Qmin -271.0, Qmax 271.0\n% INFO : Gen at bus 13 - COW\t: Pmax 609.0, Qmin -126.0, Qmax 126.0 -> Qmin -305.0, Qmax 305.0\n% INFO : Gen at bus 15 - COW\t: Pmax 206.0, Qmin -94.8, Qmax 94.8 -> Qmin -103.0, Qmax 103.0\n% INFO : Gen at bus 15 - NG\t: Pmax 195.0, Qmin -94.8, Qmax 94.8 -> Qmin -98.0, Qmax 98.0\n% INFO : Gen at bus 15 - NG\t: Pmax 206.0, Qmin -94.8, Qmax 80.0 -> Qmin -103.0, Qmax 103.0\n% INFO : Gen at bus 16 - NG\t: Pmax 589.0, Qmin -50.0, Qmax 80.0 -> Qmin -295.0, Qmax 295.0\n% INFO : Gen at bus 18 - NG\t: Pmax 382.0, Qmin -50.0, Qmax 200.0 -> Qmin -191.0, Qmax 200.0\n% INFO : Gen at bus 21 - COW\t: Pmax 675.0, Qmin -141.6, Qmax 200.0 -> Qmin -338.0, Qmax 338.0\n% INFO : Gen at bus 22 - NG\t: Pmax 222.0, Qmin -10.0, Qmax 16.0 -> Qmin -111.0, Qmax 111.0\n% INFO : Gen at bus 22 - NG\t: Pmax 184.0, Qmin -10.0, Qmax 16.0 -> Qmin -92.0, Qmax 92.0\n% INFO : Gen at bus 22 - NG\t: Pmax 146.0, Qmin -10.0, Qmax 16.0 -> Qmin -73.0, Qmax 73.0\n% INFO : Gen at bus 22 - COW\t: Pmax 233.0, Qmin -10.0, Qmax 16.0 -> Qmin -117.0, Qmax 117.0\n% INFO : Gen at bus 22 - NG\t: Pmax 216.0, Qmin -10.0, Qmax 16.0 -> Qmin -108.0, Qmax 108.0\n% INFO : Gen at bus 22 - NG\t: Pmax 83.0, Qmin -10.0, Qmax 16.0 -> Qmin -42.0, Qmax 42.0\n% INFO : Gen at bus 23 - NG\t: Pmax 421.0, Qmin -50.0, Qmax 80.0 -> Qmin -211.0, Qmax 211.0\n% INFO : Gen at bus 23 - COW\t: Pmax 292.0, Qmin -50.0, Qmax 80.0 -> Qmin -146.0, Qmax 146.0\n% INFO : Gen at bus 23 - NG\t: Pmax 382.0, Qmin -25.0, Qmax 150.0 -> Qmin -191.0, Qmax 191.0\n% INFO : \n% INFO : === Generator Setpoint Replacement Notes ===\n% INFO : Gen at bus 1\t: Pg=73.0, Qg=1.0 -> Pg=43.5, Qg=0.0\n% INFO : Gen at bus 1\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 1\t: Pg=73.0, Qg=1.0 -> Pg=109.5, Qg=0.0\n% INFO : Gen at bus 1\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 1\t: Pg=72.0, Qg=1.0 -> Pg=41.3, Qg=0.0\n% INFO : Gen at bus 1\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 1\t: Pg=72.0, Qg=1.0 -> Pg=42.8, Qg=0.0\n% INFO : Gen at bus 1\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 2\t: Pg=157.0, Qg=31.0 -> Pg=98.0, Qg=0.0\n% INFO : Gen at bus 2\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 2\t: Pg=157.0, Qg=31.0 -> Pg=95.0, Qg=0.0\n% INFO : Gen at bus 2\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 2\t: Pg=156.0, Qg=31.0 -> Pg=91.8, Qg=0.0\n% INFO : Gen at bus 2\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 2\t: Pg=156.0, Qg=31.0 -> Pg=335.3, Qg=0.0\n% INFO : Gen at bus 2\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 7\t: Pg=126.0, Qg=42.0 -> Pg=221.25, Qg=0.0\n% INFO : Gen at bus 7\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 7\t: Pg=126.0, Qg=42.0 -> Pg=82.75, Qg=0.0\n% INFO : Gen at bus 7\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 7\t: Pg=126.0, Qg=42.0 -> Pg=303.75, Qg=0.0\n% INFO : Gen at bus 7\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 13\t: Pg=410.0, Qg=105.0 -> Pg=289.25, Qg=0.0\n% INFO : Gen at bus 13\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 13\t: Pg=410.0, Qg=105.0 -> Pg=288.25, Qg=0.0\n% INFO : Gen at bus 13\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 13\t: Pg=410.0, Qg=105.0 -> Pg=321.75, Qg=0.0\n% INFO : Gen at bus 13\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 14\t: Pg=0.0, Qg=210.0 -> Pg=0.0, Qg=0.0\n% INFO : Gen at bus 14\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 15\t: Pg=132.0, Qg=79.0 -> Pg=80.1, Qg=0.0\n% INFO : Gen at bus 15\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 15\t: Pg=132.0, Qg=79.0 -> Pg=103.6, Qg=0.0\n% INFO : Gen at bus 15\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 15\t: Pg=132.0, Qg=79.0 -> Pg=98.1, Qg=0.0\n% INFO : Gen at bus 15\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 15\t: Pg=132.0, Qg=79.0 -> Pg=81.6, Qg=0.0\n% INFO : Gen at bus 15\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 15\t: Pg=132.0, Qg=79.0 -> Pg=70.1, Qg=0.0\n% INFO : Gen at bus 15\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 15\t: Pg=184.0, Qg=79.0 -> Pg=116.575, Qg=0.0\n% INFO : Gen at bus 15\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 16\t: Pg=522.0, Qg=-34.0 -> Pg=308.075, Qg=0.0\n% INFO : Gen at bus 16\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 18\t: Pg=301.0, Qg=32.0 -> Pg=216.0, Qg=4.5\n% INFO : Gen at bus 18\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 21\t: Pg=203.0, Qg=-118.0 -> Pg=362.5, Qg=0.0\n% INFO : Gen at bus 21\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 22\t: Pg=68.0, Qg=-9.0 -> Pg=113.5, Qg=0.0\n% INFO : Gen at bus 22\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 22\t: Pg=68.0, Qg=-9.0 -> Pg=94.5, Qg=0.0\n% INFO : Gen at bus 22\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 22\t: Pg=68.0, Qg=-9.0 -> Pg=75.5, Qg=0.0\n% INFO : Gen at bus 22\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 22\t: Pg=68.0, Qg=-9.0 -> Pg=119.0, Qg=0.0\n% INFO : Gen at bus 22\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 22\t: Pg=68.0, Qg=-9.0 -> Pg=110.5, Qg=0.0\n% INFO : Gen at bus 22\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 22\t: Pg=68.0, Qg=-9.0 -> Pg=44.0, Qg=0.0\n% INFO : Gen at bus 22\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 23\t: Pg=237.0, Qg=15.0 -> Pg=224.075, Qg=0.0\n% INFO : Gen at bus 23\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 23\t: Pg=237.0, Qg=15.0 -> Pg=159.575, Qg=0.0\n% INFO : Gen at bus 23\t: Vg=1.0 -> Vg=1.0\n% INFO : Gen at bus 23\t: Pg=323.0, Qg=15.0 -> Pg=226.0, Qg=0.0\n% INFO : Gen at bus 23\t: Vg=1.0 -> Vg=1.0\n% INFO : \n% INFO : === Writing Matpower Case File Notes ===\n", "meta": {"author": "power-grid-lib", "repo": "pglib-opf", "sha": "01681386d084d8bd03b429abcd1ee6966f68b9a3", "save_path": "github-repos/MATLAB/power-grid-lib-pglib-opf", "path": "github-repos/MATLAB/power-grid-lib-pglib-opf/pglib-opf-01681386d084d8bd03b429abcd1ee6966f68b9a3/api/pglib_opf_case24_ieee_rts__api.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3741987033076742}} {"text": "function alpha_filter = getAlphaFilter(kgrid, medium, filter_cutoff, taper_ratio)\n%GETALPHAFILTER Create filter for medium.alpha_filter.\n%\n% DESCRIPTION:\n% getAlphaFilter uses getWin to create a Tukey window via rotation to\n% pass to the medium.alpha_filter input field of the first order\n% simulation functions (kspaceFirstOrder1D, kspaceFirstOrder2D, and\n% kspaceFirstOrder3D). This parameter is used to regularise time\n% reversal image reconstruction when absorption compensation is\n% included.\n% \n% USAGE:\n% alpha_filter = getAlphaFilter(kgrid, medium, filter_cutoff)\n% alpha_filter = getAlphaFilter(kgrid, medium, filter_cutoff, taper_ratio)\n% \n% INPUTS:\n% kgrid - k-Wave grid structure returned by makeGrid\n% medium - k-Wave medium structure\n% filter_cutoff - alpha_filter cutoff frequency [Hz], where\n% filter_cutoff = [f_all] in 1D \n% filter_cutoff = [f_all] or [f_x, f_y] in 2D \n% filter_cutoff = [f_all] or [f_x, f_y, f_z] in 3D\n%\n% Any of the filter_cutoff inputs may be set to\n% 'max' to set the cutoff frequency to the maximum\n% frequency supported by the grid\n%\n% OPTIONAL INPUTS\n% taper_ratio - taper ratio for Tukey Window (default = 0.5)\n% \n% OUTPUTS:\n% alpha_filter - filter\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 6th May 2010\n% last update - 28th October 2011\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% See also getWin\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\n% update the command line status\ndisp('Creating absorption filter...');\n\n% check to see if the taper ratio is given\nif nargin == 3\n taper_ratio = 0.5;\nelseif nargin ~= 4\n error('incorrect number of inputs');\nend\n\n% update command line status\ndisp([' taper ratio: ' num2str(taper_ratio)]);\n\n% extract the dimensions\ndim = numDim(kgrid.k);\n\n% extract the alpha_filter cutoff frequencies\nif numel(filter_cutoff) == 1\n filter_cutoff_x = filter_cutoff;\n if dim > 2\n filter_cutoff_z = filter_cutoff;\n end\n if dim > 1\n filter_cutoff_y = filter_cutoff; \n end\nelseif numel(filter_cutoff) ~= dim\n error(['input filter_cutoff must have 1 or ' num2str(dim) ' elements for a ' num2str(dim) 'D grid']);\nelse\n if dim == 1\n filter_cutoff_x = filter_cutoff{1};\n end\n if dim == 2\n filter_cutoff_x = filter_cutoff{1};\n filter_cutoff_y = filter_cutoff{2}; \n end \n if dim == 3\n filter_cutoff_x = filter_cutoff{1};\n filter_cutoff_y = filter_cutoff{2}; \n filter_cutoff_z = filter_cutoff{3}; \n end\nend\n\n% extract the maximium sound speed\nc = max(medium.sound_speed(:));\n\n% calculate the alpha_filter size in the z direction for 3D data\nif dim > 2\n if strcmp(filter_cutoff_z, 'max')\n % set the alpha_filter size to be the same as the grid size\n filter_size_z = kgrid.Nz;\n filter_cutoff_z = kgrid.kz_max*c/(2*pi);\n else\n % convert the cutoff frequency to a wavenumber\n k_cutoff_z = 2*pi*filter_cutoff_z ./ c;\n \n % set the alpha_filter size\n filter_size_z = round(kgrid.Nz*k_cutoff_z/kgrid.kz(end));\n \n % check the alpha_filter size\n if filter_size_z > kgrid.Nz\n % set the alpha_filter size to be the same as the grid size\n filter_size_z = kgrid.Nz; \n filter_cutoff_z = kgrid.kz_max*c/(2*pi);\n end \n end\nend\n\n% calculate the alpha_filter size in the y direction for 2 and 3D data\nif dim > 1\n if strcmp(filter_cutoff_y, 'max')\n % set the alpha_filter size to be the same as the grid size\n filter_size_y = kgrid.Ny;\n filter_cutoff_y = kgrid.ky_max*c/(2*pi);\n else\n % convert the cutoff frequency to a wavenumber\n k_cutoff_y = 2*pi*filter_cutoff_y ./ c;\n \n % set the alpha_filter size\n filter_size_y = round(kgrid.Ny*k_cutoff_y/kgrid.ky(end));\n \n % check the alpha_filter size\n if filter_size_y > kgrid.Ny\n % set the alpha_filter size to be the same as the grid size\n filter_size_y = kgrid.Ny;\n filter_cutoff_y = kgrid.ky_max*c/(2*pi);\n end\n end \nend\n\n% calculate the alpha_filter size in the x direction for 1, 2, and 3D data\nif strcmp(filter_cutoff_x, 'max')\n % set the alpha_filter size to be the same as the grid size\n filter_size_x = kgrid.Nx;\n filter_cutoff_x = kgrid.kx_max*c/(2*pi);\nelse\n % convert the cutoff frequency to a wavenumber\n k_cutoff_x = 2*pi*filter_cutoff_x ./ c;\n \n % set the alpha_filter size\n filter_size_x = round(kgrid.Nx*k_cutoff_x/kgrid.kx(end));\n \n % check the alpha_filter size\n if filter_size_x > kgrid.Nx\n % set the alpha_filter size to be the same as the grid size\n filter_size_x = kgrid.Nx;\n filter_cutoff_x = kgrid.kx_max*c/(2*pi);\n end \nend \n \n% create the alpha_filter using getWin\nswitch dim\n case 1\n % create the alpha_filter\n filter_sec = getWin(filter_size_x, 'Tukey', 'Param', taper_ratio, 'Rotation', true);\n\n % enlarge the alpha_filter to the size of the grid\n alpha_filter = zeros(kgrid.Nx, 1);\n x_index = round((kgrid.Nx - filter_size_x)/2) + 1;\n alpha_filter(x_index:x_index + filter_size_x - 1) = filter_sec; \n \n % update the command line status\n disp([' filter cutoff: ' scaleSI(filter_cutoff_x) 'Hz']);\n case 2\n % create the alpha_filter\n filter_sec = getWin([filter_size_x, filter_size_y], 'Tukey', 'Param', taper_ratio, 'Rotation', true);\n\n % enlarge the alpha_filter to the size of the grid\n alpha_filter = zeros(kgrid.Nx, kgrid.Ny);\n x_index = round((kgrid.Nx - filter_size_x)/2) + 1;\n y_index = round((kgrid.Ny - filter_size_y)/2) + 1;\n alpha_filter(x_index:x_index + filter_size_x - 1, y_index:y_index + filter_size_y - 1) = filter_sec; \n \n % update the command line status\n disp([' filter cutoff: ' scaleSI(filter_cutoff_x) 'Hz by ' scaleSI(filter_cutoff_y) 'Hz']); \n case 3\n % create the alpha_filter\n filter_sec = getWin([filter_size_x, filter_size_y, filter_size_z], 'Tukey', 'Param', taper_ratio, 'Rotation', true);\n\n % enlarge the alpha_filter to the size of the grid\n alpha_filter = zeros(kgrid.Nx, kgrid.Ny, kgrid.Nz);\n x_index = round((kgrid.Nx - filter_size_x)/2) + 1;\n y_index = round((kgrid.Ny - filter_size_y)/2) + 1;\n z_index = round((kgrid.Nz - filter_size_z)/2) + 1;\n alpha_filter(x_index:x_index + filter_size_x - 1, y_index:y_index + filter_size_y - 1, z_index:z_index + filter_size_z - 1) = filter_sec;\n \n % update the command line status\n disp([' filter cutoff: ' scaleSI(filter_cutoff_x) 'Hz by ' scaleSI(filter_cutoff_y) 'Hz by ' scaleSI(filter_cutoff_z) 'Hz']); \nend\n", "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/getAlphaFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3740948136963992}} {"text": "% LIONSIMBA example script\n% Multiple cells scenario: simulates three cells in serial connection.\n\n% This file is part of the LIONSIMBA Toolbox\n%\n%\tOfficial web-site: \thttp://sisdin.unipv.it/labsisdin/lionsimba.php\n% \tOfficial GitHUB: \thttps://github.com/lionsimbatoolbox/LIONSIMBA\n%\n% LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control\n% Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,\n% University of Pavia, 27100, Pavia, Italy\n% Bhushan Gopaluni, Univ. of British Columbia, \n% Vancouver, BC V6T 1Z3, Canada\n% Richard D. Braatz, \n% Massachusetts Institute of Technology, \n% Cambridge, Massachusetts 02142, USA\n% \n% Main code contributors to LIONSIMBA 2.0:\n% Ian Campbell, Krishnakumar Gopalakrishnan,\n% Imperial college London, London, UK\n%\n% LIONSIMBA is a free Matlab-based software distributed with an MIT\n% license.\n\n% Clear the workspace\nclear\n\n% Define the integration times.\nt0 = 0;\ntf = 10^4;\n% Define the parameters structure.\nparam{1} = Parameters_init;\nparam{2} = Parameters_init;\nparam{3} = Parameters_init;\n\n% Modify the initial SOC of cell #1\nparam{1}.cs_n_init = 0.95*param{1}.cs_n_init;\n\n% Double the length of the positive electrode of cell #2\nparam{2}.len_p=2*param{2}.len_p;\n\n% Simulate the battery of 3 cells\nresults = startSimulation(t0,tf,[],-30,param);\n\nncells = length(param);\n\nv_tot = 0;\nfor i=1:ncells\n v_tot = v_tot + results.Phis{i}(:,1)-results.Phis{i}(:,end);\nend\n%% Plot the results\n\nfigure(1)\nsubplot(2,ncells,(1:ncells))\nplot(results.time{1},v_tot,'LineWidth',6)\ngrid on\nbox on\nxlabel('Time [s]')\nylabel('Pack Voltage [V]')\nhold on\nxlim([0 results.time{1}(end)])\nylim([2.5*length(param) 4.2*length(param)])\n\nfigure_index = ncells+1;\nfor i=1:ncells\n subplot(2,ncells,figure_index)\n plot(results.time{i},results.Voltage{i},'--','LineWidth',3)\n grid on\n box on\n xlabel('Time [s]')\n ylabel(['Cell #',num2str(i),' Voltage [V]'])\n figure_index = figure_index+1;\n ylim([2.5 4.2])\n xlim([0 results.time{1}(end)])\nend\n\nn_plots = 1;\nfigure_index = 1;\nfigure(2)\nfor i=1:ncells\n subplot(ncells,n_plots,figure_index)\n ce_indices = [1 results.parameters{i}.Np+1 results.parameters{i}.Np+results.parameters{i}.Ns results.parameters{i}.Np+results.parameters{i}.Ns+results.parameters{i}.Nn];\n plot(results.time{i},results.ce{i}(:,ce_indices),'LineWidth',3)\n grid on\n box on\n if(figure_index==ncells)\n xlabel('Time [s]')\n else\n% set(gca,'xtick',[])\n set(gca,'xticklabel',[])\n end\n ylabel(['Cell #',num2str(i),' - c_{e} [mol/m^3}'])\n xlim([0 results.time{1}(end)])\n ylim([0 2200])\n figure_index = figure_index+1;\nend\n\n\nn_plots = 1;\nfigure_index = 1;\nfigure(3)\nfor i=1:ncells\n subplot(ncells,n_plots,figure_index)\n phie_indices = [1 results.parameters{i}.Np+1 results.parameters{i}.Np+results.parameters{i}.Ns results.parameters{i}.Np+results.parameters{i}.Ns+results.parameters{i}.Nn];\n plot(results.time{i},results.Phie{i}(:,phie_indices),'LineWidth',3)\n grid on\n box on\n if(figure_index==ncells)\n xlabel('Time [s]')\n else\n% set(gca,'xtick',[])\n set(gca,'xticklabel',[])\n end\n ylabel(['Cell #',num2str(i)])\n xlim([0 results.time{1}(end)])\n ylim([-0.3 0])\n figure_index = figure_index+1;\nend\n\n\nn_plots = 1;\nfigure_index = 1;\nfigure(4)\nfor i=1:ncells\n subplot(ncells,n_plots,figure_index)\n cs_indices = [1 results.parameters{i}.Np results.parameters{i}.Np+1 results.parameters{i}.Np+results.parameters{i}.Nn];\n plot(results.time{i},results.cs_surface{i}(:,cs_indices),'LineWidth',3)\n grid on\n box on\n if(figure_index==ncells)\n xlabel('Time [s]')\n else\n% set(gca,'xtick',[])\n set(gca,'xticklabel',[])\n end\n ylabel(['Cell #',num2str(i)])\n xlim([0 results.time{1}(end)])\n ylim([100 51554])\n figure_index = figure_index+1;\nend\n\n\nn_plots = 1;\nfigure_index = 1;\nfigure(5)\nfor i=1:ncells\n subplot(ncells,n_plots,figure_index)\n cs_indices = [1 results.parameters{i}.Np results.parameters{i}.Np+1 results.parameters{i}.Np+results.parameters{i}.Nn];\n plot(results.time{i},results.Temperature{i}(:,end),'LineWidth',3)\n grid on\n box on\n if(figure_index==ncells)\n xlabel('Time [s]')\n else\n% set(gca,'xtick',[])\n set(gca,'xticklabel',[])\n end\n ylabel(['Cell #',num2str(i),' - Temp [K]'])\n xlim([0 results.time{1}(end)])\n ylim([296 315])\n figure_index = figure_index+1;\nend\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/example_scripts/multipleCells.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.37396079428061463}} {"text": "function [Flux, FBAsolution, model] = testPathway(model, MetIn, MetOut, AdditionalMetsInorOut, ObjectiveOption)\n% Allows the user to see if given one metabolite `A`,\n% downstream metabolite `B` can be made made. Additional sinks can be added\n% for co-factors if needed\n% `A -->-->-->-->--> B`\n%\n% USAGE:\n%\n% [Flux, FBAsolution, model] = testPathway(model, MetIn, MetOut, AdditionalMetsInorOut, ObjectiveOption)\n%\n% INPUTS:\n% model: COBRA model structure\n% MetIn: The input metabolite(s) (`A`)\n% MetOut: The output metabolite (`B`)\n%\n% OPTIONAL INPUTS:\n% AdditionalMetsInorOut: Additional metabolites for which sinks will be added\n% ObjectiveOption: Boolean:\n%\n% * 1 = objective will be production of `B` (default)\n% * 0 = use objective in model\n%\n% OUTPUTS:\n% Flux: The rate of `B` production\n% FBAsolution: Solution to the FBA problem\n% model: COBRA model with sinks in it\n%\n% .. Author: Nathan Lewis, Feb 16 2009\n\nif ~iscell(MetIn)\n Met = MetIn; clear MetIn; MetIn{1} = Met;\nend\nif ~iscell(MetOut)\n Met = MetOut; clear MetOut; MetOut{1} = Met;\nend\nif nargin > 3\n if ~iscell(AdditionalMetsInorOut)\n Met = AdditionalMetsInorOut; clear AdditionalMetsInorOut; AdditionalMetsInorOut{1} = Met;\n end\n % add sink rxns for all AdditionalMetsInorOut\n for i = 1:length(AdditionalMetsInorOut)\n model = addReaction(model,cat(2,'Tempsink_',AdditionalMetsInorOut{i}),{AdditionalMetsInorOut{i} },-1 ,true);\n end\nend\nif nargin <5,ObjectiveOption=1;end\n\nfor i = 1:length(MetIn) % add inputs\n model = addReaction(model,cat(2,'TempInput_',MetIn{i}),{MetIn{i} },1 ,false);\nend\n[model, rxnExists] = addReaction(model,cat(2,'TempOutput_',MetOut{1}),{MetOut{1} },-1 ,false);\nif (ObjectiveOption==1 && isempty(rxnExists))\n\tmodel = changeObjective(model,cat(2,'TempOutput_',MetOut{1}));\nelseif (ObjectiveOption == 1 && ~isempty(rxnExists))\n\tmodel = changeObjective(model,model.rxns(rxnExists));\nend\nFBAsolution = optimizeCbModel(model,'max');\nFlux = FBAsolution.f;\nif ~isempty(FBAsolution.x)\n%printFluxVector(model,FBAsolution.x);\nelse display('zero flux in network')\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/reconstruction/testPathway.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.37387750463714753}} {"text": "% Monopole Point Source In A Homogeneous Propagation Medium Example\n%\n% This example provides a simple demonstration of using k-Wave for the\n% simulation and detection of a time varying pressure source within a\n% two-dimensional homogeneous propagation medium. It builds on the\n% Homogeneous Propagation Medium and Recording The Particle Velocity\n% examples.\n%\n% author: Bradley Treeby\n% date: 2nd December 2009\n% last update: 2nd 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 = 50e-3/Nx; \t% grid point spacing in the x direction [m]\ndy = dx; % 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; % [m/s]\nmedium.alpha_coeff = 0.75; % [dB/(MHz^y cm)]\nmedium.alpha_power = 1.5; \n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\n\n% define a single source point\nsource.p_mask = zeros(Nx, Ny);\nsource.p_mask(end - Nx/4, Ny/2) = 1;\n\n% define a time varying sinusoidal source\nsource_freq = 0.25e6; % [Hz]\nsource_mag = 2; % [Pa]\nsource.p = source_mag*sin(2*pi*source_freq*kgrid.t_array);\n\n% filter the source to remove high frequencies not supported by the grid\nsource.p = filterTimeSeries(kgrid, medium, source.p);\n\n% define a single sensor point\nsensor.mask = zeros(Nx, Ny);\nsensor.mask(Nx/4, Ny/2) = 1;\n\n% define the acoustic parameters to record\nsensor.record = {'p', 'p_final'};\n\n% run the simulation\nsensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor);\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the final wave-field\nfigure;\nimagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_final + source.p_mask + sensor.mask, [-1 1]);\ncolormap(getColorMap);\nylabel('x-position [mm]');\nxlabel('y-position [mm]');\naxis image;\n\n% plot the simulated sensor data\nfigure;\n[t_sc, scale, prefix] = scaleSI(max(kgrid.t_array(:)));\n\nsubplot(2, 1, 1), plot(kgrid.t_array*scale, source.p, 'k-');\nxlabel(['Time [' prefix 's]']);\nylabel('Signal Amplitude');\naxis tight;\ntitle('Input Pressure Signal');\n\nsubplot(2, 1, 2), plot(kgrid.t_array*scale, sensor_data.p, 'r-');\nxlabel(['Time [' prefix 's]']);\nylabel('Signal Amplitude');\naxis tight;\ntitle('Sensor Pressure Signal');", "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_tvsp_homogeneous_medium_monopole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.37375755071241346}} {"text": "function p = prior_loggaussian(varargin)\n%PRIOR_LOGGAUSSIAN Log-Gaussian prior structure \n% \n% Description\n% P = PRIOR_LOGGAUSSIAN('PARAM1', VALUE1, 'PARAM2', VALUE2, ...) \n% creates Log-Gaussian prior structure in which the named\n% parameters have the specified values. Any unspecified\n% parameters are set to default values.\n% \n% P = PRIOR_LOGGAUSSIAN(P, 'PARAM1', VALUE1, 'PARAM2', VALUE2, ...)\n% modify a prior structure with the named parameters altered\n% with the specified values.\n%\n% Parameters for Log-Gaussian prior [default]\n% mu - location [0]\n% s2 - scale squared (variance) [1]\n% mu_prior - prior for mu [prior_fixed]\n% s2_prior - prior for s2 [prior_fixed]\n%\n% See also\n% PRIOR_*\n%\n% Copyright (c) 2000-2001,2010 Aki Vehtari\n% Copyright (c) 2010 Jaakko Riihimäki\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 = 'PRIOR_LOGGAUSSIAN';\n ip.addOptional('p', [], @isstruct);\n ip.addParamValue('mu',0, @(x) isscalar(x));\n ip.addParamValue('mu_prior',[], @(x) isstruct(x) || isempty(x));\n ip.addParamValue('s2',1, @(x) isscalar(x) && x>0);\n ip.addParamValue('s2_prior',[], @(x) isstruct(x) || isempty(x));\n ip.parse(varargin{:});\n p=ip.Results.p;\n \n if isempty(p)\n init=true;\n p.type = 'Log-Gaussian';\n else\n if ~isfield(p,'type') && ~isequal(p.type,'Log-Gaussian')\n error('First argument does not seem to be a valid prior structure')\n end\n init=false;\n end\n\n % Initialize parameters\n if init || ~ismember('mu',ip.UsingDefaults)\n p.mu = ip.Results.mu;\n end\n if init || ~ismember('s2',ip.UsingDefaults)\n p.s2 = ip.Results.s2;\n end\n % Initialize prior structure\n if init\n p.p=[];\n end\n if init || ~ismember('mu_prior',ip.UsingDefaults)\n p.p.mu=ip.Results.mu_prior;\n end\n if init || ~ismember('s2_prior',ip.UsingDefaults)\n p.p.s2=ip.Results.s2_prior;\n end\n\n if init\n % set functions\n p.fh.pak = @prior_loggaussian_pak;\n p.fh.unpak = @prior_loggaussian_unpak;\n p.fh.lp = @prior_loggaussian_lp;\n p.fh.lpg = @prior_loggaussian_lpg;\n p.fh.recappend = @prior_loggaussian_recappend;\n end\n\nend\n\nfunction [w, s, h] = prior_loggaussian_pak(p)\n \n w=[];\n s={};\n h=[];\n if ~isempty(p.p.mu)\n w = p.mu;\n s=[s; 'Log-Gaussian.mu'];\n h = 1;\n end\n if ~isempty(p.p.s2)\n w = [w log(p.s2)];\n s=[s; 'log(Log-Gaussian.s2)'];\n h = [h 1];\n end\nend\n\nfunction [p, w] = prior_loggaussian_unpak(p, w)\n\n if ~isempty(p.p.mu)\n i1=1;\n p.mu = w(i1);\n w = w(i1+1:end);\n end\n if ~isempty(p.p.s2)\n i1=1;\n p.s2 = exp(w(i1));\n w = w(i1+1:end);\n end\nend\n\nfunction lp = prior_loggaussian_lp(x, p)\n \n lJ = -log(x); % =log(1/x)=log(|J|) of transformation\n xt = log(x); % transformed x\n lp = 0.5*sum(-log(2*pi) -log(p.s2)- 1./p.s2 .* sum((xt-p.mu).^2,1)) +sum(lJ);\n \n if ~isempty(p.p.mu)\n lp = lp + p.p.mu.fh.lp(p.mu, p.p.mu);\n end\n if ~isempty(p.p.s2)\n lp = lp + p.p.s2.fh.lp(p.s2, p.p.s2) + log(p.s2);\n end\nend\n\nfunction lpg = prior_loggaussian_lpg(x, p)\n \n lJg = -1./x; % gradient of log(|J|) of transformation\n xt = log(x); % transformed x\n xtg = 1./x; % derivative of transformation\n lpg = xtg.*(1./p.s2).*(p.mu-xt) + lJg;\n \n if ~isempty(p.p.mu)\n lpgmu = sum((1./p.s2).*(xt-p.mu)) + p.p.mu.fh.lpg(p.mu, p.p.mu);\n lpg = [lpg lpgmu];\n end\n if ~isempty(p.p.s2)\n lpgs2 = (sum(-0.5*(1./p.s2-1./p.s2.^2.*(xt-p.mu).^2 )) + p.p.s2.fh.lpg(p.s2, p.p.s2)).*p.s2 + 1;\n lpg = [lpg lpgs2];\n end\nend\n\nfunction rec = prior_loggaussian_recappend(rec, ri, p)\n% The parameters are not sampled in any case.\n rec = rec;\n if ~isempty(p.p.mu)\n rec.mu(ri,:) = p.mu;\n end\n if ~isempty(p.p.s2)\n rec.s2(ri,:) = p.s2;\n end\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/dist/prior_loggaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.3737012020246673}} {"text": "%\n%\n% DIFFERENTIAL SEARCH ALGORITHM (DSA) (in MATLAB)\n% STANDARD VERSION of DSA (16.July.2013)\n%\n%\n% usage : > ds(method,fnc,mydata,popsize,dim,low,up,maxcycle)\n%\n% method\n%--------------------------------------------------------------\n% 1: Bijective DSA (B-DSA)\n% 2: Surjective DSA (S-DSA)\n% 3: Elitist DSA (strategy 1) (E1-DSA)\n% 4: Elitist DSA (strategy 2) (E2-DSA)\n% if method=[. . . ...], Hybrid-DSA (H-DSA)\n%--------------------------------------------------------------\n% example : \n% ds(1,'circlefit',mydata,10,3,-10,10,2000) ; % B-DSA\n% ds(2,'circlefit',mydata,10,3,-10,10,2000) ; % S-DSA\n% ds(3,'circlefit',mydata,10,3,-10,10,2000) ; % E1-DSA\n% ds(4,'circlefit',mydata,10,3,-10,10,2000) ; % E2-DSA\n% ds([1 2],'circlefit',mydata,10,3,-10,10,2000) ; % Hybrid-DSA, in this case B-DSA and S-DSA are hybridized.\n%--------------------------------------------------------------\n% Please cite this article as;\n% P.Civicioglu, \"Transforming geocentric cartesian coordinates to geodetic coordinates by using differential search algorithm\", Computers & Geosciences, 46 (2012), 229-247.\n% P.Civicioglu, \"Understanding the nature of evolutionary search algorithms\", Additional technical report for the project of 110Y309-Tubitak,2013, Ankara, Turkey.\n%\n% \n%\n%\n%--------------------------------------------------------------\n%{\n19.March.2013\nCopyright Notice\nCopyright (c) 2012, Pinar Civicioglu\nAll rights reserved.\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution\n \nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n%}\n\n\nfunction ds(method,fnc,mydata,size_of_superorganism,size_of_one_clan,low_habitat_limit,up_habitat_limit,epoch)\n\n% size_of_superorganism ; size of population.\n% size_of_one_clan ; size of problem dimension (1,2,3,...,d), where each clan (i.e. sub-superorganism) includes d-individuals.\n% mydata ; additional parameters for objective function, use mydata=[], if it is not needed. See Best-Fit Circle example (circlefit.m) for usage of mydata.\n\n%Initialization\n\n% control of habitat limits\nif numel(low_habitat_limit)==1,\n low_habitat_limit=low_habitat_limit*ones(1,size_of_one_clan);\n up_habitat_limit=up_habitat_limit*ones(1,size_of_one_clan);\nend\n\n\n% generate initial individuals, clans and superorganism.\nsuperorganism=genpop(size_of_superorganism,size_of_one_clan,low_habitat_limit,up_habitat_limit);\n% success of clans/superorganism\nfit_superorganism=feval(fnc,superorganism,mydata);\n\n\nfor epk=1:epoch\n \n\n % SETTING OF ALGORITHMIC CONTROL PARAMETERS\n % Trial-pattern generation strategy for morphogenesis; 'one-by-one morphogenesis'. \n % p1=0.0*rand; % i.e., 0.0 <= p1 <= 0.0\n % p2=0.0*rand; % i.e., 0.0 <= p2 <= 0.0\n \n % Trial-pattern generation strategy for morphogenesis; 'one-or-more morphogenesis'. (DEFAULT)\n p1=0.3*rand; % i.e., 0.0 <= p1 <= 0.3\n p2=0.3*rand; % i.e., 0.0 <= p2 <= 0.3\n \n %-------------------------------------------------------------------\n \n [direction,msg]=generate_direction(method(randi(numel(method))),superorganism,size_of_superorganism,fit_superorganism);\n \n map=generate_map_of_active_individuals(size_of_superorganism,size_of_one_clan,p1,p2);\n \n %-------------------------------------------------------------------\n % Recommended Methods for generation of Scale-Factor; R \n % R=4*randn; % brownian walk\n % R=4*randg; % brownian walk\n % R=lognrnd(rand,5*rand); % brownian walk\n R=1./gamrnd(1,0.5); % pseudo-stable walk\n % R=1/normrnd(0,5); % pseudo-stable walk\n\n %-------------------------------------------------------------------\n \n % bio-interaction (morphogenesis) \n stopover=superorganism+(R.*map).*(direction-superorganism);\n\n\n % Boundary Control\n stopover=update(stopover,low_habitat_limit,up_habitat_limit); \n \n % Selection-II\n fit_stopover=feval(fnc,stopover,mydata);\n ind=fit_stopover %10.16f\\n',msg,epk,globalminimum)\n \nend\n\n\nfunction pop=genpop(a,b,low,up)\npop=ones(a,b);\nfor i=1:a\n for j=1:b \n pop(i,j)=rand*(up(j)-low(j))+low(j);\n end\nend\n\n\nfunction p=update(p,low,up)\n[popsize,dim]=size(p);\nfor i=1:popsize\n for j=1:dim\n % first (standard)-method\n if p(i,j)up(j), if randup(j), p(i,j)=rand*(up(j)-low(j))+low(j); end\n else\n if p(i,j)up(j), p(i,j)=up(j); end \n end\n %}\n end \nend\n\n\nfunction [direction,msg]=generate_direction(method,superorganism,size_of_superorganism,fit_superorganism);\n switch method\n case 1, \n % BIJECTIVE DSA (B-DSA) (i.e., go-to-rnd DSA); \n % philosophy: evolve the superorganism (i.e.,population) towards to \"permuted-superorganism (i.e., random directions)\" \n direction=superorganism(randperm(size_of_superorganism),:); msg=' B-DSA';\n case 2, \n % SURJECTIVE DSA (S-DSA) (i.e., go-to-good DSA)\n % philosophy: evolve the superorganism (i.e.,population) towards to \"some of the random top-best\" solutions\n ind=ones(size_of_superorganism,1); \n [null_,B]=sort(fit_superorganism); \n for i=1:size_of_superorganism, ind(i)=B(randi(ceil(rand*size_of_superorganism),1)); end; \n direction=superorganism(ind,:); msg=' S-DSA'; \n case 3,\n % ELITIST DSA #1 (E1-DSA) (i.e., go-to-best DSA)\n % philosophy: evolve the superorganism (i.e.,population) towards to \"one of the random top-best\" solution\n [null,jind]=sort(fit_superorganism); ibest=jind(ceil(rand*size_of_superorganism)); msg='E1-DSA'; \n direction=repmat(superorganism(ibest,:),[size_of_superorganism 1]); \n case 4,\n % ELITIST DSA #2 (E2-DSA) (i.e., go-to-best DSA)\n % philosophy: evolve the superorganism (i.e.,population) towards to \"the best\" solution\n [null_,ibest]=min(fit_superorganism); msg='E2-DSA';\n direction=repmat(superorganism(ibest,:),[size_of_superorganism 1]); \n end\nreturn\n \n \nfunction map=generate_map_of_active_individuals(size_of_superorganism,size_of_one_clan,p1,p2);\n % strategy-selection of active/passive individuals\n map=zeros(size_of_superorganism,size_of_one_clan);\n if rand 8) \n corrector = 1; \n else \n corrector = 0; \n hRd = zeros(m,1); \n end \n hEinvRc = zeros(m,1); \n EinvRc = cell(size(blk,1),1); \n rhsfree = []; \n%%\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n n = sum(pblk{2}); numblk = length(pblk{2}); \n if strcmp(pblk{1},'l')\n\t if iscell(sigmu)\n EinvRc{p} = sigmu{p}./Z{p} -X{p};\n\t else\n EinvRc{p} = sigmu./Z{p} -X{p};\n end\n Rq = sparse(n,1); \n if (corrector) & (norm(par.parbarrier{p})==0)\n Rq = dX{p}.*dZ{p}./Z{p}; \n else\n tmp = par.dd{p}.*Rd{p};\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n\t EinvRc{p} = EinvRc{p} - Rq; \n tmp2 = mexMatvec(At{p},EinvRc{p},1); \n hEinvRc = hEinvRc + tmp2;\n\telseif strcmp(pblk{1},'q') \n\t if iscell(sigmu)\n EinvRc{p} = qops(pblk,-sigmu{p}./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};\n\t else\n EinvRc{p} = qops(pblk,-sigmu./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};\n end\n Rq = sparse(n,1); \n \t if (corrector) & (norm(par.parbarrier{p})==0)\n w = sqrt(par.gamz{p}./par.gamx{p}); \n hdx = qops(pblk,w,par.ff{p},5,dX{p}); \n hdz = qops(pblk,w,par.ff{p},6,dZ{p}); \n hdxdz = Arrow(pblk,hdx,hdz);\n vv = qops(pblk,w,par.ff{p},5,X{p}); \n Vihdxdz = Arrow(pblk,vv,hdxdz,1); \n Rq = qops(pblk,w,par.ff{p},6,Vihdxdz); \n else\n tmp = par.dd{p}.*Rd{p} + qops(pblk,qops(pblk,Rd{p},par.ee{p},1),par.ee{p},3);\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n\t EinvRc{p} = EinvRc{p} - Rq; \n tmp2 = mexMatvec(At{p},EinvRc{p},1); \n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'s') \n n2 = pblk{2}.*(pblk{2}+1)/2; \n\t if iscell(sigmu)\n \t %%ss = [0,cumsum(pblk{2})]; \n %%sigmuvec = zeros(n,1); \n %%for k = 1:length(pblk{2}); \n %% sigmuvec(ss(k)+1:ss(k+1)) = sigmu{p}(k)*ones(pblk{2}(k),1); \n %%end\n sigmuvec = mexexpand(pblk{2},sigmu{p}); \n tmp = spdiags(sigmuvec./par.sv{p} -par.sv{p},0,n,n);\n else\n tmp = spdiags(sigmu./par.sv{p} -par.sv{p},0,n,n);\n end\n EinvRc{p} = Prod3(pblk,par.G{p}',tmp,par.G{p},1);\n Rq = sparse(n,n); \n if (corrector) & (norm(par.parbarrier{p})==0)\n hdZ = Prod3(pblk,par.G{p},dZ{p},par.G{p}',1); \n hdX = spdiags(qops(pblk,par.parbarrier{p}',1./par.sv{p},3)-par.sv{p},0,n,n)-hdZ; \n tmp = Prod2(pblk,hdX,hdZ,0); \n tmp = 0.5*(tmp+tmp');\n if (numblk == 1) \n d = par.sv{p};\n e = ones(pblk{2},1); \n Rq = 2*tmp./(d*e'+e*d'); \n if (nnz(Rq) <= spdensity*n2); Rq = sparse(Rq); end \n else\n Rq = sparse(n,n);\n ss = [0, cumsum(pblk{2})]; \n for i = 1:numblk\n pos = [ss(i)+1 : ss(i+1)]; \n d = par.sv{p}(pos); e = ones(length(pos),1); \n Rq(pos,pos) = 2*tmp(pos,pos)./(d*e' + e*d'); \n end\n end\n Rq = Prod3(pblk,par.G{p}',Rq,par.G{p},1);\n else\n tmp = Prod3(pblk,par.W{p},Rd{p},par.W{p},1,par.nzlistAy{p});\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp}); \n hRd = hRd + tmp2;\n end \n EinvRc{p} = EinvRc{p} - Rq; \n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p)); \n hEinvRc = hEinvRc + tmp2; \n elseif strcmp(pblk{1},'u') \n rhsfree = [rhsfree; Rd{p}]; \n end \n end\n%% \n rhs = rp + hRd - hEinvRc; \n rhs = full([rhs; rhsfree]); \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/NTrhsfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.37332510877577235}} {"text": "%% pathRRT\n%% - create a path from a start node to an end node\n%% using the RRT algorithm.\n%% - RRT = Rapidly-exploring Random Tree\n%% \n%% Last Modified - 6/8/2006 - R. Beard\n%% - 4/15/2010 - R. Beard\n\nfunction path_out=planRRT(wpp_start, wpp_end, map)\n\n % standard length of path segments\n segmentLength = 100;\n\n % desired down position is down position of end node\n pd = wpp_end(3);\n chi = -9999;\n \n % specify start and end nodes from wpp_start and wpp_end\n start_node = [wpp_start(1), wpp_start(2), pd, chi, 0, 0, 0];\n end_node = [wpp_end(1), wpp_end(2), pd, chi, 0, 0, 0];\n % format: [N, E, D, chi, cost, parent_idx, flag_connect_to_goal]\n\n % establish tree starting with the start node\n tree = start_node;\n \n % check to see if start_node connects directly to end_node\n if ( (norm(start_node(1:3)-end_node(1:3))= downAtNE(map, X(i), Y(i)),\n collision_flag = 1;\n end\n end\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% pointsAlongPath\n%% Find points along straight-line path separted by Del (to be used in\n%% collision detection)\nfunction [X,Y,Z] = pointsAlongPath(start_node, end_node, Del)\n\n X = [start_node(1)];\n Y = [start_node(2)];\n Z = [start_node(3)];\n \n q = [end_node(1:3)-start_node(1:3)];\n L = norm(q);\n q = q/L;\n \n w = start_node(1:3);\n for i=2:floor(L/Del),\n w = w + Del*q;\n X = [X, w(1)];\n Y = [Y, w(2)];\n Z = [Z, w(3)];\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% downAtNE\n%% find the world down coordinate at a specified (n,e) location\nfunction down = downAtNE(map, n, e)\n\n [d_n,idx_n] = min(abs(n - map.buildings_n));\n [d_e,idx_e] = min(abs(e - map.buildings_e));\n\n if (d_n<=map.BuildingWidth) && (d_e<=map.BuildingWidth),\n down = -map.heights(idx_e,idx_n);\n else\n down = 0;\n end\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% extendTree\n%% extend tree by randomly selecting point and growing tree toward that\n%% point\nfunction [new_tree,flag] = extendTree(tree,end_node,segmentLength,map,pd,chi)\n\n flag1 = 0;\n loop_count = 0;\n while flag1==0,\n % select a random point\n randomNode=generateRandomNode(map,pd,chi);\n \n % find leaf on node that is closest to randomPoint\n tmp = tree(:,1:3)-ones(size(tree,1),1)*randomNode(1:3);\n [dist,idx] = min(diag(tmp*tmp'));\n L = min(sqrt(dist), segmentLength); \n cost = tree(idx,5) + L;\n tmp = randomNode(1:3)-tree(idx,1:3);\n new_point = tree(idx,1:3)+L*(tmp/norm(tmp));\n new_node = [new_point, chi, cost, idx, 0]; \n loop_count = loop_count+1\n if collision(tree(idx,:), new_node, map)==0,\n new_tree = [tree; new_node];\n flag1=1;\n end\n end\n \n % check to see if new node connects directly to end_node\n if ( (norm(new_node(1:3)-end_node(1:3))1,\n parent_node = tree(parent_node,6);\n path = [tree(parent_node,:); path];\n end\n \nend\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% smoothPath\n%% smooth the waypoint path \nfunction newPath = smoothPath(path,map)\n\n newPath = path(1,:); % add the start node \n ptr =2; % pointer into the path\n while ptr <= size(path,1)-1,\n if collision(newPath(end,:), path(ptr+1,:), map)~=0, % if there is a collision\n newPath = [newPath; path(ptr,:)]; % add previous node\n end\n ptr=ptr+1;\n end\n newPath = [newPath; path(end,:)];\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% plotmap\n%% plot obstacles and path\nfunction plotmap(map,path,smoothedPath,tree)\n \n % setup plot\n figure(3), clf\n axis([0,map.width,0,map.width,0,2*map.MaxHeight]);\n xlabel('E')\n ylabel('N')\n zlabel('h')\n hold on\n \n % plot buildings \n V = [];\n F = [];\n patchcolors = [];\n count = 0;\n for i=1:map.NumBlocks,\n for j=1:map.NumBlocks,\n [Vtemp,Ftemp,patchcolorstemp] = buildingVertFace(map.buildings_n(i),...\n map.buildings_e(j),map.BuildingWidth,map.heights(j,i));\n V = [V; Vtemp];\n Ftemp = Ftemp + count;\n F = [F; Ftemp];\n count = count + 8;\n patchcolors = [patchcolors;patchcolorstemp];\n end\n end\n \n patch('Vertices', V, 'Faces', F,...\n 'FaceVertexCData',patchcolors,...\n 'FaceColor','flat');\n \n % draw tree\n for i=2:size(tree,1),\n X = [tree(i,1), tree(tree(i,6),1)];\n Y = [tree(i,2), tree(tree(i,6),2)]; \n Z = [tree(i,3), tree(tree(i,6),3)]; \n plot3(Y,X,-Z,'g')\n end\n \n % draw path\n X = path(:,1);\n Y = path(:,2);\n Z = path(:,3);\n plot3(Y,X,-Z,'r','linewidth',2);\n\n % draw smooth path\n X = smoothedPath(:,1);\n Y = smoothedPath(:,2);\n Z = smoothedPath(:,3);\n plot3(Y,X,-Z,'k','linewidth',2);\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% buildingVertFace(x,y,width,height)\n%% define patches for a building located at (x,y)\nfunction [V,F,patchcolors] = buildingVertFace(n,e,width,height)\n \n % vertices of the building\n V = [...\n e+width/2, n+width/2, 0;...\n e+width/2, n-width/2, 0;...\n e-width/2, n-width/2, 0;...\n e-width/2, n+width/2, 0;...\n e+width/2, n+width/2, height;...\n e+width/2, n-width/2, height;...\n e-width/2, n-width/2, height;...\n e-width/2, n+width/2, height;...\n ]; \n % define faces of fuselage\n F = [...\n 1, 4, 8, 5;... % North Side\n 1, 2, 6, 5;... % East Side\n 2, 3, 7, 6;... % South Side\n 3, 4, 8, 7;... % West Side\n 5, 6, 7, 8;... % Top\n ]; \n\n myred = [1, 0, 0];\n mygreen = [0, 1, 0];\n myblue = [0, 0, 1];\n myyellow = [1,1,0];\n mymagenta = [0, 1, 1];\n\n patchcolors = [...\n mygreen;... % North\n mygreen;... % East\n mygreen;... % South\n mygreen;... % West\n myyellow;... % Top\n ];\n\nend\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/planRRT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.37318909508506304}} {"text": "function CPD = update_ess(CPD, fmarginal, evidence, ns, cnodes, hidden_bitv)\n% UPDATE_ESS Update the Expected Sufficient Statistics of a hhmmF node.\n% function CPD = update_ess(CPD, fmarginal, evidence, ns, cnodes, hidden_bitv)\n\n% Figure out the node numbers associated with each parent\n% so we extract evidence from the right place\ndom = fmarginal.domain; % Q(1) .. Q(d) F(d+1) F(d)\nQps = fmarginal.domain(1:end-2);\nQ = Qps(end);\nQps = Qps(1:end-1);\n\nQsz = CPD.Qsizes(CPD.Q);\nQpsz = prod(CPD.Qsizes(CPD.Qps)); % may be 1\n\n% We assume the F node are always hidden, but allow some of the Q nodes\n% to be observed. We do case analysis for speed.\n%We only extract prob from fmarginal.T when F(d+1)=2 i.e., model below has finished.\n% wrong -> % We sum over the possibilities that F(d+1) = 1 or 2\n\nobs_self = ~hidden_bitv(Q);\nif obs_self\n self_val = evidence{Q};\nend\n\nif isempty(Qps) % independent of parent context\n counts = zeros(Qsz, 2);\n %fmarginal.T(Q(d), F(d+1), F(d))\n if obs_self\n marg = myreshape(fmarginal.T, [1 2 2]);\n counts(self_val,:) = marg(1,2,:);\n %counts(self_val,:) = marg(1,1,:) + marg(1,2,:);\n else\n marg = myreshape(fmarginal.T, [Qsz 2 2]);\n counts = squeeze(marg(:,2,:));\n %counts = squeeze(marg(:,2,:)) + squeeze(marg(:,1,:));\n end\nelse\n counts = zeros(Qpsz, Qsz, 2);\n %fmarginal.T(Q(1:d-1), Q(d), F(d+1), F(d))\n obs_Qps = ~any(hidden_bitv(Qps)); % we assume that all or none of the Q parents are observed\n if obs_Qps\n Qps_val = subv2ind(Qpsz, cat(1, evidence{Qps}));\n end\n if obs_self & obs_Qps\n marg = myreshape(fmarginal.T, [1 1 2 2]);\n counts(Qps_val, self_val, :) = squeeze(marg(1,1,2,:));\n %counts(Qps_val, self_val, :) = squeeze(marg(1,1,2,:)) + squeeze(marg(1,1,1,:));\n elseif ~obs_self & obs_Qps\n marg = myreshape(fmarginal.T, [1 Qsz 2 2]);\n counts(Qps_val, :, :) = squeeze(marg(1,:,2,:));\n %counts(Qps_val, :, :) = squeeze(marg(1,:,2,:)) + squeeze(marg(1,:,1,:));\n elseif obs_self & ~obs_Qps\n error('not yet implemented')\n else\n marg = myreshape(fmarginal.T, [Qpsz Qsz 2 2]);\n counts(:, :, :) = squeeze(marg(:,:,2,:));\n %counts(:, :, :) = squeeze(marg(:,:,2,:)) + squeeze(marg(:,:,1,:));\n end \nend\n\nCPD.sub_CPD_term = update_ess_simple(CPD.sub_CPD_term, counts);\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/CPDs/@hhmmF_CPD/Old/update_ess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.37297842252263796}} {"text": "function TCP = jeongLungTCPmodel(paramS,doseBinsV,volHistV)\n% Usage: TCP = jeongLungTCPmodel(paramS);\n% Lung TCP model\n% Based on code by Jeho Jeong jeongj@mskcc.org\n%------------------------------------------------------------------------------------\n% INPUTS:\n% paramS : Parameter dictionary with fields\n% -frxSize (Fraction size (Gy)), \n% -treatmentSchedule(Vector indicating treatment days)\n% Example: \n% paramS.frxSize.val = 2; \n% paramS.treatmentSchedule.val = [ 1 2 3 4 5 ...\n% 8 9 10 11 12 ...\n% 15 16 17 18 19 ...\n% 22 23 24 25 26];\n% \n%----------------------------------------------------------------------------\n% AI 8/30/18\n\n%% Get fractionation \nfx_in = paramS.frxSize.val;\nnFrx = paramS.numFractions.val;\n\n%% Get treatment days\nschedule_in = paramS.treatmentSchedule.val;\nif isfield(paramS,'scheduleType')\n scheduleType = paramS.scheduleType;\nelse\n scheduleType = 'weekday';\nend\n%Check for numeric input\nif ~isnumeric(schedule_in)\n scheduleV = str2num(schedule_in);\nelse\n scheduleV = schedule_in;\nend\n%Otherwise, assume function specified\nif isempty(scheduleV)\n scheduleV = eval([schedule_in,'(',num2str(nFrx),',scheduleType)']);\n %scheduleV = getTreatmentSchedule(nFrx); %every weekday with weekend\n %breaks\nend\n\n%% Input variables for the analysis\nalpha_p_ori=0.305; \na_over_b=2.8;\noer_i=1.7;\nrho_t=10^6;\nv_t_ref=3e4;\nf_s=0.01;\nt_c=2;\nf_p_pro_in=0.5;\nht_loss=2; \nk_m=0.3; \nht_lys=3; \noer_h=1.37;\nF_p_cyc=[0.56;0.24;0.2];\nAlpha_ratio_p_cyc=[2;3];\n \nd_t=15; \nclf_in=0.92; \ngf_in=0.25;\n\nbeta_p_ori=alpha_p_ori/a_over_b; \n\n\n%% EQD2 estimation for each cohort\n\n\nEQD2=[]; \nn_pt=[];\nv_t=3e4; \nalpha_p=alpha_p_ori; \nbeta_p=beta_p_ori;\nn_t=rho_t*v_t; %No. cells\nn_t_ref=rho_t*v_t_ref;\ntotal_clono_cell=n_t*f_s;\ndelta_t=d_t/(60*24); %dt in days\nt_start=0;\n\n\nIC=[];\nGF=[];\nTCP=[];\nTD50=[];\nBED=[];\nReox_time=[];\nReox_time2=[];\nTreat_duration=[];\nvec_leng=[];\ncomp_size(1)=0; %Compartment size (P)\ncomp_size(2)=0; %Compartment size (H)\ncomp_size(3)=0; %Compartment size (I)\ncomp_size_ref(1)=0; \ncomp_size_ref(2)=0;\ncomp_size_ref(3)=0;\np_pre=[]; \ni_pre=[]; \nh_pre=[];\nT_end=[]; \n\n\nclf=clf_in;\ngf=gf_in;\n\n\n%% Run sub-routine for specific CLF and GF\n%---Variables for the initial st-st distribution--%\nf_p_pro=f_p_pro_in;\n\ncomp_size(1)=gf/f_p_pro*n_t;\ncomp_size(2)=(1-gf*(1/f_p_pro_in+clf*ht_loss/t_c))*n_t;\ncomp_size(3)=clf*gf*ht_loss/t_c*n_t;\n\ncomp_size_ref(1)=gf/f_p_pro*n_t_ref;\ncomp_size_ref(2)=(1-gf*(1/f_p_pro_in+clf*ht_loss/t_c))*n_t_ref;\ncomp_size_ref(3)=clf*gf*ht_loss/t_c*n_t_ref;\n%--- end ----%\n\n\n%Record number of cells\nf_p=comp_size(1)/sum(comp_size);\nf_i=comp_size(2)/sum(comp_size);\nf_h=comp_size(3)/sum(comp_size);\n\n\nfor d=fx_in\n Treat_day=scheduleV;\n \n %Cell cycle and dose-dependent radiosensitivity\n f = @(alpha_s)F_p_cyc(1)*exp(-Alpha_ratio_p_cyc(1)*alpha_s*2-...\n Alpha_ratio_p_cyc(1)*(alpha_s/a_over_b)*4)+F_p_cyc(2)*...\n exp(-alpha_s*2-(alpha_s/a_over_b)*4)+F_p_cyc(3)*...\n exp(-Alpha_ratio_p_cyc(2)*alpha_s*2-...\n Alpha_ratio_p_cyc(2)*(alpha_s/a_over_b)*4)-exp(-alpha_p*2-...\n (alpha_p/a_over_b)*4);\n \n alpha_s=0.3; grid=0.1; pre_f=f(alpha_s);\n while abs(f(alpha_s)) >= eps\n if pre_f*f(alpha_s)<0\n grid=grid*0.1;\n end\n pre_f = f(alpha_s);\n if f(alpha_s)>0\n alpha_s=alpha_s+grid;\n else\n alpha_s=alpha_s-grid;\n end\n end\n Alpha_p_cyc(2)= alpha_s;\n\n\n Alpha_p_cyc(1)=Alpha_p_cyc(2)*Alpha_ratio_p_cyc(1);\n Alpha_p_cyc(3)=Alpha_p_cyc(2)*Alpha_ratio_p_cyc(2);\n\n %Effective alpha, beta from survival fractions \n Su_p=F_p_cyc(1)*exp(-Alpha_p_cyc(1)*d-(Alpha_p_cyc(1)/a_over_b)*d^2)...\n +F_p_cyc(2)*exp(-Alpha_p_cyc(2)*d-(Alpha_p_cyc(2)/a_over_b)*d^2)...\n +F_p_cyc(3)*exp(-Alpha_p_cyc(3)*d-(Alpha_p_cyc(3)/a_over_b)*d^2);\n alpha_p_eff=-log(Su_p)/(d*(1+(d/a_over_b)));\n beta_p_eff=(alpha_p_eff/a_over_b);\n\n Su_i_2gy=exp(-alpha_p/oer_i*2-(alpha_p/a_over_b)/(oer_i^2)*2^2);\n oer_i_g1=(-(Alpha_p_cyc(1)*2)-sqrt((Alpha_p_cyc(1)*2)^2-...\n 4*log(Su_i_2gy)*(Alpha_p_cyc(1)/a_over_b)*2^2))/(2*log(Su_i_2gy));\n Su_h_2gy=exp(-alpha_p/oer_h*2-(alpha_p/a_over_b)/(oer_h^2)*2^2);\n oer_h_g1=(-(Alpha_p_cyc(1)*2)-sqrt((Alpha_p_cyc(1)*2)^2-...\n 4*log(Su_h_2gy)*(Alpha_p_cyc(1)/a_over_b)*2^2))/(2*log(Su_h_2gy));\n alpha_i=Alpha_p_cyc(1)/oer_i_g1;\n beta_i=(Alpha_p_cyc(1)/a_over_b)/(oer_i_g1^2);\n alpha_h=Alpha_p_cyc(1)/oer_h_g1;\n beta_h=(Alpha_p_cyc(1)/a_over_b)/(oer_h_g1^2);\n\n alpha_p=alpha_p_eff;\n beta_p=beta_p_eff;\n\n % Run sub-routine for a specific CLF and GF\n %--- RT fractional dose for SBRT schedule ---%\n\n % Assign proliferating fraction to the initial value\n f_p_pro=f_p_pro_in;\n\n % Cell distribution in each compartment \n % (1:Pv, 2:Pd, 3:Iv, 4:Id, 5:Hv, 6:Hd, 7:lysis)\n % Initially all compartments are fully filled with viable cells\n % \"comp_size\" is the size of each compartment (1:P, 2:I, 3:H)\n\n cell_dist=[];\n cell_dist(1)=comp_size(1);\n cell_dist(2)=0;\n cell_dist(3)=comp_size(2);\n cell_dist(4)=0;\n cell_dist(5)=comp_size(3);\n cell_dist(6)=0;\n cell_dist(7)=0;\n\n % variables (t:time(day), j:# of fraction, add_time:additional time for\n % weekend break, cum_cell_dist: cumulative cell distribution for\n % each time increment)\n t=0; \n j=0;\n cum_cell_dist_sbrt=[];\n\n\n % Treat for specific SBRT schedule\n while t(t_start+(Treat_day(j+1)-1)-delta_t/2) &&...\n t<(t_start+(Treat_day(j+1)-1)+delta_t/2)\n\n cell_dist(2)=cell_dist(2)+cell_dist(1)*(1-exp(-alpha_p*d-beta_p*d^2));\n cell_dist(1)=cell_dist(1)*exp(-alpha_p*d-beta_p*d^2);\n cell_dist(4)=cell_dist(4)+cell_dist(3)*(1-exp(-alpha_i*d-beta_i*d^2));\n cell_dist(3)=cell_dist(3)*exp(-alpha_i*d-beta_i*d^2);\n cell_dist(6)=cell_dist(6)+cell_dist(5)*(1-exp(-alpha_h*d-beta_h*d^2));\n cell_dist(5)=cell_dist(5)*exp(-alpha_h*d-beta_h*d^2);\n\n j=j+1;\n end\n\n % Cell Proliferation & Death \n cell_dist(1)=cell_dist(1)*(2)^(f_p_pro*delta_t/t_c); \n h_pre=cell_dist(5)+cell_dist(6);\n cell_dist(5)=cell_dist(5)*(0.5)^(delta_t/ht_loss); \n cell_dist(6)=cell_dist(6)*(0.5)^(delta_t/ht_loss); \n p_d_pre=cell_dist(2);\n cell_dist(2)=cell_dist(2)*(2)^(f_p_pro*(2*k_m-1)*delta_t/t_c); \n\n\n % Mitotically dead cell in 1 time step\n md=p_d_pre-cell_dist(2)+(h_pre-cell_dist(5)-cell_dist(6));\n cell_dist(7)=cell_dist(7)+md;\n cell_dist(7)=cell_dist(7)*(0.5)^(delta_t/ht_lys);\n\n\n % Recompartmentalization of the cell \n if cell_dist(1)+cell_dist(2)>=comp_size(1) \n p_ex=(cell_dist(1)+cell_dist(2))-comp_size(1); \n p_ratio=cell_dist(1)/(cell_dist(1)+cell_dist(2)); \n cell_dist(1)=comp_size(1)*p_ratio; \n cell_dist(2)=comp_size(1)*(1-p_ratio); \n cell_dist(3)=cell_dist(3)+p_ex*p_ratio; \n cell_dist(4)=cell_dist(4)+p_ex*(1-p_ratio); \n else \n if cell_dist(3)+cell_dist(4)>0 \n if cell_dist(3)+cell_dist(4)>comp_size(1)-...\n (cell_dist(1)+cell_dist(2)) \n p_def=comp_size(1)-(cell_dist(1)+cell_dist(2)); \n i_ratio=cell_dist(3)/(cell_dist(3)+cell_dist(4)); \n cell_dist(1)=cell_dist(1)+p_def*i_ratio; \n cell_dist(2)=cell_dist(2)+p_def*(1-i_ratio); \n cell_dist(3)=cell_dist(3)-p_def*i_ratio; \n cell_dist(4)=cell_dist(4)-p_def*(1-i_ratio); \n else \n cell_dist(1)=cell_dist(1)+cell_dist(3); \n cell_dist(2)=cell_dist(2)+cell_dist(4); \n cell_dist(3)=0; cell_dist(4)=0; \n if cell_dist(5)+cell_dist(6)>0 \n if cell_dist(5)+cell_dist(6)>comp_size(1)-...\n (cell_dist(1)+cell_dist(2)) \n p_def=comp_size(1)-(cell_dist(1)+cell_dist(2)); \n h_ratio=cell_dist(5)/(cell_dist(5)+cell_dist(6)); \n cell_dist(1)=cell_dist(1)+p_def*h_ratio; \n cell_dist(2)=cell_dist(2)+p_def*(1-h_ratio); \n cell_dist(5)=cell_dist(5)-p_def*h_ratio; \n cell_dist(6)=cell_dist(6)-p_def*(1-h_ratio); \n else \n cell_dist(1)=cell_dist(1)+cell_dist(5); \n cell_dist(2)=cell_dist(2)+cell_dist(6); \n cell_dist(5)=0; cell_dist(6)=0; \n end \n end \n end \n end \n end \n if cell_dist(3)+cell_dist(4)>=comp_size(2) \n i_ex=(cell_dist(3)+cell_dist(4))-comp_size(2); \n i_ratio=cell_dist(3)/(cell_dist(3)+cell_dist(4)); \n cell_dist(3)=comp_size(2)*i_ratio; \n cell_dist(4)=comp_size(2)*(1-i_ratio); \n cell_dist(5)=cell_dist(5)+i_ex*i_ratio; \n cell_dist(6)=cell_dist(6)+i_ex*(1-i_ratio); \n else \n if cell_dist(5)+cell_dist(6)>0 \n if cell_dist(5)+cell_dist(6)>comp_size(2)-...\n (cell_dist(3)+cell_dist(4)) \n i_def=comp_size(2)-(cell_dist(3)+cell_dist(4)); \n h_ratio=cell_dist(5)/(cell_dist(5)+cell_dist(6)); \n cell_dist(3)=cell_dist(3)+i_def*h_ratio; \n cell_dist(4)=cell_dist(4)+i_def*(1-h_ratio); \n cell_dist(5)=cell_dist(5)-i_def*h_ratio; \n cell_dist(6)=cell_dist(6)-i_def*(1-h_ratio); \n else \n cell_dist(3)=cell_dist(3)+cell_dist(5); \n cell_dist(4)=cell_dist(4)+cell_dist(6); \n cell_dist(5)=0; cell_dist(6)=0; \n end \n end \n end \n\n\n % time step increase and store the number of cells in each compartment\n t=t+delta_t; \n cum_cell_dist_sbrt=[cum_cell_dist_sbrt cell_dist'];\n\n end\n \n \n s_sbrt=cell_dist(1)+cell_dist(3)+cell_dist(5);\n sf_sbrt=s_sbrt/sum(comp_size);\n ntd2=length(Treat_day)*d*(1+(d/a_over_b))/(1+(2/a_over_b));\n d_sbrt=d;\n n_frac_sbrt=length(Treat_day);\n duration_sbrt=max(Treat_day);\n t_sbrt=t;\n %-------------------------------------------------------------------------------%\n\n \n %% EQD2 calculation\n d=2;\n alpha_p=alpha_p_ori; beta_p=beta_p_ori;\n alpha_i=alpha_p_ori/oer_i; beta_i=beta_p_ori/(oer_i^2);\n alpha_h=alpha_p_ori/oer_h; beta_h=beta_p_ori/(oer_h^2);\n s_eqd2=0; sf_eqd2=0; eqd2=0; \n \n\n %----- RT fractional dose for EQD2 estimation ----%\n\n % Assign proliferating fraction to the initial value\n\n f_p_pro=f_p_pro_in;\n\n % Cell distribution in each compartment \n % (1:Pv, 2:Pd, 3:Iv, 4:Id, 5:Hv, 6:Hd, 7:lysis)\n % Initially all compartments are fully filled with viable cells\n % \"comp_size\" is the size of each compartment (1:P, 2:I, 3:H)\n\n cell_dist=[];\n cell_dist(1)=comp_size_ref(1);\n cell_dist(2)=0;\n cell_dist(3)=comp_size_ref(2);\n cell_dist(4)=0;\n cell_dist(5)=comp_size_ref(3);\n cell_dist(6)=0;\n cell_dist(7)=0;\n\n % variables (t:time(day), j:# of fraction, add_time:additional time for\n % weekend break, cum_cell_dist: cumulative cell distribution for\n % each time increment)\n t=0; \n j=0;\n add_time=0;\n cum_cell_dist=[];\n\n\n\n\n % Treat until the SF becomes equivalent to SBRT regime\n while (cell_dist(1)+cell_dist(3)+cell_dist(5))>s_sbrt \n\n % Change in f_p_pro (k_p) as blood supply improves\n f_p_pro=1-0.5*(cell_dist(1)+cell_dist(2))/comp_size(1);\n\n\n % RT fraction\n if t>(t_start+j+add_time-delta_t/2) && t<(t_start+j+add_time+delta_t/2)\n\n cell_dist(2)=cell_dist(2)+cell_dist(1)*(1-exp(-alpha_p*d-beta_p*d^2));\n cell_dist(1)=cell_dist(1)*exp(-alpha_p*d-beta_p*d^2);\n cell_dist(4)=cell_dist(4)+cell_dist(3)*(1-exp(-alpha_i*d-beta_i*d^2));\n cell_dist(3)=cell_dist(3)*exp(-alpha_i*d-beta_i*d^2);\n cell_dist(6)=cell_dist(6)+cell_dist(5)*(1-exp(-alpha_h*d-beta_h*d^2));\n cell_dist(5)=cell_dist(5)*exp(-alpha_h*d-beta_h*d^2);\n\n j=j+1;\n\n % Week-end break\n if rem(j,5)==0\n add_time=add_time+2;\n end\n\n end\n\n % Cell Proliferation & Death \n cell_dist(1)=cell_dist(1)*(2)^(f_p_pro*delta_t/t_c);\n h_pre=cell_dist(5)+cell_dist(6);\n cell_dist(5)=cell_dist(5)*(0.5)^(delta_t/ht_loss); \n cell_dist(6)=cell_dist(6)*(0.5)^(delta_t/ht_loss); \n p_d_pre=cell_dist(2);\n cell_dist(2)=cell_dist(2)*(2)^(f_p_pro*(2*k_m-1)*delta_t/t_c); \n\n\n % Mitotically dead cell in 1 time step\n md=p_d_pre-cell_dist(2)+(h_pre-cell_dist(5)-cell_dist(6));\n cell_dist(7)=cell_dist(7)+md;\n cell_dist(7)=cell_dist(7)*(0.5)^(delta_t/ht_lys);\n\n\n % Recompartmentalization of the cell \n if cell_dist(1)+cell_dist(2)>=comp_size(1) \n p_ex=(cell_dist(1)+cell_dist(2))-comp_size(1); \n p_ratio=cell_dist(1)/(cell_dist(1)+cell_dist(2)); \n cell_dist(1)=comp_size(1)*p_ratio; \n cell_dist(2)=comp_size(1)*(1-p_ratio); \n cell_dist(3)=cell_dist(3)+p_ex*p_ratio; \n cell_dist(4)=cell_dist(4)+p_ex*(1-p_ratio); \n else \n if cell_dist(3)+cell_dist(4)>0 \n if cell_dist(3)+cell_dist(4)>comp_size(1)-...\n (cell_dist(1)+cell_dist(2)) \n p_def=comp_size(1)-(cell_dist(1)+cell_dist(2)); \n i_ratio=cell_dist(3)/(cell_dist(3)+cell_dist(4)); \n cell_dist(1)=cell_dist(1)+p_def*i_ratio; \n cell_dist(2)=cell_dist(2)+p_def*(1-i_ratio); \n cell_dist(3)=cell_dist(3)-p_def*i_ratio; \n cell_dist(4)=cell_dist(4)-p_def*(1-i_ratio); \n else \n cell_dist(1)=cell_dist(1)+cell_dist(3); \n cell_dist(2)=cell_dist(2)+cell_dist(4); \n cell_dist(3)=0; cell_dist(4)=0; \n if cell_dist(5)+cell_dist(6)>0 \n if cell_dist(5)+cell_dist(6)>comp_size(1)-...\n (cell_dist(1)+cell_dist(2)) \n p_def=comp_size(1)-(cell_dist(1)+cell_dist(2)); \n h_ratio=cell_dist(5)/(cell_dist(5)+cell_dist(6)); \n cell_dist(1)=cell_dist(1)+p_def*h_ratio; \n cell_dist(2)=cell_dist(2)+p_def*(1-h_ratio); \n cell_dist(5)=cell_dist(5)-p_def*h_ratio; \n cell_dist(6)=cell_dist(6)-p_def*(1-h_ratio); \n else \n cell_dist(1)=cell_dist(1)+cell_dist(5); \n cell_dist(2)=cell_dist(2)+cell_dist(6); \n cell_dist(5)=0; cell_dist(6)=0; \n end \n end \n end \n end \n end \n if cell_dist(3)+cell_dist(4)>=comp_size(2) \n i_ex=(cell_dist(3)+cell_dist(4))-comp_size(2); \n i_ratio=cell_dist(3)/(cell_dist(3)+cell_dist(4)); \n cell_dist(3)=comp_size(2)*i_ratio; \n cell_dist(4)=comp_size(2)*(1-i_ratio); \n cell_dist(5)=cell_dist(5)+i_ex*i_ratio; \n cell_dist(6)=cell_dist(6)+i_ex*(1-i_ratio); \n else \n if cell_dist(5)+cell_dist(6)>0 \n if cell_dist(5)+cell_dist(6)>comp_size(2)-...\n (cell_dist(3)+cell_dist(4)) \n i_def=comp_size(2)-(cell_dist(3)+cell_dist(4)); \n h_ratio=cell_dist(5)/(cell_dist(5)+cell_dist(6)); \n cell_dist(3)=cell_dist(3)+i_def*h_ratio; \n cell_dist(4)=cell_dist(4)+i_def*(1-h_ratio); \n cell_dist(5)=cell_dist(5)-i_def*h_ratio; \n cell_dist(6)=cell_dist(6)-i_def*(1-h_ratio); \n else \n cell_dist(3)=cell_dist(3)+cell_dist(5); \n cell_dist(4)=cell_dist(4)+cell_dist(6); \n cell_dist(5)=0; cell_dist(6)=0; \n end \n end \n end \n\n\n % time step increase and store the number of cells in each compartment\n t=t+delta_t; \n cum_cell_dist=[cum_cell_dist cell_dist'];\n\n s_eqd2_pre=s_eqd2;\n sf_eqd2_pre=sf_eqd2;\n eqd2_pre=eqd2;\n\n s_eqd2=cell_dist(1)+cell_dist(3)+cell_dist(5);\n sf_eqd2=s_eqd2/sum(comp_size);\n tcp=exp(-s_eqd2*f_s);\n eqd2=j*d;\n\n\n end\n \n \n %----------------------------------------------------------------------%\n\n\n eqd2=eqd2_pre+((eqd2-eqd2_pre)/(s_eqd2_pre-s_eqd2))*(s_eqd2_pre-s_sbrt);\n\n \nend\n\n%% Compute TCP\nTD_50 = 62.1;\ngamma_50 = 1.5;\nTCP_upper_bound = 0.95;\n\nTCP=TCP_upper_bound/(1+(TD_50/eqd2)^(4*gamma_50));\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/ModelImplementationLibrary/DosimetricModels/jeongLungTCPmodel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3729774042418959}} {"text": "function yp = p00_fun ( test, neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P00_FUN evaluates the right hand side of any test problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer TEST, the test problem index.\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, the value of the independent variable.\n%\n% Input, real Y(NEQN,1), the value of the dependent variables.\n%\n% Output, real YP(NEQN,1), the value of the derivative of the\n% dependent variables, as specified by the ODE.\n%\n yp = zeros ( neqn, 1 );\n \n if ( test == 1 )\n yp = p01_fun ( neqn, t, y );\n elseif ( test == 2 )\n yp = p02_fun ( neqn, t, y );\n elseif ( test == 3 )\n yp = p03_fun ( neqn, t, y );\n elseif ( test == 4 )\n yp = p04_fun ( neqn, t, y );\n elseif ( test == 5 )\n yp = p05_fun ( neqn, t, y );\n elseif ( test == 6 )\n yp = p06_fun ( neqn, t, y );\n elseif ( test == 7 )\n yp = p07_fun ( neqn, t, y );\n elseif ( test == 8 )\n yp = p08_fun ( neqn, t, y );\n elseif ( test == 9 )\n yp = p09_fun ( neqn, t, y );\n elseif ( test == 10 )\n yp = p10_fun ( neqn, t, y );\n elseif ( test == 11 )\n yp = p11_fun ( neqn, t, y );\n elseif ( test == 12 )\n yp = p12_fun ( neqn, t, y );\n elseif ( test == 13 )\n yp = p13_fun ( neqn, t, y );\n elseif ( test == 14 )\n yp = p14_fun ( neqn, t, y );\n elseif ( test == 15 )\n yp = p15_fun ( neqn, t, y );\n elseif ( test == 16 )\n yp = p16_fun ( neqn, t, y );\n elseif ( test == 17 )\n yp = p17_fun ( neqn, t, y );\n elseif ( test == 18 )\n yp = p18_fun ( neqn, t, y );\n elseif ( test == 19 )\n yp = p19_fun ( neqn, t, y );\n elseif ( test == 20 )\n yp = p20_fun ( neqn, t, y );\n elseif ( test == 21 )\n yp = p21_fun ( neqn, t, y );\n elseif ( test == 22 )\n yp = p22_fun ( neqn, t, y );\n elseif ( test == 23 )\n yp = p23_fun ( neqn, t, y );\n elseif ( test == 24 )\n yp = p24_fun ( neqn, t, y );\n elseif ( test == 25 )\n yp = p25_fun ( neqn, t, y );\n elseif ( test == 26 )\n yp = p26_fun ( neqn, t, y );\n elseif ( test == 27 )\n yp = p27_fun ( neqn, t, y );\n elseif ( test == 28 )\n yp = p28_fun ( neqn, t, y );\n elseif ( test == 29 )\n yp = p29_fun ( neqn, t, y );\n elseif ( test == 30 )\n yp = p30_fun ( neqn, t, y );\n elseif ( test == 31 )\n yp = p31_fun ( neqn, t, y );\n elseif ( test == 32 )\n yp = p32_fun ( neqn, t, y );\n elseif ( test == 33 )\n yp = p33_fun ( neqn, t, y );\n elseif ( test == 34 )\n yp = p34_fun ( neqn, t, y );\n elseif ( test == 35 )\n yp = p35_fun ( neqn, t, y );\n elseif ( test == 36 )\n yp = p36_fun ( neqn, t, y );\n elseif ( test == 37 )\n yp = p37_fun ( neqn, t, y );\n elseif ( test == 38 )\n yp = p38_fun ( neqn, t, y );\n elseif ( test == 39 )\n yp = p39_fun ( neqn, t, y );\n elseif ( test == 40 )\n yp = p40_fun ( neqn, t, y );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_FUN - Fatal error!\\n' );\n fprintf ( 1, ' Illegal problem index TEST = %d\\n', test );\n error ( 'P00_FUN - Fatal error!' );\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/test_ode/p00_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.37278806621119437}} {"text": "function [poly,poly_idx,max_index,max_size] = extdom_polygon(bnde,pts,order,line,min_size)\n% DESCRIPTION: Given a set of boundary edges of a singly- or multi-\n% polygonal region, organize them in a winding order.\n%\n% INPUTS:\n% bnde: the indices of each boundary edge as a nbnde x 2 matrix\n% pts: the x,y locations of all the points in the region\n% stored as an np x 2 matrix.\n% order:the order in which the traversal takes place\n% counter-clockwise (0) or clockwise (1) or add a negative\n% sign to append NaNs in each cell.\n% line:if desired output will be polylines\n% min_size: if the lenght of the polygon is less than min_size\n% points, throw it out. zero by default. \n% OUTPUTS:\n% poly: the boundary of each enclosing polygon sorted in winding-order\n% poly is returned as a cell-array of length number of polys.\n% poly_idx: indices of the polygon coordinates in the same format as\n% poly\n% max_index: is the index into poly that is the largest\n% max_size: is the size of the largest poly\n%\n% Last Edited:\n% kjr,UND,CHL,2017\n% kjr,UND,CHL -->revised for massive speed improvements March 2018.\n%\n% TRAVERSAL METHOD\n% Pick any unvisited edge segment [v_start,v_next] and add these vertices to the polygon loop.\n% Find the unvisited edge segment [v_i,v_j] that has either v_i = v_next or v_j = v_next and add the other vertex (the one not equal to v_next) to the polygon loop.\n% Reset v_next as this newly added vertex, mark the edge as visited and continue from 2.\n% Traversal is done when we get back to v_start.\n% NOTE: that the signed area will be positive if the vertices are\n% oriented counterclockwise, and will be negative if it is oriented clockwise\n\n% NOTE: By flipping the edges left-to-right, we can easily see the nodal\n% connectivity of the triangulation. However, since we are effectively\n% adding new \"edges\", we must also quickly locate and flag the \"flipped\" edge\n% in addition to the current edge under consideration. This is accomplished with the invmap\n% array which allows one, given a vertex gid, to quickly find it's linear\n% index inside the array bnde((boundary edges). This localizes the search to find\n% the connectivity to continue the \"walk\" on the boundary making the\n% calculation massively more efficient than compared to searching the entire bnde\n% array with edge under consideration.\n\n% if storing lines\nif(nargin < 4); line = 0; end\nif(nargin < 5); min_size = 1; end\n\nbnde = [bnde; fliplr(bnde)];\nbnde = sortrows(bnde,1);\nned = length(bnde);\nan = sign(order);\nactive = true(ned,1);\n\np = 0 ;\n% given a vertex with num gid, return where it exists last lid.\nfor lid = 1 : ned\n gid = bnde(lid,1);\n invmap(gid) = lid ;\nend\n\nwhile any(active)\n p = p + 1;\n \n rn = find(active,1);\n \n temp = pts(bnde(rn,:)',:);\n temp2 = bnde(rn,:)';\n \n v_start= bnde(rn,1);\n v_next = bnde(rn,2);\n \n active(rn) = false;\n \n % flag flipped edge too\n flipped = fliplr(bnde(rn,:));\n idx = invmap(flipped(1));\n st = max((idx - 1),1);\n ed = min(idx,ned);\n rn = find(flipped(2)==bnde(st:ed,2),1);\n \n active(rn+st-1) = false;\n \n k = 2 ;\n while v_next~=v_start\n \n % form local set to search for continuation of boundary walk.\n idx = invmap(v_next);\n st = max((idx - 1),1);\n ed = min(idx,ned);\n \n r = find(v_next==bnde(st:ed,1) & active(st:ed),1);\n tsel = bnde(st+r-1,:); tsel_inv = fliplr(tsel) ;\n sel=tsel(tsel~=v_next);\n \n if(line)\n if(isempty(sel))\n break\n end\n end\n % store points.\n k = k + 1;\n temp(k,:) = pts(sel,:);\n temp2(k,:)= sel;\n \n active(r+st-1) = false;\n \n % flag flipped edge too\n idx = invmap(tsel_inv(1));\n st = max((idx - 1),1);\n ed = min(idx,ned);\n r = find(tsel_inv(2)==bnde(st:ed,2),1);\n active(r+st-1) = false;\n \n v_next = sel;\n \n end\n \n if length(temp > min_size)\n poly{p} = temp;\n poly_idx{p} = temp2;\n else\n continue \n end\n if an < 0\n poly{p}(end+1,:) = [NaN NaN];\n poly_idx{p}(end+1,:) = NaN;\n end\n [area]=parea(poly{p}(:,1),poly{p}(:,2));\n if order==0 % ccw\n if sign(area)<0\n poly{p} = flipud(poly{p});\n poly_idx{p} = flipud(poly_idx{p});\n end\n else % cw\n if sign(area)>0\n poly{p} = flipud(poly{p});\n poly_idx{p} = flipud(poly_idx{p});\n end\n end\nend\n[max_size, max_index] = max(cellfun('size', poly, 1));\nend\n% helper function, computes area of polygon\nfunction [area]=parea(x,y)\nn = length(x);\nxp = [x; x(1)];\nyp = [y; y(1)];\narea = 0;\nfor i = 1:n\n area = area + det([xp(i), xp(i+1); yp(i), yp(i+1)]);\nend\narea = 1/2*area;\nend", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/extdom_polygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3727274531134735}} {"text": "function [SPM] = cl_ext_spm_spm(SPM)\n% [Re]ML Estimation of a General Linear Model\n%\n% :Usage:\n% ::\n%\n% FORMAT [SPM] = spm_spm(SPM)\n%\n% :Required fields of SPM:\n%\n% xY.VY - nScan x 1 struct array of image handles (see spm_vol)\n% Images must have the same orientation, voxel size and data type\n% - Any scaling should have already been applied via the image handle\n% scalefactors.\n%\n% xX - Structure containing design matrix information\n% - Required fields are:\n% xX.X - Design matrix (raw, not temporally smoothed)\n% xX.name - cellstr of parameter names corresponding to columns\n% of design matrix\n% - Optional fields are:\n% xX.K - cell of session-specific structures (see spm_filter)\n% - Design & data are pre-multiplied by K\n% (K*Y = K*X*beta + K*e)\n% - Note that K should not smooth across block boundaries\n% - defaults to speye(size(xX.X,1))\n% xX.W - Optional whitening/weighting matrix used to give\n% weighted least squares estimates (WLS). If not specified\n% spm_spm will set this to whiten the data and render\n% the OLS estimates maximum likelihood\n% i.e. W*W' = inv(xVi.V).\n%\n% xVi - Structure describing intrinsic temporal non-sphericity\n% - Required fields are:\n% xVi.Vi - array of non-sphericity components\n% - defaults to {speye(size(xX.X,1))} - i.i.d.\n% - specifying a cell array of constraints (Qi)\n% These constraints invoke spm_reml to estimate\n% hyperparameters assuming V is constant over voxels.\n% that provide a high precise estimate of xX.V\n% - Optional fields are:\n% xX.V - Optional non-sphericity matrix. Cov(e) = sigma^2*V\n% If not specified spm_spm will compute this using\n% a 1st pass to identify significant voxels over which\n% to estimate V. A 2nd pass is then used to re-estimate\n% the parameters with WLS and save the ML estimates\n% (unless xX.W is already specified).\n%\n% xM - Structure containing masking information, or a simple column vector\n% of thresholds corresponding to the images in VY [default: -Inf]\n% - If a structure, the required fields are:\n% xM.TH - nVar x nScan matrix of analysis thresholds, one per image\n% xM.I - Implicit masking (0=>none, 1 => implicit zero/NaN mask)\n% xM.VM - struct array of explicit mask image handles\n% - (empty if no explicit masks)\n% - Explicit mask images are >0 for valid voxels to assess.\n% - Mask images can have any orientation, voxel size or data\n% type. They are interpolated using nearest neighbour\n% interpolation to the voxel locations of the data Y.\n% - Note that voxels with constant data (i.e. the same value across\n% scans) are also automatically masked out.\n%\n% swd - Directory where the output files will be saved [default: pwd]\n% If exists, it becomes the current working directory.\n%\n% In addition, global SPM \"defaults\" variable is used (see spm_defaults):\n% \n% stats..UFp - critical F-threshold for selecting voxels over \n% which the non-sphericity is estimated (if \n% required) [default: 0.001]\n% \n% stats.maxres - maximum number of residual images for smoothness\n% estimation\n%\n% stats.maxmem - maximum amount of data processed at a time (in bytes)\n%\n% modality - SPM modality {'PET','FMRI','EEG'}\n%\n%__________________________________________________________________________\n%\n% spm_spm is the heart of the SPM package. Given image files and a\n% General Linear Model, it estimates the model parameters, variance\n% hyperparameters, and smoothness of standardised residual fields, writing\n% these out to disk in the current working directory for later\n% interrogation in the results section. (NB: Existing analyses in the\n% current working directory are overwritten). This directory\n% now becomes the working directory for this analysis and all saved\n% images are relative to this directory.\n%\n% The model is expressed via the design matrix (xX.X). The basic model\n% at each voxel is of the form is Y = X*B + e, for data Y, design\n% matrix X, (unknown) parameters B and residual errors e. The errors\n% are assumed to have a normal distribution.\n%\n% Sometimes confounds (e.g. drift terms in fMRI) are necessary. These\n% can be specified directly in the design matrix or implicitly, in terms\n% of a residual forming matrix K to give a generalised linear model\n% K*Y = K*X*B + K*e. In fact K can be any matrix (e.g. a convolution\n% matrix).\n%\n% In some instances i.i.d. assumptions about errors do not hold. For\n% example, with serially correlated (fMRI) data or correlations among the\n% levels of a factor in repeated measures designs. This non-sphericity\n% can be specified in terms of components (SPM.xVi.Vi{i}). If specified\n% these covariance components will then be estimated with ReML (restricted\n% maximum likelihood) hyperparameters. This estimation assumes the same\n% non-sphericity for voxels that exceed the global F-threshold. The ReML\n% estimates can then be used to whiten the data giving maximum likelihood\n% (ML) or Gauss-Markov estimators. This entails a second pass of the data\n% with an augmented model K*W*Y = K*W*X*B + K*W*e where W*W' = inv(xVi.V).\n% xVi.V is the non-sphericity based on the hyperparameter estimates.\n% W is stored in xX.W and cov(K*W*e) in xX.V. The covariance of the\n% parameter estimates is then xX.Bcov = pinv(K*W*X)*xX.V*pinv(K*W*X)'.\n%\n% If you do not want ML estimates but want to use ordinary least squares\n% (OLS) then simply set SPM.xX.W to the identity matrix. Any non-sphericity\n% V will still be estimated but will be used to adjust the degrees of freedom\n% of the ensuing statistics using the Satterthwaite approximation (c.f.\n% the Greenhouse-Geisser corrections).\n%\n% If [non-spherical] variance components Vi are not specified xVi.Vi and\n% xVi.V default to the identity matrix (i.e. i.i.d). The parameters are\n% then estimated by OLS. In this instance the OLS and ML estimates are\n% the same.\n%\n% Note that only a single voxel-specific hyperparameter (i.e. variance\n% component) is estimated, even if V is not i.i.d. This means spm_spm\n% always implements a fixed-effects model.\n% Random effects models can be emulated using a multi-stage procedure:\n% This entails summarising the data with contrasts such that the fixed\n% effects in a second model on the summary data are those effects of\n% interest (i.e. the population effects). This means contrasts are\n% re-entered into spm_spm to make an inference (SPM) at the next\n% level. At this higher hierarchical level the residual variance for the\n% model contains the appropriate variance components from lower levels.\n% See spm_RandFX.man for further details and below.\n%\n% Under the additional assumption that the standardised error fields\n% are non-stationary standard Gaussian random fields, results from\n% Random field theory can be applied to estimate the significance\n% statistic images (SPM's) adjusting p values for the multiple tests\n% at all voxels in the search volume. The parameters required for\n% this random field correction are the volume, and Lambda, the covariance\n% matrix of partial derivatives of the standardised error fields, estimated\n% by spm_est_smoothness.\n%\n% ----------------\n%\n% The volume analysed is the intersection of the threshold masks,\n% explicit masks and implicit masks. See spm_spm_ui for further details\n% on masking options.\n%\n%--------------------------------------------------------------------------\n%\n% The output of spm_spm takes the form of an SPM.mat file of the analysis\n% parameters, and 'float' flat-file images of the parameter and variance\n% [hyperparameter] estimates. An 8bit zero-one mask image indicating the\n% voxels assessed is also written out, with zero indicating voxels outside\n% tha analysed volume.\n%\n% ----------------\n%\n% The following SPM.fields are set by spm_spm (unless specified)\n%\n% xVi.V - estimated non-sphericity trace(V) = rank(V)\n% xVi.h - hyperparameters xVi.V = xVi.h(1)*xVi.Vi{1} + ...\n% xVi.Cy - spatially whitened (used by ReML to estimate h)\n% xVi.CY - <(Y - )*(Y - )'> (used by spm_spm_Bayes)\n%\n% ----------------\n%\n% Vbeta - struct array of beta image handles (relative)\n% VResMS - file struct of ResMS image handle (relative)\n% VM - file struct of Mask image handle (relative)\n%\n% ----------------\n%\n% xX.W - if not specified W*W' = inv(x.Vi.V)\n% xX.V - V matrix (K*W*Vi*W'*K') = correlations after K*W is applied\n% xX.xKXs - space structure for K*W*X, the 'filtered and whitened'\n% design matrix\n% - given as spm_sp('Set',xX.K*xX.W*xX.X) - see spm_sp\n% xX.pKX - pseudoinverse of K*W*X, computed by spm_sp\n% xX.Bcov - xX.pKX*xX.V*xX.pKX - variance-covariance matrix of\n% parameter estimates\n% (when multiplied by the voxel-specific hyperparameter ResMS\n% of the parameter estimates (ResSS/xX.trRV = ResMS) )\n% xX.trRV - trace of R*V\n% xX.trRVRV - trace of RVRV\n% xX.erdf - effective residual degrees of freedom (trRV^2/trRVRV)\n% xX.nKX - design matrix (xX.xKXs.X) scaled for display\n% (see spm_DesMtx('sca',... for details)\n%\n% ----------------\n%\n% xVol.M - 4x4 voxel->mm transformation matrix\n% xVol.iM - 4x4 mm->voxel transformation matrix\n% xVol.DIM - image dimensions - column vector (in voxels)\n% xVol.XYZ - 3 x S vector of in-mask voxel coordinates\n% xVol.S - Lebesgue measure or volume (in voxels)\n% xVol.R - vector of resel counts (in resels)\n% xVol.FWHM - Smoothness of components - FWHM, (in voxels)\n%\n% ----------------\n%\n% xCon - Contrast structure (created by spm_FcUtil.m)\n% xCon.name - Name of contrast\n% xCon.STAT - 'F', 'T' or 'P' - for F/T-contrast ('P' for PPMs)\n% xCon.c - (F) Contrast weights\n% xCon.X0 - Reduced design matrix (spans design space under Ho)\n% It is in the form of a matrix (spm99b) or the\n% coordinates of this matrix in the orthogonal basis\n% of xX.X defined in spm_sp.\n% xCon.iX0 - Indicates how contrast was specified:\n% If by columns for reduced design matrix then iX0 contains\n% the column indices. Otherwise, it's a string containing\n% the spm_FcUtil 'Set' action: Usually one of {'c','c+','X0'}\n% (Usually this is the input argument F_iX0.)\n% xCon.X1o - Remaining design space (orthogonal to X0).\n% It is in the form of a matrix (spm99b) or the\n% coordinates of this matrix in the orthogonal basis\n% of xX.X defined in spm_sp.\n% xCon.eidf - Effective interest degrees of freedom (numerator df)\n% xCon.Vcon - ...for handle of contrast/ESS image (empty at this stage)\n% xCon.Vspm - ...for handle of SPM image (empty at this stage)\n%\n% ----------------\n%\n%\n% The following images are written to file\n%\n% mask.{img,hdr} - analysis mask image\n% 8-bit (uint8) image of zero-s & one's indicating which voxels were\n% included in the analysis. This mask image is the intersection of the\n% explicit, implicit and threshold masks specified in the xM argument.\n% The XYZ matrix contains the voxel coordinates of all voxels in the\n% analysis mask. The mask image is included for reference, but is not\n% explicitly used by the results section.\n%\n% ----------------\n%\n% beta_????.{img,hdr} - parameter images\n% These are 32-bit (float32) images of the parameter estimates. The image\n% files are numbered according to the corresponding column of the\n% design matrix. Voxels outside the analysis mask (mask.img) are given\n% value NaN.\n%\n% ----------------\n%\n% ResMS.{img,hdr} - estimated residual variance image\n% This is a 64-bit (float64) image of the residual variance estimate.\n% Voxels outside the analysis mask are given value NaN.\n%\n% ----------------\n%\n% RPV.{img,hdr} - estimated resels per voxel image\n% This is a 64-bit (float64) image of the RESELs per voxel estimate.\n% Voxels outside the analysis mask are given value 0. These images\n% reflect the nonstationary aspects the spatial autocorrelations.\n%\n% ----------------\n%\n% ResI_????.{img,hdr} - standardised residual (temporary) images\n% These are 64-bit (float64) images of standardised residuals. At most\n% maxres images will be saved and used by spm_est_smoothness, after which\n% they will be deleted.\n%\n%--------------------------------------------------------------------------\n%\n% References:\n%\n% Christensen R (1996) Plane Answers to Complex Questions\n% Springer Verlag\n%\n% Friston KJ, Holmes AP, Worsley KJ, Poline JB, Frith CD, Frackowiak RSJ (1995)\n% ``Statistical Parametric Maps in Functional Imaging:\n% A General Linear Approach''\n% Human Brain Mapping 2:189-210\n%\n% Worsley KJ, Friston KJ (1995)\n% ``Analysis of fMRI Time-Series Revisited - Again''\n% NeuroImage 2:173-181\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n%\n% ..\n% % Andrew Holmes, Jean-Baptiste Poline & Karl Friston\n% $Id: spm_spm.m 3960 2010-06-30 17:41:24Z ged $\n% ..\n \nSVNid = '$Rev: 3960 $';\n \n%-Say hello\n%--------------------------------------------------------------------------\nSPMid = spm('FnBanner',mfilename,SVNid);\nFinter = spm('FigName','Stats: estimation...'); spm('Pointer','Watch');\n \n%-Get SPM.mat[s] if necessary\n%--------------------------------------------------------------------------\nif nargin == 0\n P = cellstr(spm_select(Inf,'^SPM\\.mat$','Select SPM.mat[s]'));\n for i = 1:length(P)\n swd = fileparts(P{i});\n load(fullfile(swd,'SPM.mat'));\n SPM.swd = swd;\n spm_spm(SPM);\n end\n return\nend\n \n%-Change to SPM.swd if specified\n%--------------------------------------------------------------------------\ntry\n cd(SPM.swd);\ncatch\n SPM.swd = pwd;\nend\n \n%-Ensure data are assigned\n%--------------------------------------------------------------------------\ntry\n SPM.xY.VY;\ncatch\n spm('alert!','Please assign data to this design', mfilename);\n spm('FigName','Stats: done',Finter); spm('Pointer','Arrow')\n return\nend\n \n%-Delete files from previous analyses\n%--------------------------------------------------------------------------\nif exist(fullfile(SPM.swd,'mask.img'),'file') == 2\n \n str = {'Current directory contains SPM estimation files:',...\n 'pwd = ',SPM.swd,...\n 'Existing results will be overwritten!'};\n if spm_input(str,1,'bd','stop|continue',[1,0],1)\n spm('FigName','Stats: done',Finter); spm('Pointer','Arrow')\n return\n else\n warning('Overwriting old results\\n\\t (pwd = %s) ',SPM.swd);\n try, SPM = rmfield(SPM,'xVol'); end\n end\nend\n \nfiles = {'^mask\\..{3}$','^ResMS\\..{3}$','^RPV\\..{3}$',...\n '^beta_.{4}\\..{3}$','^con_.{4}\\..{3}$','^ResI_.{4}\\..{3}$',...\n '^ess_.{4}\\..{3}$', '^spm\\w{1}_.{4}\\..{3}$'};\n \nfor i = 1:length(files)\n j = spm_select('List',SPM.swd,files{i});\n for k = 1:size(j,1)\n spm_unlink(deblank(j(k,:)));\n end\nend\n \n \n%==========================================================================\n% - A N A L Y S I S P R E L I M I N A R I E S\n%==========================================================================\n \n%-Initialise\n%==========================================================================\nfprintf('%-40s: %30s','Initialising parameters','...computing'); %-#\nxX = SPM.xX;\n[nScan nBeta] = size(xX.X);\n \n \n%-If xM is not a structure then assume it's a vector of thresholds\n%--------------------------------------------------------------------------\ntry\n xM = SPM.xM;\ncatch\n xM = -Inf(nScan,1);\nend\nif ~isstruct(xM)\n xM = struct('T', [],...\n 'TH', xM,...\n 'I', 0,...\n 'VM', {[]},...\n 'xs', struct('Masking','analysis threshold'));\nend\n \n%-Check confounds (xX.K) and non-sphericity (xVi)\n%--------------------------------------------------------------------------\nif ~isfield(xX,'K')\n xX.K = 1;\nend\ntry\n %-If covariance components are specified use them\n %----------------------------------------------------------------------\n xVi = SPM.xVi;\ncatch\n \n %-otherwise assume i.i.d.\n %----------------------------------------------------------------------\n xVi = struct( 'form', 'i.i.d.',...\n 'V', speye(nScan,nScan));\nend\n \n \n%-Get non-sphericity V\n%==========================================================================\ntry\n %-If xVi.V is specified proceed directly to parameter estimation\n %----------------------------------------------------------------------\n V = xVi.V;\n str = 'parameter estimation';\n \ncatch\n \n % otherwise invoke ReML selecting voxels under i.i.d assumptions\n %----------------------------------------------------------------------\n V = speye(nScan,nScan);\n str = '[hyper]parameter estimation';\nend\n \n%-Get whitening/Weighting matrix: If xX.W exists we will save WLS estimates\n%--------------------------------------------------------------------------\ntry\n %-If W is specified, use it\n %----------------------------------------------------------------------\n W = xX.W;\ncatch\n \n if isfield(xVi,'V')\n \n % otherwise make W a whitening filter W*W' = inv(V)\n %------------------------------------------------------------------\n W = spm_sqrtm(spm_inv(xVi.V));\n W = W.*(abs(W) > 1e-6);\n xX.W = sparse(W);\n \n else\n % unless xVi.V has not been estimated - requiring 2 passes\n %------------------------------------------------------------------\n W = speye(nScan,nScan);\n str = 'hyperparameter estimation (1st pass)';\n end\nend\n \n \n%-Design space and projector matrix [pseudoinverse] for WLS\n%==========================================================================\nxX.xKXs = spm_sp('Set',spm_filter(xX.K,W*xX.X)); % KWX\nxX.xKXs.X = full(xX.xKXs.X);\nxX.pKX = spm_sp('x-',xX.xKXs); % projector\nerdf = spm_SpUtil('trRV',xX.xKXs); % Working error df\n \n%-If xVi.V is not defined compute Hsqr and F-threshold under i.i.d.\n%--------------------------------------------------------------------------\nif ~isfield(xVi,'V')\n \n Fcname = 'effects of interest';\n iX0 = [SPM.xX.iB SPM.xX.iG];\n xCon = spm_FcUtil('Set',Fcname,'F','iX0',iX0,xX.xKXs);\n X1o = spm_FcUtil('X1o', xCon(1),xX.xKXs);\n Hsqr = spm_FcUtil('Hsqr',xCon(1),xX.xKXs);\n trRV = spm_SpUtil('trRV',xX.xKXs);\n trMV = spm_SpUtil('trMV',X1o);\n \n % Threshold for voxels entering non-sphericity estimates\n %----------------------------------------------------------------------\n try\n modality = lower(spm_get_defaults('modality'));\n UFp = spm_get_defaults(['stats.' modality '.ufp']);\n catch\n UFp = 0.001;\n end\n UF = spm_invFcdf(1 - UFp,[trMV,trRV]);\nend\n \n%-Image dimensions and data\n%==========================================================================\nVY = SPM.xY.VY;\nspm_check_orientations(VY);\n \n% check files exists and try pwd\n%--------------------------------------------------------------------------\nfor i = 1:numel(VY)\n if ~spm_existfile(VY(i).fname)\n [p,n,e] = fileparts(VY(i).fname);\n VY(i).fname = [n,e];\n end\nend\n \nM = VY(1).mat;\nDIM = VY(1).dim(1:3)';\nxdim = DIM(1); ydim = DIM(2); zdim = DIM(3);\nYNaNrep = spm_type(VY(1).dt(1),'nanrep');\n \n \n%-Maximum number of residual images for smoothness estimation\n%--------------------------------------------------------------------------\nMAXRES = spm_get_defaults('stats.maxres');\nnSres = min(nScan,MAXRES);\n \n \nfprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...done'); %-#\n \n \n%-Initialise output images (unless this is a 1st pass for ReML)\n%==========================================================================\nif isfield(xX,'W')\n fprintf('%-40s: %30s','Output images','...initialising'); %-#\n \n %-Initialise new mask name: current mask & conditions on voxels\n %----------------------------------------------------------------------\n VM = struct('fname', 'mask.img',...\n 'dim', DIM',...\n 'dt', [spm_type('uint8') spm_platform('bigend')],...\n 'mat', M,...\n 'pinfo', [1 0 0]',...\n 'descrip','spm_spm:resultant analysis mask');\n VM = spm_create_vol(VM);\n \n \n %-Initialise beta image files\n %----------------------------------------------------------------------\n Vbeta(1:nBeta) = deal(struct(...\n 'fname', [],...\n 'dim', DIM',...\n 'dt', [spm_type('float32') spm_platform('bigend')],...\n 'mat', M,...\n 'pinfo', [1 0 0]',...\n 'descrip', ''));\n \n for i = 1:nBeta\n Vbeta(i).fname = sprintf('beta_%04d.img',i);\n Vbeta(i).descrip = sprintf('spm_spm:beta (%04d) - %s',i,xX.name{i});\n end\n Vbeta = spm_create_vol(Vbeta);\n \n \n %-Initialise residual sum of squares image file\n %----------------------------------------------------------------------\n VResMS = struct('fname', 'ResMS.img',...\n 'dim', DIM',...\n 'dt', [spm_type('float64') spm_platform('bigend')],...\n 'mat', M,...\n 'pinfo', [1 0 0]',...\n 'descrip', 'spm_spm:Residual sum-of-squares');\n VResMS = spm_create_vol(VResMS);\n \n \n %-Initialise standardised residual images\n %----------------------------------------------------------------------\n VResI(1:nSres) = deal(struct(...\n 'fname', [],...\n 'dim', DIM',...\n 'dt', [spm_type('float64') spm_platform('bigend')],...\n 'mat', M,...\n 'pinfo', [1 0 0]',...\n 'descrip', 'spm_spm:StandardisedResiduals'));\n \n for i = 1:nSres\n VResI(i).fname = sprintf('ResI_%04d.img', i);\n VResI(i).descrip = sprintf('spm_spm:ResI (%04d)', i);\n end\n VResI = spm_create_vol(VResI);\n fprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...initialised'); %-#\nend % (xX,'W')\n \n \n%==========================================================================\n% - F I T M O D E L & W R I T E P A R A M E T E R I M A G E S\n%==========================================================================\n \n%-MAXMEM is the maximum amount of data processed at a time (bytes)\n%--------------------------------------------------------------------------\nMAXMEM = spm_get_defaults('stats.maxmem');\nmmv = MAXMEM/8/nScan;\nblksz = min(xdim*ydim,ceil(mmv)); %-block size\nnbch = ceil(xdim*ydim/blksz); %-# blocks\nnbz = max(1,min(zdim,floor(mmv/(xdim*ydim)))); nbz = 1; %-# planes\nblksz = blksz * nbz;\n \n%-Initialise variables used in the loop\n%==========================================================================\n[xords, yords] = ndgrid(1:xdim, 1:ydim);\nxords = xords(:)'; yords = yords(:)'; % plane X,Y coordinates\nS = 0; % Volume (voxels)\ns = 0; % Volume (voxels > UF)\nCy = 0; % spatially whitened\nCY = 0; % <(Y - ) * (Y - )'>\nEY = 0; % for ReML\ni_res = round(linspace(1,nScan,nSres))'; % Indices for residual\n \n%-Initialise XYZ matrix of in-mask voxel co-ordinates (real space)\n%--------------------------------------------------------------------------\nXYZ = zeros(3,xdim*ydim*zdim);\n \n%-Cycle over bunches blocks within planes to avoid memory problems\n%==========================================================================\nspm_progress_bar('Init',100,str,'');\n \nfor z = 1:nbz:zdim %-loop over planes (2D or 3D data)\n \n % current plane-specific parameters\n %----------------------------------------------------------------------\n CrPl = z:min(z+nbz-1,zdim); %-plane list\n zords = CrPl(:)*ones(1,xdim*ydim); %-plane Z coordinates\n CrBl = []; %-parameter estimates\n CrResI = []; %-residuals\n CrResSS = []; %-residual sum of squares\n Q = []; %-in mask indices for this plane\n \n for bch = 1:nbch %-loop over blocks\n \n %-Print progress information in command window\n %------------------------------------------------------------------\n if numel(CrPl) == 1\n str = sprintf('Plane %3d/%-3d, block %3d/%-3d',...\n z,zdim,bch,nbch);\n else\n str = sprintf('Planes %3d-%-3d/%-3d',z,CrPl(end),zdim);\n end\n if z == 1 && bch == 1\n str2 = '';\n else\n str2 = repmat(sprintf('\\b'),1,72); \n end\n fprintf('%s%-40s: %30s',str2,str,' ');\n \n %-construct list of voxels in this block\n %------------------------------------------------------------------\n I = (1:blksz) + (bch - 1)*blksz; %-voxel indices\n I = I(I <= numel(CrPl)*xdim*ydim); %-truncate\n xyz = [repmat(xords,1,numel(CrPl)); ...\n repmat(yords,1,numel(CrPl)); ...\n reshape(zords',1,[])];\n xyz = xyz(:,I); %-voxel coordinates\n nVox = size(xyz,2); %-number of voxels\n \n %-Get data & construct analysis mask\n %=================================================================\n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),'...read & mask data')\n Cm = true(1,nVox); %-current mask\n \n \n %-Compute explicit mask\n % (note that these may not have same orientations)\n %------------------------------------------------------------------\n for i = 1:length(xM.VM)\n \n %-Coordinates in mask image\n %--------------------------------------------------------------\n j = xM.VM(i).mat\\M*[xyz;ones(1,nVox)];\n \n %-Load mask image within current mask & update mask\n %--------------------------------------------------------------\n Cm(Cm) = spm_get_data(xM.VM(i),j(:,Cm),false) > 0;\n end\n \n %-Get the data in mask, compute threshold & implicit masks\n %------------------------------------------------------------------\n Y = zeros(nScan,nVox);\n for i = 1:nScan\n \n %-Load data in mask\n %--------------------------------------------------------------\n if ~any(Cm), break, end %-Break if empty mask\n Y(i,Cm) = spm_get_data(VY(i),xyz(:,Cm),false);\n \n Cm(Cm) = Y(i,Cm) > xM.TH(i); %-Threshold (& NaN) mask\n if xM.I && ~YNaNrep && xM.TH(i) < 0 %-Use implicit mask\n Cm(Cm) = abs(Y(i,Cm)) > eps;\n end\n end\n \n %-Mask out voxels where data is constant\n %------------------------------------------------------------------\n Cm(Cm) = any(diff(Y(:,Cm),1));\n Y = Y(:,Cm); %-Data within mask\n CrS = sum(Cm); %-# current voxels\n \n \n %==================================================================\n %-Proceed with General Linear Model (if there are voxels)\n %==================================================================\n if CrS\n \n %-Whiten/Weight data and remove filter confounds\n %--------------------------------------------------------------\n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),'...filtering');%-#\n \n KWY = spm_filter(xX.K,W*Y);\n \n %-General linear model: Weighted least squares estimation\n %--------------------------------------------------------------\n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),'...estimation');%-#\n \n beta = xX.pKX*KWY; %-Parameter estimates\n res = spm_sp('r',xX.xKXs,KWY); %-Residuals\n ResSS = sum(res.^2); %-Residual SSQ\n clear KWY %-Clear to save memory\n \n \n %-If ReML hyperparameters are needed for xVi.V\n %--------------------------------------------------------------\n if ~isfield(xVi,'V')\n \n %-F-threshold & accumulate spatially whitened Y*Y'\n %----------------------------------------------------------\n j = sum((Hsqr*beta).^2,1)/trMV > UF*ResSS/trRV;\n j = find(j);\n if ~isempty(j)\n q = size(j,2);\n s = s + q;\n q = spdiags(sqrt(trRV./ResSS(j)'),0,q,q);\n Y = Y(:,j)*q;\n Cy = Cy + Y*Y';\n end\n \n end % (xVi,'V')\n \n \n %-if we are saving the WLS (ML) parameters\n %--------------------------------------------------------------\n if isfield(xX,'W')\n \n %-sample covariance and mean of Y (all voxels)\n %----------------------------------------------------------\n CY = CY + Y*Y';\n EY = EY + sum(Y,2);\n \n %-Save betas etc. for current plane as we go along\n %----------------------------------------------------------\n CrBl = [CrBl, beta];\n CrResI = [CrResI, res(i_res,:)];\n CrResSS = [CrResSS, ResSS];\n \n end % (xX,'W')\n clear Y %-Clear to save memory\n \n end % (CrS)\n \n %-Append new inmask voxel locations and volumes\n %------------------------------------------------------------------\n XYZ(:,S + (1:CrS)) = xyz(:,Cm); %-InMask XYZ voxel coords\n Q = [Q I(Cm)]; %-InMask XYZ voxel indices\n S = S + CrS; %-Volume analysed (voxels)\n \n end % (bch)\n \n \n %-Plane complete, write plane to image files (unless 1st pass)\n %======================================================================\n if isfield(xX,'W')\n \n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),'...saving plane'); %-#\n \n jj = NaN(xdim,ydim,numel(CrPl));\n \n %-Write Mask image\n %------------------------------------------------------------------\n if ~isempty(Q), jj(Q) = 1; end\n VM = spm_write_plane(VM, ~isnan(jj), CrPl);\n \n %-Write beta images\n %------------------------------------------------------------------\n for i = 1:nBeta\n if ~isempty(Q), jj(Q) = CrBl(i,:); end\n Vbeta(i) = spm_write_plane(Vbeta(i), jj, CrPl);\n end\n \n %-Write standardised residual images\n %------------------------------------------------------------------\n for i = 1:nSres\n if ~isempty(Q), jj(Q) = CrResI(i,:)./sqrt(CrResSS/erdf); end\n VResI(i) = spm_write_plane(VResI(i), jj, CrPl);\n end\n \n %-Write ResSS into ResMS (variance) image scaled by tr(RV) above\n %------------------------------------------------------------------\n if ~isempty(Q), jj(Q) = CrResSS; end\n VResMS = spm_write_plane(VResMS, jj, CrPl);\n \n end % (xX,'W')\n \n %-Report progress\n %----------------------------------------------------------------------\n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),'...done'); %-#\n spm_progress_bar('Set',100*(bch + nbch*(z - 1))/(nbch*zdim));\n \n \nend % (for z = 1:zdim)\nfprintf('\\n'); %-#\nspm_progress_bar('Clear')\n \n%==========================================================================\n% - P O S T E S T I M A T I O N C L E A N U P\n%==========================================================================\nif S == 0, spm('alert!','No inmask voxels - empty analysis!'); return; end\n \n%-average sample covariance and mean of Y (over voxels)\n%--------------------------------------------------------------------------\nCY = CY/S;\nEY = EY/S;\nCY = CY - EY*EY';\n \n%-If not defined, compute non-sphericity V using ReML Hyperparameters\n%==========================================================================\nif ~isfield(xVi,'V')\n \n %-check there are signficant voxels\n %----------------------------------------------------------------------\n if s == 0\n spm('FigName','Stats: no significant voxels',Finter); \n spm('Pointer','Arrow');\n if isfield(SPM.xGX,'rg')&&~isempty(SPM.xGX.rg)\n figure(Finter);\n plot(SPM.xGX.rg);\n spm('alert*',{'Please check your data'; ...\n 'There are no significant voxels';...\n 'The globals are plotted for diagnosis'});\n else\n spm('alert*',{'Please check your data'; ...\n 'There are no significant voxels'});\n end\n warning('Please check your data: There are no significant voxels.');\n return\n end\n \n %-ReML estimate of residual correlations through hyperparameters (h)\n %----------------------------------------------------------------------\n str = 'Temporal non-sphericity (over voxels)';\n fprintf('%-40s: %30s\\n',str,'...ReML estimation'); %-#\n Cy = Cy/s;\n \n % ReML for separable designs and covariance components\n %----------------------------------------------------------------------\n if isstruct(xX.K)\n m = length(xVi.Vi);\n h = zeros(m,1);\n V = sparse(nScan,nScan);\n for i = 1:length(xX.K)\n \n % extract blocks from bases\n %--------------------------------------------------------------\n q = xX.K(i).row;\n p = [];\n Qp = {};\n for j = 1:m\n if nnz(xVi.Vi{j}(q,q))\n Qp{end + 1} = xVi.Vi{j}(q,q);\n p = [p j];\n end\n end\n \n % design space for ReML (with confounds in filter)\n %--------------------------------------------------------------\n Xp = xX.X(q,:);\n try\n Xp = [Xp xX.K(i).X0];\n end\n \n % ReML\n %--------------------------------------------------------------\n fprintf('%-30s\\n',sprintf(' ReML Block %i',i));\n [Vp,hp] = spm_reml(Cy(q,q),Xp,Qp);\n V(q,q) = V(q,q) + Vp;\n h(p) = hp;\n end\n else\n [V,h] = spm_reml(Cy,xX.X,xVi.Vi);\n end\n \n % normalize non-sphericity and save hyperparameters\n %----------------------------------------------------------------------\n V = V*nScan/trace(V);\n xVi.h = h;\n xVi.V = V; % Save non-sphericity xVi.V\n xVi.Cy = Cy; % spatially whitened \n SPM.xVi = xVi; % non-sphericity structure\n \n % If xX.W is not specified use W*W' = inv(V) to give ML estimators\n %----------------------------------------------------------------------\n if ~isfield(xX,'W')\n if spm_matlab_version_chk('7') >=0\n save('SPM','SPM','-V6');\n else\n save('SPM','SPM');\n end\n clear\n load SPM\n SPM = spm_spm(SPM);\n return\n end\nend\n \n \n%-Use non-sphericity xVi.V to compute [effective] degrees of freedom\n%==========================================================================\nxX.V = spm_filter(xX.K,spm_filter(xX.K,W*V*W')');% KWVW'K'\n[trRV trRVRV] = spm_SpUtil('trRV',xX.xKXs,xX.V); % trRV (for X)\nxX.trRV = trRV; % \nxX.trRVRV = trRVRV; %-Satterthwaite\nxX.erdf = trRV^2/trRVRV; % approximation\nxX.Bcov = xX.pKX*xX.V*xX.pKX'; % Cov(beta)\n \n \n%-Set VResMS scalefactor as 1/trRV (raw voxel data is ResSS)\n%--------------------------------------------------------------------------\nVResMS.pinfo(1) = 1/xX.trRV;\nVResMS = spm_create_vol(VResMS);\n \n%-Smoothness estimates of component fields and RESEL counts for volume\n%==========================================================================\ntry\n FWHM = SPM.xVol.FWHM;\n VRpv = SPM.xVol.VRpv;\n R = SPM.xVol.R;\ncatch\n [FWHM,VRpv,R] = spm_est_smoothness(VResI,VM,[nScan erdf]);\nend\n \n%-Delete the residuals images\n%==========================================================================\n% j = spm_select('List',SPM.swd,'^ResI_.{4}\\..{3}$');\n% for k = 1:size(j,1)\n% spm_unlink(deblank(j(k,:)));\n% end\n \n \n%-Compute scaled design matrix for display purposes\n%--------------------------------------------------------------------------\nxX.nKX = spm_DesMtx('sca',xX.xKXs.X,xX.name);\n \n \n%-Save remaining results files and analysis parameters\n%==========================================================================\nfprintf('%-40s: %30s','Saving results','...writing'); %-#\n \n%-place fields in SPM\n%--------------------------------------------------------------------------\nSPM.xVol.XYZ = XYZ(:,1:S); %-InMask XYZ coords (voxels)\nSPM.xVol.M = M; %-voxels -> mm\nSPM.xVol.iM = inv(M); %-mm -> voxels\nSPM.xVol.DIM = DIM; %-image dimensions\nSPM.xVol.FWHM = FWHM; %-Smoothness data\nSPM.xVol.R = R; %-Resel counts\nSPM.xVol.S = S; %-Volume (voxels)\nSPM.xVol.VRpv = VRpv; %-Filehandle - Resels per voxel\n \nSPM.Vbeta = Vbeta; %-Filehandle - Beta\nSPM.VResMS = VResMS; %-Filehandle - Hyperparameter\nSPM.VM = VM; %-Filehandle - Mask\n \nSPM.xVi = xVi; % non-sphericity structure\nSPM.xVi.CY = CY; %-<(Y - )*(Y - )'>\n \nSPM.xX = xX; %-design structure\n \nSPM.xM = xM; %-mask structure\n \nSPM.xCon = struct([]); %-contrast structure\n \nSPM.SPMid = SPMid;\nSPM.swd = pwd;\n \n \n%-Save analysis parameters in SPM.mat file\n%--------------------------------------------------------------------------\nif spm_matlab_version_chk('7') >=0\n save('SPM','SPM','-V6');\nelse\n save('SPM','SPM');\nend\n \n%==========================================================================\n%- E N D: Cleanup GUI\n%==========================================================================\nfprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...done') %-#\nspm('FigName','Stats: done',Finter); spm('Pointer','Arrow')\nfprintf('%-40s: %30s\\n','Completed',spm('time')) %-#\nfprintf('...use the results section for assessment\\n\\n') %-#\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Image_thresholding/cl_ext_spm_spm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.37267270773772404}} {"text": "function []=panel2disp(n,N,m,p,k,T,Ymat,Xmat,Units,endo,exo,const,beta_gibbs,B_median,beta_median,beta_std,beta_lbound,beta_ubound,sigma_gibbs,sigma_median,D_estimates,gamma_estimates,ar,lambda1,lambda3,lambda4,startdate,enddate,forecast_record,forecast_estimates,Fcperiods,stringdates3,Fstartdate,Fcenddate,Feval,Fcomp,data_endo_c,data_endo_c_lags,data_exo_c,It,Bu,IRF,IRFt,pref,names,PriorExcel)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n% obtain first a point estimate betatilde of the VAR coefficients\n% this is simply the median\nbetatilde=beta_median;\nBtilde=reshape(betatilde,k,n);\n\n% check whether the model is stationary\n[stationary eigmodulus]=bear.checkstable(betatilde,n,p,k);\n\n\n\n\n% the other measures are unit-specific, hence, loop over units\nfor ii=1:N\n\n% obtain predicted values\nYp(:,:,ii)=Xmat(:,:,ii)*B_median;\n% then produce the corresponding residuals, using (1.9.4)\nEPS(:,:,ii)=Ymat(:,:,ii)-Yp(:,:,ii);\n\n\n% Compute then the sum of squared residuals\n% compute first the RSS matrix, defined in (1.9.5)\nRSS(:,:,ii)=EPS(:,:,ii)'*EPS(:,:,ii);\n% retain only the diagonal elements to get the vector of RSSi values\nrss(:,:,ii)=diag(RSS(:,:,ii));\n\n\n% Go on calculating R2\n% generate Mbar\nMbar=eye(T)-ones(T,T)/T;\n% then compute the TSS matrix, defined in (1.9.8)\nTSS(:,:,ii)=Ymat(:,:,ii)'*Mbar*Ymat(:,:,ii);\n% generate the R2 matrix in (1.9.9)\nR2(:,:,ii)=eye(n)-RSS(:,:,ii)./TSS(:,:,ii);\n% retain only the diagonal elements to get the vector of R2 values\nr2(:,:,ii)=diag(R2(:,:,ii));\n\n\n% then calculate the adjusted R2, using (1.9.11)\nR2bar(:,:,ii)=eye(n)-((T-1)/(T-k))*(eye(n)-R2(:,:,ii));\n% retain only the diagonal elements to get the vector of R2bar values\nr2bar(:,:,ii)=diag(R2bar(:,:,ii));\n\nend\n\n\n\n\n% now start displaying and saving the results\n\n\n% preliminary task: create and open the txt file used to save the results\n\nfilelocation=fullfile(pref.results_path, [pref.results_sub '.txt']);\nfid=fopen(filelocation,'wt');\n\n% print toolbox header\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n% print the list of contributors\nbear.printcontributors(fid);\n\n% print then estimation results\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\ntoolboxinfo='BEAR toolbox estimates';\nfprintf('%s\\n',toolboxinfo);\nfprintf(fid,'%s\\n',toolboxinfo);\n\ntime=clock;\ndatestring=datestr(time);\ndateinfo=['Date: ' datestring(1,1:11) ' Time: ' datestring(1,13:17)];\nfprintf('%s\\n',dateinfo);\nfprintf(fid,'%s\\n',dateinfo);\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\nVARtypeinfo='Panel VAR: pooled estimator';\nfprintf('%s\\n',VARtypeinfo);\nfprintf(fid,'%s\\n',VARtypeinfo);\n\nif IRFt==1\nSVARinfo='structural decomposition: none';\nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\nelseif IRFt==2\nSVARinfo='structural decomposition: choleski factorisation'; \nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\nelseif IRFt==3\nSVARinfo='structural decomposition: triangular factorisation'; \nfprintf('%s\\n',SVARinfo);\nfprintf(fid,'%s\\n',SVARinfo);\nend\n\ntemp='units: ';\nfor ii=1:N\ntemp=[temp ' ' Units{ii,1} ' '];\nend\nunitinfo=temp;\nfprintf('%s\\n',unitinfo);\nfprintf(fid,'%s\\n',unitinfo);\n\ntemp='endogenous variables: ';\nfor ii=1:n\ntemp=[temp ' ' endo{ii,1} ' '];\nend\nendoinfo=temp;\nfprintf('%s\\n',endoinfo);\nfprintf(fid,'%s\\n',endoinfo);\n\ntemp='exogenous variables: ';\nif const==0 && m==0\ntemp=[temp ' none'];\nelseif const==1 && m==1\ntemp=[temp ' constant '];\nelseif const==0 && m>0\n for ii=1:m-1\n temp=[temp ' ' exo{ii,1} ' '];\n end\nelseif const==1 && m>1\ntemp=[temp ' constant '];\n for ii=1:m-1\n temp=[temp ' ' exo{ii,1} ' '];\n end\nend\nexoinfo=temp;\nfprintf('%s\\n',exoinfo);\nfprintf(fid,'%s\\n',exoinfo);\n\nsampledateinfo=['estimation sample: ' startdate '-' enddate];\nfprintf('%s\\n',sampledateinfo);\nfprintf(fid,'%s\\n',sampledateinfo);\n\nsamplelengthinfo=['sample size (omitting initial conditions): ' num2str(T)];\nfprintf('%s\\n',samplelengthinfo);\nfprintf(fid,'%s\\n',samplelengthinfo);\n\nlaginfo=['number of lags included in regression: ' num2str(p)];\nfprintf('%s\\n',laginfo);\nfprintf(fid,'%s\\n',laginfo);\n\nhyperparam1='hyperparameters:';\nfprintf('%s\\n',hyperparam1);\nfprintf(fid,'%s\\n',hyperparam1);\n\nif PriorExcel==1\n arprint=[];\n for ii=1:n\n arprint=[arprint num2str(ar(ii,1)) ' '];\n end\n hyperparam2=['autoregressive coefficients (ar): ' arprint];\nelse\n hyperparam2=['autoregressive coefficients (ar): ' num2str(ar(1,1))];\nend\nfprintf('%s\\n',hyperparam2);\nfprintf(fid,'%s\\n',hyperparam2);\n\nhyperparam3=['overall tightness (lambda1): ' num2str(lambda1)];\nfprintf('%s\\n',hyperparam3);\nfprintf(fid,'%s\\n',hyperparam3);\n\nhyperparam4=['lag decay (lambda3): ' num2str(lambda3)];\nfprintf('%s\\n',hyperparam4);\nfprintf(fid,'%s\\n',hyperparam4);\n\nhyperparam5=['exogenous variable tightness (lambda4): ' num2str(lambda4(1,1))];\nfprintf('%s\\n',hyperparam5);\nfprintf(fid,'%s\\n',hyperparam5);\n\n\n\n% display coefficient estimates\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\ncoeffinfo=['VAR coefficients (Common to all units):'];\nfprintf('%s\\n',coeffinfo);\nfprintf(fid,'%s\\n',coeffinfo);\n\n\nfor ii=1:n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nif ii~=1\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nend\n\nendoinfo=['Endogenous: ' endo{ii,1}];\nfprintf('%s\\n',endoinfo);\nfprintf(fid,'%s\\n',endoinfo);\n\ncoeffheader=fprintf('%25s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\ncoeffheader=fprintf(fid,'%25s %15s %15s %15s %15s\\n','','Median','St.dev','Low.bound','Upp.bound');\n\n% handle the endogenous\n for jj=1:n\n for kk=1:p\n values=[beta_median((ii-1)*k+n*(kk-1)+jj,1) beta_std((ii-1)*k+n*(kk-1)+jj,1) beta_lbound((ii-1)*k+n*(kk-1)+jj,1) beta_ubound((ii-1)*k+n*(kk-1)+jj,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',strcat(endo{jj,1},'(-',int2str(kk),')'),values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',strcat(endo{jj,1},'(-',int2str(kk),')'),values);\n end\n end\n\n% handle the exogenous\n % if there is no constant:\n if const==0\n % if there is no exogenous at all, obvioulsy, don't display anything\n if m==0\n % if there is no constant but some other exogenous, display them\n else\n for jj=1:m\n values=[beta_median(ii*k-m+jj,1) beta_std(ii*k-m+jj,1) beta_lbound(ii*k-m+jj,1) beta_ubound(ii*k-m+jj,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n end\n end\n % if there is a constant\n else\n % display the results related to the constant\n values=[beta_median(ii*k-m+1,1) beta_std(ii*k-m+1,1) beta_lbound(ii*k-m+1,1) beta_ubound(ii*k-m+1,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n','Constant',values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n','Constant',values);\n % if there is no other exogenous, stop here\n if m==1\n % if there are other exogenous, display their results\n else\n for jj=1:m-1\n values=[beta_median(ii*k-m+jj+1,1) beta_std(ii*k-m+jj+1,1) beta_lbound(ii*k-m+jj+1,1) beta_ubound(ii*k-m+jj+1,1)];\n fprintf('%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n fprintf(fid,'%25s %15.3f %15.3f %15.3f %15.3f\\n',exo{jj,1},values);\n end\n end\n end\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n\n% display evaluation measures\n\n % loop over units\n for jj=1:N\n unitinfo=['unit: ' Units{jj,1}];\n fprintf('%s\\n',unitinfo);\n fprintf(fid,'%s\\n',unitinfo);\n\n rssinfo=['Sum of squared residuals: ' num2str(rss(ii,1,jj),'%.2f')];\n fprintf('%s\\n',rssinfo);\n fprintf(fid,'%s\\n',rssinfo);\n\n r2info=['R-squared: ' num2str(r2(ii,1,jj),'%.3f')];\n fprintf('%s\\n',r2info);\n fprintf(fid,'%s\\n',r2info);\n\n adjr2info=['adj. R-squared: ' num2str(r2bar(ii,1,jj),'%.3f')];\n fprintf('%s\\n',adjr2info);\n fprintf(fid,'%s\\n',adjr2info);\n\n fprintf('%s\\n','');\n fprintf(fid,'%s\\n','');\n\n end\n\nend\n\n\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n% display VAR stability results\neigmodulus=reshape(eigmodulus,p,n);\nstabilityinfo1=['Roots of the characteristic polynomial (modulus):'];\nfprintf('%s\\n',stabilityinfo1);\nfprintf(fid,'%s\\n',stabilityinfo1);\nfor jj=1:p\ntemp=num2str(eigmodulus(jj,1),'%.3f');\n for kk=2:n\n temp=[temp,' ',num2str(eigmodulus(jj,kk),'%.3f')];\n end\nfprintf('%s\\n',temp);\nfprintf(fid,'%s\\n',temp);\nend\nif stationary==1;\nstabilityinfo2=['No root lies outside the unit circle.'];\nstabilityinfo3=['The estimated VAR model satisfies the stability condition'];\nfprintf('%s\\n',stabilityinfo2);\nfprintf(fid,'%s\\n',stabilityinfo2);\nfprintf('%s\\n',stabilityinfo3);\nfprintf(fid,'%s\\n',stabilityinfo3);\nelse\nstabilityinfo2=['Warning: at leat one root lies on or outside the unit circle.'];\nstabilityinfo3=['The estimated VAR model will not be stable'];\nend\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\nfprintf('%s\\n','');\nfprintf(fid,'%s\\n','');\n\n\n% display posterior for sigma\nsigmainfo=['sigma (residual covariance matrix): posterior estimates'];\nfprintf('%s\\n',sigmainfo);\nfprintf(fid,'%s\\n',sigmainfo);\n% calculate the (integer) length of the largest number in sigma, for formatting purpose\nwidth=length(sprintf('%d',floor(max(abs(bear.vec(sigma_median))))));\n% add a separator, a potential minus sign, and three digits (total=5) to obtain the total space for each entry in the matrix\nwidth=width+5;\nfor ii=1:n\ntemp=[];\n for jj=1:n\n % convert matrix entry into string\n number=num2str(sigma_median(ii,jj),'% .3f');\n % pad potential missing blanks\n while numel(number) % turn off a few editor warnings...\n\n%% --- using the Common Spatial Pattern method ---\n\n% load the data set (BCI2000 format)\ntraindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);\n\n% define the approach (here: Common Spatial Patterns without any customization)\nmyapproach = 'CSP';\n\n% learn a predictive model\n[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'}); \ndisp(['training mis-classification rate: ' num2str(trainloss*100,3) '%']);\n\n% visualize results\nbci_visualize(lastmodel)\n\n%% --- using the Common Spatial Pattern method with some custom options ---\n\n% load the data set (BCI2000 format)\ntraindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);\n\n% define the approach \n% Note: The settings found in the GUI \"Review/Edit Approach\" Panel can be translated literally\n% into cell array representations as below. Each paradigm has a few top-level parameter groups\n% (for CSP: SignalProcessing, FeatureExtraction, etc), which in turn have sub-parameters\n% (e.g., SignalProcessing has EpochExtraction, SpectralSelection, Resampling, etc.), and so\n% on. Some parameters are numbers, strings, cell arrays, etc. You only need to specify those \n%\t parameters where you actually want to deviate from the paradigm's defaults.\n%\n% For illustratory purposes, we use a different window relative to the target markers (0.5s to 3s after),\n% and a somewhat customized FIR frequency filter with a pass-band between ~7.5Hz and ~27Hz.\nmyapproach = {'CSP' 'SignalProcessing',{'EpochExtraction',[0.5 3],'FIRFilter',[7 8 26 28]}};\n\n% learn a predictive model\n[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'}); \ndisp(['training mis-classification rate: ' num2str(trainloss*100,3) '%']);\n\n% visualize results\nbci_visualize(lastmodel)\n\n\n%% --- applying the CSP model to some data (here: same data) ---\n\n% apply the previously learned model to a data set (querying it for each target marker in the data)\n[prediction,loss,teststats,targets] = bci_predict(lastmodel,traindata);\n\n% display the results\ndisp(['test mis-classification rate: ' num2str(loss*100,3) '%']);\ndisp([' predicted classes: ',num2str(round(prediction{2}*prediction{3})')]); % class probabilities * class values\ndisp([' true classes : ',num2str(round(targets)')]);\n\n\n%% --- the same using pseudo-online processing ---\n\n% This function is quite flexible, but here we only ask it to query the BCI seconds after each of the given markers\n[predictions,latencies] = onl_simulate(traindata,lastmodel,'markers',{'StimulusCode_2','StimulusCode_3'},'offset',3);\n\n% now check the prediction accuracy by hand (we knew the correct target label at each of the markers)\naccuracy = mean(argmax(predictions') == targets');\ndisp(['pseudo-online mis-classification rate: ' num2str((1-accuracy)*100,3) '%']);\n\n\n%% --- using the Spectrally weighted Common Spatial Pattern (Spec-CSP) method ---\n% this method automatically learns the spectral filters (within a pre-defined range), but it \n% may run into a local optimum or over-fit spuriously correlated bands\n\n% load the data set\ntraindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);\n\n% define the approach\nmyapproach = {'SpecCSP' 'SignalProcessing',{'EpochExtraction',[0.5 3]}};\n\n% learn a predictive model\n[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'}); %#ok<>\n\n% visualize results\nbci_visualize(lastmodel)\n\n\n%% --- test the learned model in simulated real-time processing ---\n% ( click into the figure to stop the update (and make sure that your click was registered) )\n\n% load feedback session\ntestdata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/feedback/DanielS001R01.dat','channels',1:29);\n\n% play it back in real time\nrun_readdataset('Dataset',testdata);\n\n% process data in real time using lastmodel, and visualize outputs\nrun_writevisualization('Model',lastmodel, 'VisFunction','bar(y);ylim([0 1])');\n\n% make sure that the online processing gets terminated...\ndisp('Click into the figure to stop online processing.'); \nwaitforbuttonpress; onl_clear; close(gcf);\n\n\n%% --- train an alternative model with parameter search ---\n% (over possible values for the number of pattern pairs, using CSP; note: this takes quite some time!)\n% (the number of pattern pairs found optimal should be 3 in this case)\n\n% load the data set (BCI2000 format)\ntraindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);\n\n% define approach\nmyapproach = {'CSP' 'Prediction',{'FeatureExtraction',{'PatternPairs',search(1,2,3)}}};\n\n% learn the model\n[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});\ndisp(['training mis-classification rate: ' num2str(trainloss*100,3) '%']);\n\n% visualize results\nbci_visualize(lastmodel);\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/userscripts/tutorial_erd1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3724036023959944}} {"text": " function st = ct_geom_par(type, varargin)\n%|function st = ct_geom_par(type, varargin)\n%|\n%| Same as ct_geom, but adds a rebinned variable\n%| ct_geom should be changed to include a new type instead\n%|\n%| Create the \"CT geometry\" structure that describes the sampling\n%| characteristics of a cone-beam CT system (axial or helical).\n%| (Use sino_geom() for 2D fan-beam or parallel-beam systems.)\n%|\n%| in\n%|\ttype\t'fan'\t\tmulti-slice fan-beam - recommended\n%|\t\t'par'\t\t(parallel-beam only weakly supported)\n%|\n%| options for all geometries\n%|\t'orbit_start'\t\tdefault: 0\n%|\t'orbit'\t\t\t[degrees] default: 180 for parallel / mojette\n%|\t\t\t\t\tor 360 for fan (negative for CW)\n%|\t\t\t\t\tcan be 'short' for fan-beam short scan\n%|\t'down'\t\t\tdown-sampling factor, for testing\n%|\t\t\t\t\tcan be [down_s down_t down_a]\n%|\t'units'\t\t\tstring to print distance units (default: 'mm')\n%|\n%| options for fan-beam\n%|\t'ns'\t\t\t# of horizontal samples\n%|\t'nt'\t\t\t# of vertical samples\n%|\t'na' | 'nbeta'\t\t# of angular samples\n%|\t'ds'\t\t\thorizontal sample spacing (default: 1)\n%|\t'dt'\t\t\tvertical sample spacing (default: -ds)\n%|\t\t\t\tor {'dz', dz} to use dz * dsd / dso (usual CT)\n%|\t'offset_s'\t\tunitless fraction of a channel (default: 0)\n%|\t\t\t\t(relative to line between two center channels).\n%|\t\t\t\tuse 0.25 or 1.25 for \"quarter-detector offset\"\n%|\t'offset_t'\t\tunitless (default: 0)\n%|\n%| options for partial scans (added by jang-hwan cho)\n%|\t'nframe'\t\t# of frames to divide orbit into (default: 1)\n%|\t'frame'\t\t\twhich frame? (default: 1)\n%|\n%| options for helical (or step-and-shoot)\n%|\t'pitch'\t\t\tbed_travel_per_rotation / axial_fov. default: 0.\n%|\t\t\t\t(unitless. can be negative. usually near 1.0)\n%|\t'source_z0'\t\tz-location of source for first view. Default 0.\n%|\t\t\t\t\tIt must have same units as dt and ds.\n%|\t\t\t\tUse 'center' to center the helix around z=0.\n%|\n%|\t'user_source_zs' [na]\tuser-specified source z-locations for each view.\n%|\t\t\t\tusually this is empty (default) in which case\n%|\t\t\t\tsource_zs is computed internally from \"pitch\"\n%|\t\t\t\tIt must have same units as dt and ds.\n%|\n%|\tfan beam distances:\n%|\t'dsd' | 'dis_src_det'\tdefault: inf (parallel beam)\n%|\t'dso' | 'dis_src_iso'\tdefault: inf (parallel beam)\n%|\t'dod' | 'dis_iso_det'\tdefault: 0\n%|\t'dfs' | 'dis_foc_src'\tdefault: 0 (3rd generation CT arc),\n%|\t\t\t\t\tuse 'inf' for flat detector\n%|\n%| out\n%|\tst\t(struct)\tinitialized structure\n%|\n%| methods\n%|\tst.shape(sino)\t\treshape sinograms that are columns into 3d array\n%|\tst.s\t\t\ts sample locations\n%|\tst.t\t\t\tt sample locations\n%|\tst.gamma\t\t[nb] gamma sample values [radians]\n%|\tst.gamma_max\t\thalf of fan angle [radians]\n%|\tst.ws\t\t\t(ns-1)/2 + st.offset_s\n%|\tst.wt\t\t\t(nt-1)/2 + st.offset_t\n%|\tst.ad\t\t\t[na] source angles in degrees\n%|\tst.ar\t\t\t[na] source angles in radians\n%|\tst.dim\t\t\tdimensions: [st.ns st.nt st.na]\n%|\tst.downsample(down)\treduce sampling by integer factor\n%|\tst.ones\t\t\tones(ns,nt,na, 'single')\n%|\tst.zeros\t\tzeros(ns,nt,na, 'single')\n%|\tst.rmax\t\t\tmax radius within FOV\n%|\tst.footprint_size(ig)\tmax footprint width in 's'\n%|\tst.zfov\t\t\taxial FOV\n%|\tst.source_zs\t\t[na] z-locations of source for each view\n%|\tst.shape(sino(:))\treshape to [ns,nt,na,?]\n%|\tst.unitv(is,it,ia)\tunit 'vector' with one nonzero element\n%|\tst.plot([ig])\t\tshow geometry\n%|\n%|\ttrick: you can make orbit=0 and orbit_start = column vector (length na)\n%|\tif you need nonuniformly spaced projection view angles.\n%|\n%| Copyright 2006-1-18, Jeff Fessler and Jang-Hwan Cho, University of Michigan\n%|\n%| 2009-12-04 modified source_zs definition to use source_z0, eliminate na/2\n%| 2012-12-09 modified by Greg Handy to include the rebinned variable\n\nif nargin == 1 && streq(type, 'test'), ct_geom_test, return, end\nif nargin < 1, help(mfilename), error(mfilename), end\n\nif streq(type, 'ge1') % special case: GE fan-beam\n\tst = ct_geom_ge1(type, varargin{:});\nreturn\nend\n\nif streq(type, 'ge2') % special case: GE axial or helical\n\tst = ct_geom_ge2(type, varargin{:});\nreturn\nend\n\nif streq(type, 'hd1') % special case: GE HD (UM only)\n\tst = ct_geom_hd1(type, varargin{:});\nreturn\nend\n\n% defaults\nst.type = type;\nst.rebinned = false;\nst.ns = [];\nst.nt = [];\nst.na = [];\nst.down = 1;\nst.nframe = 1; % entire scan as 1 \"frame\"\nst.frame = 1;\nst.orbit_start = 0;\nst.pitch = 0; % default for axial\nst.source_z0 = 0; % default for axial\nst.units = 'mm';\nst.user_source_zs = [];\n\nif streq(type, 'fan')\n\tst = ct_geom_fan(st, varargin{:});\n%elseif streq(type, 'par')\n%\tst = ct_geom_par(st, varargin{:});\n%elseif streq(type, 'moj')\n%\tst = ct_geom_moj(st, varargin{:});\nelse\n\tfail('unknown sinotype %s', type)\nend\n\nif isempty(st.na), st.na = 2 * floor(st.ns * pi/2 / 2); end\n\nct_geom_checks(st)\n\nmeth = { ...\n\t's', @ct_geom_s, '()'; ...\n\t't', @ct_geom_t, '()'; ...\n\t'ws', @ct_geom_ws, '()'; ...\n\t'wt', @ct_geom_wt, '()'; ...\n\t'ad', @ct_geom_ad, '()'; ...\n\t'ar', @ct_geom_ar, '()'; ...\n\t'gamma', @ct_geom_gamma, '()'; ...\n\t'gamma_max', @ct_geom_gamma_max, '()'; ...\n\t'zfov', @ct_geom_zfov, '()'; ...\n\t'source_dz_per_view', @ct_geom_source_dz_per_view, '()'; ...\n\t'source_zs', @ct_geom_source_zs, '() -> [na]'; ...\n\t'orbit_short', @ct_geom_orbit_short, '()'; ...\n\t'xds', @ct_geom_xds, '()'; ...\n\t'yds', @ct_geom_yds, '()'; ...\n\t'downsample', @ct_geom_downsample, '()'; ...\n\t'dim', @ct_geom_dim, '()'; ...\n\t'ones', @ct_geom_ones, '()'; ...\n\t'rmax', @ct_geom_rmax, '()'; ...\n\t'footprint_size', @ct_geom_footprint_size, '(ig)'; ...\n\t'unitv', @ct_geom_unitv, '() | (is,it,ia)'; ...\n\t'zeros', @ct_geom_zeros, '()'; ...\n\t'shape', @ct_geom_shape, '()'; ...\n\t'plot', @ct_geom_plot, '() | (ig)';\n\t'plot3', @ct_geom_plot3, '() | (ig)';\n\t};\n\nst = strum(st, meth);\n\nif streq(st.source_z0, 'center')\n\tst.source_z0 = -st.na/2 * st.source_dz_per_view;\nend\n\nif any(st.down ~= 1)\n\tdown = st.down; st.down = 1; % trick\n\tst = st.downsample(down);\nend\n\nif streq(type, 'fan') && streq(st.orbit, 'short')\n\tst.orbit = st.orbit_short / st.nframe; % jc\n\tst.orbit_start = st.orbit_start + (st.frame - 1) * st.orbit; % jc/jf\n\tif st.frame ~= 1, warn 'untested and possibly incorrect', end % jf\nend\n\n\n% ct_geom_orbit_short()\nfunction os = ct_geom_orbit_short(st)\nos = 180 + 2 * rad2deg(st.gamma_max);\n\n\n% ct_geom_dim()\nfunction dim = ct_geom_dim(st)\ndim = [st.ns st.nt st.na];\nif isempty(st.ns) || isempty(st.nt) || isempty(st.na)\n\terror 'dim requested without ns,nt,na'\nend\n\n\n% ct_geom_ones()\n% sinogram of all ones\nfunction out = ct_geom_ones(st)\nout = ones(st.dim, 'single');\n\n\n% ct_geom_zeros()\n% sinogram of all zeros\nfunction out = ct_geom_zeros(st)\nout = zeros(st.dim, 'single');\n\n\n% ct_geom_unitv()\n% sinogram with just one ray\nfunction out = ct_geom_unitv(st, is, it, ia)\nout = st.zeros;\nif ~isvar('is') || isempty(is)\n\tis = floor(st.ns/2 + 1);\n\tit = floor(st.nt/2 + 1);\n\tia = 1;\nend\nout(is,it,ia) = 1;\n\n\n% ct_geom_rmax()\n% max radius within fov\nfunction rmax = ct_geom_rmax(st)\nsmax = max(abs(st.s));\nif streq(st.type, 'fan')\n\tif isinf(st.dso) % parallel\n\t\trmax = smax;\n\telseif st.dfs == 0 % arc\n\t\trmax = st.dso * sin(smax / st.dsd);\n\telseif isinf(st.dfs) % flat\n\t\trmax = st.dso * sin(atan(smax / st.dsd));\n\telse\n\t\terror 'unknown case'\n\tend\nend\n\n\n% ct_geom_ws()\n% 'middle' sample position\nfunction ws = ct_geom_ws(st)\nws = (st.ns-1)/2 + st.offset_s;\n\n\n% ct_geom_wt()\n% 'middle' sample position\nfunction wt = ct_geom_wt(st)\nwt = (st.nt-1)/2 + st.offset_t;\n\n\n% ct_geom_s()\n% sample locations ('radial')\nfunction s = ct_geom_s(st, varargin)\ns = st.ds * ([0:st.ns-1]' - st.ws);\nif length(varargin)\n\ts = s(varargin{:});\nend\n\n\n% ct_geom_t()\n% sample locations ('radial')\nfunction t = ct_geom_t(st, varargin)\nt = st.dt * ([0:st.nt-1]' - st.wt);\nif length(varargin)\n\tt = t(varargin{:});\nend\n\n\n% ct_geom_ad()\n% angular sample locations (degrees)\nfunction ang = ct_geom_ad(st, varargin)\nang = [0:st.na-1]'/st.na * st.orbit + st.orbit_start;\nang = ang(varargin{:});\n\n% ct_geom_ar()\n% angular sample locations (radians)\nfunction ang = ct_geom_ar(st, varargin)\nang = deg2rad(ct_geom_ad(st));\nang = ang(varargin{:});\n\n\n% ct_geom_shape()\n% reshape into sinogram array\nfunction sino = ct_geom_shape(st, sino)\nsino = reshapee(sino, st.ns, st.nt, st.na, []);\n\n\n% ct_geom_downsample()\n% down-sample (for testing)\nfunction st = ct_geom_downsample(si, down)\nst = si;\nst.down = st.down .* down;\n\nswitch numel(down)\ncase 1\n\tdown_s = down;\n\tdown_t = down;\n\tdown_a = down;\ncase 3\n\tdown_s = down(1);\n\tdown_t = down(2);\n\tdown_a = down(3);\notherwise\n\tfail('bad down %g', down)\nend\nclear down\n\nst.ns = 4 * ceil(st.ns / down_s / 4); % multiple of 4 for simd\nst.nt = 2 * ceil(st.nt / down_t / 2); % keep it even\n\nuser_specified = false; % did user specify zs or orbit_start vector?\n\nif ~isempty(st.user_source_zs)\n\tst.user_source_zs = st.user_source_zs(1:down_a:st.na);\n\tuser_specified = true;\nend\n\nif numel(st.orbit_start) > 1\n\tst.orbit_start = st.orbit_start(1:down_a:si.na);\n\tuser_specified = true;\nend\n\nif streq(st.type, 'fan')\n\tst.ds = st.ds * down_s;\n\tst.dt = st.dt * down_t;\nelse\n\tfail('unknown sinotype \"%s\"', type)\nend\n\nif user_specified % if user-specified then just decimate\n\tst.na = length([1:down_a:st.na]);\n\nelseif all(diff(si.source_zs) == 0) % axial\n\tst.na = max(1, round(si.na / down_a)); % at least one view\n\nelse % helical described by pitch and source_z0\n\tnturn = si.orbit / 360;\n\tna1 = si.na / nturn; % # of views in 1 turn, originally\n\n\t% if it is helical with equal view spacing, then adjust orbit slightly,\n\t% to preserve integer number of views per turn (if applicable)\n\ttol = 1e-4;\n\tif abs(round(na1) - na1) < tol % integer views per turn\n\t\tna2 = round(na1 / down_a); % new # of views in 1 turn (integer)\n\t\ttmp = nturn * na2; % new na value, roughly na/down\n\t\tif abs(round(tmp) - tmp) < tol\n\t\t\tst.na = round(tmp);\n\t\telse % adjust orbit\n\t\t\tst.na = floor(tmp);\n\t\t\tst.orbit = 360 / na2 * st.na;\n\t\tend\n\telse\n\t\tst.na = round(si.na / down_a);\n\tend\nend\n\n\n% ct_geom_zfov()\n% axial FOV, considering magnification factor, as collimated at iso\nfunction zfov = ct_geom_zfov(st)\nif isinf(st.dso) || isinf(st.dsd) % parallel beam\n\tzfov = st.nt * st.dt;\nelse % cone\n\tzfov = st.dso / st.dsd * st.nt * st.dt;\nend\n\n\n% ct_geom_source_dz_per_view()\n% source axial travel for each view\nfunction out = ct_geom_source_dz_per_view(st)\nif ~isempty(st.user_source_zs), fail 'undefined', end\nif st.na == 1 % for tomosynthesis\n\tout = 0;\n\treturn\nend\nif ~st.pitch\n\tout = 0;\n\treturn\nend\nif length(st.orbit) ~= 1 || st.orbit == 0\n\tfail 'dz_per_view undefined for user angles'\nend\nna_per_360 = st.na * (360 / st.orbit); % # views per turn\nout = st.pitch * st.zfov / na_per_360;\n\n\n% ct_geom_checks\n% check vectors user_source_zs and orbit_start\nfunction ct_geom_checks(st)\nif ~isempty(st.user_source_zs) && (st.pitch ~= 0)\n\tfail('only one of \"pitch\" (recommended) or user_source_zs can be given')\nend\nif ~isempty(st.user_source_zs) && length(st.user_source_zs) ~= st.na\n\tfail('user_source_zs size mismatch')\nend\nif numel(st.orbit_start) > 1 && numel(st.orbit_start) ~= st.na\n\tfail('orbit_start vector length')\nend\n\n\n% ct_geom_source_zs()\n% source z locations\nfunction source_zs = ct_geom_source_zs(st, varargin)\n\nif ~isempty(st.user_source_zs) % user-provided\n\tsource_zs = st.user_source_zs;\n\tsource_zs = source_zs(varargin{:});\nelse\n\tsource_dz = st.source_dz_per_view;\n\tsource_zs = st.source_z0 + [0:st.na-1]' * source_dz;\n\tsource_zs = source_zs(varargin{:});\nend\n\n\n% ct_geom_gamma()\n% gamma sample values\nfunction gamma = ct_geom_gamma(st, varargin)\nswitch st.dfs\ncase 0\n\tgamma = st.s / st.dsd; % 3rd gen: equiangular arc\ncase inf\n\tgamma = atan(st.s / st.dsd); % flat\notherwise\n\terror 'dfs not done'\nend\ngamma = gamma(varargin{:});\n\n\n% ct_geom_gamma_max()\nfunction gamma_max = ct_geom_gamma_max(st)\ngamma_max = max(st.gamma);\n\n\n% ct_geom_xds()\n% center positions of detectors\nfunction xds = ct_geom_xds(st, varargin)\nswitch st.type\ncase 'par'\n\txds = st.s;\ncase 'fan'\n\tswitch st.dfs\n\tcase 0 % arc\n\t\txds = st.dsd * sin(st.gamma);\n\tcase inf % flat\n\t\txds = st.s;\n\totherwise\n\t\terror 'not done'\n\tend\notherwise\n\terror 'bug'\nend\n\n\n% ct_geom_yds()\n% center positions of detectors\nfunction yds = ct_geom_yds(st, varargin)\nswitch st.type\ncase 'par'\n\tyds = zeros(size(st.s));\n\ncase 'fan'\n\tswitch st.dfs\n\tcase 0 % arc\n\t\tyds = st.dso - st.dsd * cos(st.gamma);\n\tcase inf % flat\n\t\tyds = -st.dod * ones(size(st.s));\n\totherwise\n\t\terror 'not done'\n\tend\notherwise\n\terror 'bug'\nend\n\n\n% ct_geom_footprint_size()\n% biggest possible footprint over image\nfunction footprint_size = ct_geom_footprint_size(st, ig, varargin)\ndi = sqrt(ig.dx^2 + ig.dy^2);\nsmax = max(abs(st.s));\nrfov = max(ig.nx * ig.dx, ig.ny * ig.dy) / 2;\ndso = st.dso;\ndsd = st.dsd;\nif rfov > 0.99 * dso, error 'bad dso', end\n\nif isinf(st.dso) % parallel\n\tfootprint_size = di;\nelseif st.dfs == 0 % arc3\n\tfootprint_size = di * dsd / (dso - rfov);\nelseif isinf(st.dfs) % flat\n\tfootprint_size = di * sqrt(dsd^2 + smax^2) / (dso - rfov);\nelse\n\terror 'unknown case'\nend\nfootprint_size = footprint_size / st.ds; % unitless \n\n\n%\n% ct_geom_fan()\n%\nfunction st = ct_geom_fan(st, varargin);\n\n% defaults\nst.orbit = 360; % [degrees]\nst.ds\t\t= 1;\nst.dt\t\t= [];\nst.offset_s\t= 0;\nst.offset_t\t= 0;\n\nst.dsd = [];\t% dis_src_det\nst.dso = [];\t% dis_src_iso\nst.dod = [];\t% dis_iso_det\nst.dfs = 0;\t% dis_foc_src (3rd gen CT)\n\nsubs = { ...\n\t'src_det_dis', 'dsd';\n\t'dis_src_det', 'dsd';\n\t'dis_src_iso', 'dso';\n\t'dis_iso_det', 'dod';\n\t'dis_foc_src', 'dfs';\n\t'nbeta', 'na';\n\t'source_zs', 'user_source_zs';\n\t};\nst = vararg_pair(st, varargin, 'subs', subs);\n\n% work out distances\nif (~isempty(st.dsd) && isinf(st.dsd)) ...\n|| (~isempty(st.dso) && isinf(st.dso)) % handle parallel-beam case gracefully\n\tst.dsd = inf; st.dso = inf; st.dod = 1;\nend\nif isempty(st.dsd) + isempty(st.dso) + isempty(st.dod) > 1\n\terror 'must provide at least two of dsd, dso, dod'\nend\nif isempty(st.dsd), st.dsd = st.dso + st.dod; end\nif isempty(st.dso), st.dso = st.dsd - st.dod; end\nif isempty(st.dod), st.dod = st.dsd - st.dso; end\nif st.dso + st.dod ~= st.dsd\n\terror 'bad fan-beam distances'\nend\n\nif isempty(st.dt), st.dt = -st.ds; end\nif iscell(st.dt)\n\tif length(st.dt) == 2 && streq(st.dt{1}, 'dz')\n\t\tdz = st.dt{2};\n\t\tst.dt = dz * st.dsd / st.dso;\n\t\tprintm('dt = dz * dsd / dso = %g * %g / %g = %g', ...\n\t\t\tdz, st.dsd, st.dso, st.dt)\n\telse\n\t\tfail 'bad dt cell'\n\tend\nend\n\n\n% ct_geom_plot2()\n% picture of 2D source position / detector geometry\nfunction ct_geom_plot2(st, ig, varargin)\narg.tomosyn = false; % set to 1 for offset_x plotting trick\narg = vararg_pair(arg, varargin);\nif arg.tomosyn, fail 'not done', end\nif ~streq(st.type, 'fan'), error 'only fan done', end\nx0 = 0;\ny0 = st.dso;\nt = linspace(0,2*pi,1001);\n\nif isinf(st.dsd) % parallel beam\n\trfov = max(abs(st.s));\n\tplot(\t0, 0, '.', ...\n\t\trfov * cos(t), rfov * sin(t), 'm:', ...\n\t\tst.s, -rfov, 'yo')\n\nelse % fan beam\n\n\trot = deg2rad(st.orbit_start);\n\trot = [cos(rot) sin(rot); -sin(rot) cos(rot)];\n\tp0 = rot * [x0; y0];\n\tpd = rot * [st.xds'; st.yds'];\n\trfov = st.dso * sin(max(abs(st.gamma)));\n\n\tplot(\tp0(1), p0(2), 'ys', ... % source\n\t\tst.dso * cos(t), st.dso * sin(t), 'c--', ... % source circle\n\t\tpd(1,:), pd(2,:), 'yo') % detector elements\n\n\thold on\n\tif isvar('ig') && ~isempty(ig)\n\t\txmin = min(ig.x); xmax = max(ig.x);\n\t\tymin = min(ig.y); ymax = max(ig.y);\n\t\tim(ig.x, ig.y, ig.mask(:,:,1))\n\n\t\tplot([xmax xmin xmin xmax xmax], [ymax ymax ymin ymin ymax], 'g-')\n\tend\n\n\tplot(\t0, 0, '.', ...\n\t\t[pd(1,1) p0(1) pd(1,end)], [pd(2,1) p0(2) pd(2,end)], 'r-', ...\n\t\trfov * cos(t), rfov * sin(t), 'm:')\n\n\taxis equal, axis tight\n\thold off\n\nend\n\n\nif isvar('ig') && ~isempty(ig)\n\thold on\n\txmin = min(ig.x); xmax = max(ig.x);\n\tymin = min(ig.y); ymax = max(ig.y);\n\tplot([xmax xmin xmin xmax xmax], [ymax ymax ymin ymin ymax], 'g-')\n\thold off\nend\ntitlef('fov = %g', rfov)\naxis square, zoom on\n\n\n% ct_geom_plot3()\n% picture of 3D helical CT geometry\nfunction dummy = ct_geom_plot3(st, ig)\ndummy = [];\nif ~streq(st.type, 'fan'), error 'only fan done', end\n\nif isinf(st.dso) || isinf(st.dsd)\n\twarn 'parallel-beam plot not done'\nreturn\nend\n\nt1 = -st.dso * sin(st.ar); % source x pos\nt2 = st.dso * cos(st.ar); % source y pos\nt3 = st.source_zs; % source z pos\nplot3(t1, t2, t3, 'y.') % source trajectory\nview(-110, 22)\nhold on\nfor ia = [1 1+floor(st.na/2) st.na]\n\ttext(t1(ia), t2(ia), t3(ia), sprintf('%d', ia))\nend\n\n% axes\nr100 = @(x) 100 * ceil(max(abs(x)) / 100);\nr10 = @(x) 10 * ceil(max(abs(x)) / 10);\nplot3([-1 1] * r100(t1), [0 0], [0 0])\ntext(r100(t1), 0, 'x')\nplot3([0 0], [-1 1] * r100(t2), [0 0])\ntext(0, r100(t2), 'y')\nplot3([0 0], [0 0], [-1 1] * r10(t3))\ntext(0, 0, r10(t3), 'z')\n\ngrid on\nxlabelf('x (%s)', st.units)\nylabelf('y (%s)', st.units)\nzlabelf('z (%s)', st.units)\n\nif isvar('ig') && ~isempty(ig) && isfield(ig.meth,'z') % image box\n\txmin = min(ig.x); xmax = max(ig.x);\n\tymin = min(ig.y); ymax = max(ig.y);\n\tzmin = min(ig.z); zmax = max(ig.z);\n\tplot3(\t[xmin xmax xmax xmin xmin ], ...\n\t\t[ymin ymin ymax ymax ymin ], ...\n\t\t[zmin zmin zmin zmin zmin ], ...\n\t\t'g-')\n\tplot3(\t[xmin xmax xmax xmin xmin], ...\n\t\t[ymin ymin ymax ymax ymin], ...\n\t\t[zmax zmax zmax zmax zmax], ...\n\t\t'g-')\n\tplot3(xmin*[1 1], ymin*[1 1], [zmin zmax], 'g-')\n\tplot3(xmax*[1 1], ymin*[1 1], [zmin zmax], 'g-')\n\tplot3(xmin*[1 1], ymax*[1 1], [zmin zmax], 'g-')\n\tplot3(xmax*[1 1], ymax*[1 1], [zmin zmax], 'g-')\n\tplot3(xmin*ones(ig.nz,1), ymin*ones(ig.nz,1), ig.z, 'g.')\nend\n\n% detector array for source at each position\ndetcolor = {'r.', 'c.', 'm.'};\nia_list = [1 1+floor(st.na/2) st.na];\nfor ia = ia_list\n\tsrc = [t1(ia) t2(ia) t3(ia)];\n\tunit_vec = [-src(1) -src(2) 0] / sqrt(src(1)^2+src(2)^2);\n\t% diametrically opposite point of the source on the detector\n\tdet_cen_loc = src + st.dsd * unit_vec;\n\tplot3(det_cen_loc(1), det_cen_loc(2), det_cen_loc(3), 'rs')\n\n\trot = st.ar(ia);\n\trot = [cos(rot) -sin(rot); sin(rot) cos(rot)];\n\tpd = rot * [st.xds'; st.yds'];\n\n\tfor it=1:st.nt\n\t\tplot3(pd(1,:), pd(2,:), src(3) + st.t(it)*ones(1,st.ns), ...\n\t\t\tdetcolor{find(ia == ia_list)})\n\tend\n\n\tif 1 && ia == 1 % line from source to middle of first detector row\n\t\tplot3([src(1) det_cen_loc(1)], [src(2) det_cen_loc(2)], ...\n\t\t\t[src(3) st.t(1)], 'm-')\n\tend\nend\nhold off\n\n\n% ct_geom_plot()\nfunction out = ct_geom_plot(st, varargin)\nim clf\nif all(st.source_zs == 0) % 2D or axial case\n\tct_geom_plot2(st, varargin{:});\nelse\n\tct_geom_plot3(st, varargin{:});\nend\nif nargout, out = []; end\n\n\n% ct_geom_ge1()\n% 'lightspeed';\n% these numbers are published in IEEE T-MI Oct. 2006, p.1272-1283 wang:06:pwl\nfunction st = ct_geom_ge1(type, varargin)\n\ntmp.orbit = 360;\ntmp = vararg_pair(tmp, varargin, 'allow_new', true);\nif streq(tmp.orbit, 'short')\n\tna = 642; % trick: reduce na for short scans\n\tfor ii=1:length(varargin)\n\t\tif (streq(varargin{ii}, 'orbit'))\n\t\t\tvarargin{ii+1} = na/984*360;\n\t\t\tbreak\n\t\tend\n\tend\nelse\n\tna = 984;\nend\n\nst = ct_geom('fan', ...\n\t'ns', 888, ... % detector channels\n\t'nt', 1, ... % detector rows\n\t'na', na, ... % angular samples\n\t'orbit', 360, ...\n\t'offset_s', 1.25, ... % quarter-detector offset\n\t'dsd', 949.075, ...\n\t'dso', 541, ...\n\t'dfs', 0, ... % arc\n\t'ds', 1.0239, ... % detector pitch\n\t'dt', 1.0964, ... % detector row spacing for 0.625mm slices, 2009-12-06\n\tvarargin{:});\n%\t'dod', 408.075, ...\n% 'strip_width', [], ...\n\n\n% ct_geom_ge2()\n% helical CT\nfunction st = ct_geom_ge2(type, varargin)\nst = ct_geom_ge1(type, ...\n\t'nt', 64, ... % 64-slice\n\t'dt', 949.0750 / 541 * 0.625, ... % about 1.0964\n\tvarargin{:});\n\n\n% ct_geom_test()\nfunction ct_geom_test\n% axial cone-beam test\ncg = ct_geom('fan', 'ns', 888, 'nt', 64, 'na', 984, ...\n\t'offset_s', 1.25, ...\n\t'dsd', 949, 'dod', 408);\ncg.ad(2);\ncg.downsample(2);\ncg.rmax;\ncg.ws;\ncg.nframe; cg.frame; cg.gamma; cg.gamma_max;\ncg.s(cg.ns/2+1);\nif im\n\tcg.plot;\nprompt\nend\n\n% test user_source_zs\ncg = ct_geom('fan', 'dsd', 949, 'dod', 408, ...\n\t'ns', 888, 'ds', 1.0239, 'offset_s', 1.25, ...\n\t'nt', 8, 'dt', 1.0964, ...\n\t'na', 2*984, 'orbit', 2*360, ...\n\t'source_zs', []);\ncg.source_zs(1:2:7);\n\n% helical cone-beam test\ncg = ct_geom('fan', 'dsd', 949, 'dod', 408, ...\n\t'ns', 888, 'ds', 1.0239, 'offset_s', 1.25, ...\n\t'nt', 8, 'dt', 1.0964, ...\n\t'na', 2*984, 'orbit', 2*360, ...\n\t'pitch', 1.0);\n\ncg.source_zs(1:2:7);\ncg.downsample(2);\ncg.s(cg.ns/2+1);\nif im\n\tcg.plot;\nprompt\nend\n\nif 1 % footprint\n\tcg = ct_geom('ge2');\n\tig = image_geom('nx', 512, 'fov', 500);\n\tcg.footprint_size(ig);\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/handy-greg/t-fdk/ct_geom_par.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3723767802066108}} {"text": "function [S,f,R,Serr]=mtspectrumpt(data,params,fscorr,t)\n% Multi-taper spectrum - point process times\n%\n% Usage:\n%\n% [S,f,R,Serr]=mtspectrumpt(data,params,fscorr,t)\n% Input: \n% data (structure array of spike times with dimension channels/trials; \n% also accepts 1d array of spike times) -- required\n% params: structure with fields tapers, pad, Fs, fpass, err, trialave\n% - optional\n% tapers : precalculated tapers from dpss or in the one of the following\n% forms: \n% (1) A numeric vector [TW K] where TW is the\n% time-bandwidth product and K is the number of\n% tapers to be used (less than or equal to\n% 2TW-1). \n% (2) A numeric vector [W T p] where W is the\n% bandwidth, T is the duration of the data and p \n% is an integer such that 2TW-p tapers are used. In\n% this form there is no default i.e. to specify\n% the bandwidth, you have to specify T and p as\n% well. Note that the units of W and T have to be\n% consistent: if W is in Hz, T must be in seconds\n% and vice versa. Note that these units must also\n% be consistent with the units of params.Fs: W can\n% be in Hz if and only if params.Fs is in Hz.\n% The default is to use form 1 with TW=3 and K=5\n%\n%\t pad\t\t (padding factor for the FFT) - optional (can take values -1,0,1,2...). \n% -1 corresponds to no padding, 0 corresponds to padding\n% to the next highest power of 2 etc.\n%\t\t\t \t e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT\n%\t\t\t \t to 512 points, if pad=1, we pad to 1024 points etc.\n%\t\t\t \t Defaults to 0.\n% Fs (sampling frequency) - optional. Default 1.\n% fpass (frequency band to be used in the calculation in the form\n% [fmin fmax])- optional. \n% Default all frequencies between 0 and Fs/2\n% err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars\n% [0 p] or 0 - no error bars) - optional. Default 0.\n% trialave (average over channels/trials when 1, don't average when 0) - optional. Default 0\n% fscorr (finite size corrections, 0 (don't use finite size corrections) or \n% 1 (use finite size corrections) - optional\n% (available only for spikes). Defaults 0.\n% t (time grid over which the tapers are to be calculated:\n% this argument is useful when calling the spectrum\n% calculation routine from a moving window spectrogram\n% calculation routine). If left empty, the spike times\n% are used to define the grid.\n% Output:\n% S (spectrum with dimensions frequency x channels/trials if trialave=0; \n% dimension frequency if trialave=1)\n% f (frequencies)\n% R (rate)\n% Serr (error bars) - only if err(1)>=1\nif nargin < 1; error('Need data'); end;\nif nargin < 2; params=[]; end;\n[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);\nclear params\ndata=change_row_to_column(data);\nif nargout > 3 && err(1)==0; error('cannot compute error bars with err(1)=0; change params and run again'); end;\nif nargin < 3 || isempty(fscorr); fscorr=0;end;\nif nargin < 4 || isempty(t);\n [mintime,maxtime]=minmaxsptimes(data);\n dt=1/Fs; % sampling time\n t=mintime-dt:dt:maxtime+dt; % time grid for prolates\nend;\nN=length(t); % number of points in grid for dpss\nnfft=max(2^(nextpow2(N)+pad),N); % number of points in fft of prolates\n[f,findx]=getfgrid(Fs,nfft,fpass); % get frequency grid for evaluation\ntapers=dpsschk(tapers,N,Fs); % check tapers\n[J,Msp,Nsp]=mtfftpt(data,tapers,nfft,t,f,findx); % mt fft for point process times\nS=squeeze(mean(conj(J).*J,2));\nif trialave; S=squeeze(mean(S,2));Msp=mean(Msp);end;\nR=Msp*Fs;\nif nargout==4;\n if fscorr==1;\n Serr=specerr(S,J,err,trialave,Nsp);\n else\n Serr=specerr(S,J,err,trialave);\n end;\nend;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/pointtimes/mtspectrumpt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3723767802066108}} {"text": "function D = driving_function_mono_wfs(x0,xs,src,f,conf)\n%DRIVING_FUNCTION_MONO_WFS driving signal for WFS\n%\n% Usage: D = driving_function_mono_wfs(x0,xs,src,f,conf)\n%\n% Input parameters:\n% x0 - position and direction of the secondary source / m [nx7]\n% xs - position of virtual source or direction of plane\n% wave / m [1x3] or [1x6]\n% src - source type of the virtual source\n% 'pw' - plane wave (xs is the direction of the\n% plane wave in this case)\n% 'ps' - point source\n% 'ls' - line source\n% 'fs' - focused source\n% f - frequency of the monochromatic source / Hz\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% D - driving function signal [nx1]\n%\n% See also: plot_sound_field, sound_field_mono_wfs_25d,\n% driving_function_imp_wfs_25d\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 5;\nnargmax = 5;\nnarginchk(nargmin,nargmax);\nisargsecondarysource(x0);\nisargxs(xs);\nisargpositivescalar(f);\nisargchar(src);\nisargstruct(conf);\n\n\n%% ===== Computation ====================================================\n% Calculate the driving function in time-frequency domain\n\n% Secondary source positions and directions\nnx0 = x0(:,4:6);\nx0 = x0(:,1:3);\n\n% Source position/direction/orientation\nxs = repmat(xs,[size(x0,1) 1]);\n\n% Get driving signals\nif strcmp('pw',src)\n % === Plane wave ===\n % Direction of plane wave\n nk = bsxfun(@rdivide,xs,vector_norm(xs(:,1:3),2));\n % Driving signal\n D = driving_function_mono_wfs_pw(x0,nx0,nk,f,conf);\n\nelseif strcmp('ps',src)\n % === Point source ===\n D = driving_function_mono_wfs_ps(x0,nx0,xs(:,1:3),f,conf);\n\nelseif strcmp('ls',src)\n % === Line source ===\n D = driving_function_mono_wfs_ls(x0,nx0,xs,f,conf);\n\nelseif strcmp('fs',src)\n % === Focused source ===\n D = driving_function_mono_wfs_fs(x0,nx0,xs(:,1:3),f,conf);\n\nelse\n error('%s: %s is not a known source type.',upper(mfilename),src);\nend\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_monochromatic/driving_function_mono_wfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.37217080546187764}} {"text": "function [c] = power(a,b,varargin)\n% C = A.^B\n% [C]=POWER(A,B) Compute A.^B for a TT-tensor A and natural B.\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\nif isa(a,'tt_tensor') && numel(b) == 1\n c=a;\n b=b-1;\n while(b>0)\n c=c.*a;\n b=b-1;\n end\n \nelse\n error('Incorrect usage for TT-power');\nend\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/@tt_tensor/power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3721174862016143}} {"text": "%% DEMO_febio_0059_face_mask_loading\n% Below is a demonstration for:\n%\n% * Building triangulated surface geometry for a face\n% * Meshing the face using pentahedral elements\n% * Building model of a tube\n% * Defining the boundary conditions\n% * Coding the febio structure\n% * Running the model\n% * Importing and visualizing results\n\n%% Keywords\n%\n% * febio_spec version 3.0\n% * febio, FEBio\n% * face\n% * contact, sliding, friction\n% * pentahedral elements, penta6\n% * static, solid\n% * hyperelastic, Ogden\n% * displacement logfile\n\n%%\n\nclear; close all; clc;\n\n%%\n% Plot settings\nfontSize=15;\nfaceAlpha1=1;\nfaceAlpha2=0.3;\nmarkerSize1=15;\nmarkerSize2=10;\nlineWidth=2;\ncMap=spectral(250);\n\n%% Control parameters\n\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\n\n% Defining file names\nfebioFebFileNamePart='tempModel';\nfebioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name\nfebioLogFileName=fullfile(savePath,[febioFebFileNamePart,'.txt']); %FEBio log file name\nfebioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement\nfebioLogFileName_force=[febioFebFileNamePart,'_force_out.txt']; %Log file name for exporting force\nfebioLogFileName_strainEnergy=[febioFebFileNamePart,'_energy_out.txt']; %Log file name for exporting strain energy density\n\n% Geometry parameters\npointSpacingTissue=6;\nfaceTissueThickness=6;\npointSpacingMask=pointSpacingTissue/2;\nmaskRimWidth=5; \nmaskRimFilletRadius=6; \nmaskDiscRadius1=25;\nmaskDiscRadius2=maskDiscRadius1+4;\nmaskDiscOffset=25; \nbezierTangency=0.1; \n\ndistInclude=40; %Distance from mask to include face in FEA\n\n%Ray tracing parameters\noptionStructRayTrace.tolEps = 1e-6;\noptionStructRayTrace.triSide = 0;\noptionStructRayTrace.rayType = 'ray';\noptionStructRayTrace.exclusionType = 'inclusive';\noptionStructRayTrace.paired = 0; \n\n%Material parameters\nc1_tissue=1e-3; %Shear-modulus-like parameter\nm1_tissue=2; %Material parameter setting degree of non-linearity\nk_tissue=c1_tissue*100; %Bulk modulus\n\nc1_rim=c1_tissue*5; %Shear-modulus-like parameter\nm1_rim=2; %Material parameter setting degree of non-linearity\nk_rim=c1_rim*10; %Bulk modulus\n\n% FEA control settings\nnumTimeSteps=15; %Number of time steps desired\nmax_refs=35; %Max reforms\nmax_ups=0; %Set to zero to use full-Newton iterations\nopt_iter=10; %Optimum number of iterations\nmax_retries=5; %Maximum number of retires\ndtmin=(1/numTimeSteps)/100; %Minimum time step size\ndtmax=(1/numTimeSteps); %Maximum time step size\nsymmetric_stiffness=0;\nmin_residual=1e-20;\nrunMode='external';\n\n%Boundary condition parameters\ninitialOffset=0;\ndisplacementMagnitude_z=-2-initialOffset; %Displacement applied\n\n%Contact parameters\ncontactPenalty=10;\nlaugon=0;\nminaug=1;\nmaxaug=10;\nfric_coeff=0.5;\n\n%% Load face geometry\n\ntestCase=1;\nswitch testCase\n case 1\n %Load surface model\n [Ff,Vf]=graphicsModels(9);\n \n %Surface markers\n V_markers=[65.51,49.94,217.14;... %Tip of the nose\n 66.44,54.79,259.81;... %Nose between eyes\n 53.81,115,263.39;... %Right eye outer corner\n 126.5,46.62,269.75;... %Left eye outer corner\n 85.67,69.44,194.1;... %Middle of mounth\n 98.39,80.38,158]; %Bottom of chin\n case 2\n %Load surface model\n [Ff,Vf]=graphicsModels(13);\n \n %Surface markers \n V_markers=[3.50162,-181.107,-8.09110;... %Tip of the nose\n 1.51627,-159.171,30.4679;... %Nose between eyes\n -43.2473,-139.003,24.6407;... %Right eye outer corner\n 48.4245,-136.490,25.3913;... %Left eye outer corner\n 4.11905,-167.594,-36.9600;... %Middle of mounth\n 2.85290,-161.802,-73.4644]; %Bottom of chin\nend\n\ndistEyes=sqrt(sum((V_markers(3,:)-V_markers(4,:)).^2,2));\n\n%% Remeshing surface \noptionStruct_remesh.pointSpacing=pointSpacingTissue; %Set desired point spacing\noptionStruct_remesh.disp_on=0; % Turn off command window text display\n[Ff,Vf]=ggremesh(Ff,Vf,optionStruct_remesh);\n\n%%\n\nny=vecnormalize(V_markers(2,:)-V_markers(6,:));\nnx=vecnormalize(V_markers(4,:)-V_markers(3,:));\nnz=vecnormalize(cross(nx,ny));\nnx=vecnormalize(cross(ny,nz));\n\nQ=[nx;ny;nz]';\n\n%%\n\n% cFigure; hold on;\n% gpatch(Ff,Vf,'w','none',1);\n% % plotV(V_markers,'r.','MarkerSize',35);\n% % text(V_markers(:,1)+4,V_markers(:,2),V_markers(:,3),{'1','2','3','4','5','6'},'FontSize',25);\n% % quiverTriad(V_markers(1,:),Q,100);\n% axisGeom; camlight headlight;\n% colormap(spectral(250))\n% gdrawnow; \n\n%%\n\ncFigure; hold on;\ngpatch(Ff,Vf,'w','none',0.5);\nplotV(V_markers,'r.','MarkerSize',35);\ntext(V_markers(:,1)+4,V_markers(:,2),V_markers(:,3),{'1','2','3','4','5','6'},'FontSize',25);\nquiverTriad(V_markers(1,:),Q,100);\naxisGeom; camlight headlight;\ncolormap(spectral(250))\ngdrawnow; \n\n%% Centre on nose and rotate to face face looking down Z-axis\n\nVf=Vf-V_markers(1,:);\nVf=Vf*Q;\nV_markers=V_markers-V_markers(1,:);\nV_markers=V_markers*Q;\nnz=[0 0 1];%nz*Q;\n\n%%\n\ncFigure; hold on;\ngpatch(Ff,Vf,'w','none',0.5);\nplotV(V_markers,'r.','MarkerSize',35);\ntext(V_markers(:,1)+6,V_markers(:,2),V_markers(:,3)+15,{'1','2','3','4','5','6'},'FontSize',25);\naxisGeom; camlight headlight;\ncolormap(spectral(250))\ngdrawnow;\n\n%% Construct mask rim curve\n\nV1=V_markers(1,[1 2]);\nV2=V_markers(2,[1 2]);\nV3=V_markers(3,[1 2]);\nV4=V_markers(4,[1 2]);\nV5=V_markers(5,[1 2]);\nV6=V_markers(6,[1 2]);\n\npp1=0.4*V1+0.6*V2;\npp2=0.6*V1+0.4*V3;\npp3=V3-[0 V3(2)]+[0 0.5*V5(2)+0.5*V1(2)];\npp4=[0.3*V2(1)+0.8*V3(1) 0.5*V5(2)+0.5*V6(2)];\npp5=V6;\npp6=[0.3*V2(1)+0.8*V4(1) 0.5*V5(2)+0.5*V6(2)];\npp7=V4-[0 V4(2)]+[0 0.5*V5(2)+0.5*V1(2)];\npp8=0.6*V1+0.4*V4;\n\nV_rim_points=[pp1;pp2;pp3;pp4;pp5;pp6;pp7;pp8];\nV_rim_points(:,3)=0;\n\n[V_rim_points,indFaceIntersect]=traceToSurf(V_rim_points,-nz,Ff,Vf,optionStructRayTrace);\nnumRimControlPoints=size(V_rim_points,1);\n\nV_rim_curve=evenlySpaceCurve(V_rim_points,pointSpacingMask,'pchip',1);\nV_rim_curve=traceToSurf(V_rim_curve,-nz,Ff,Vf,optionStructRayTrace);\nnumPointsRimCurve=size(V_rim_curve,1);\n\n\nNe1=vecnormalize([V_rim_points(2:end,:); V_rim_points(1,:)]-V_rim_points(1:end,:));\nNe2=vecnormalize(V_rim_points - [V_rim_points(end,:); V_rim_points(1:end-1,:)]);\nNe=vecnormalize(0.5*Ne1+0.5*Ne2);\n\nNf=patchNormal(Ff,Vf); %Normal directions\nNff=Nf(indFaceIntersect(:,2),:);\nN_rim_points=vecnormalize(cross(Nff,Ne));\n\nV_rim_points1=V_rim_points-N_rim_points.*maskRimWidth/2;\nV_rim_points2=V_rim_points+N_rim_points.*maskRimWidth/2;\n\n%%\n\ncFigure; hold on;\ngpatch(Ff,Vf,'w','none',0.5);\nplotV(V_markers,'r.','MarkerSize',25);\ntext(V_markers(:,1)+4,V_markers(:,2),V_markers(:,3),{'1','2','3','4','5','6'},'FontSize',25);\n\nplotV(V_rim_points,'k.','MarkerSize',25);\nplotV(V_rim_points1,'b.','MarkerSize',25);\nplotV(V_rim_points2,'g.','MarkerSize',25);\n\nquiverVec(V_rim_points,N_rim_points,maskRimWidth/2,'y');\nquiverVec(V_rim_points,-N_rim_points,maskRimWidth/2,'y');\naxisGeom; camlight headlight;\nview(2);\ngdrawnow; \n\n%% \n\n[~,indClose]=minDist(V_markers,Vf);\nd=meshDistMarch(Ff,Vf,indClose([1 5]));\n\n[~,indClose]=minDist(V_rim_curve,Vf);\nd_rim_curve=meshDistMarch(Ff,Vf,indClose);\nd_markers_max=max(d(indClose));\n\nlogicCloseVertices= d<=d_markers_max | d_rim_curve Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='All'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates\n\n% -> Elements\npartName1='Part1';\nfebio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part\nfebio_spec.Mesh.Elements{1}.ATTR.type='tet4'; %Element type\nfebio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E_face,1))'; %Element id's\nfebio_spec.Mesh.Elements{1}.elem.VAL=E_face; %The element matrix\n\npartName2='Part2';\nfebio_spec.Mesh.Elements{2}.ATTR.name=partName2; %Name of this part\nfebio_spec.Mesh.Elements{2}.ATTR.type='tet4'; %Element type\nfebio_spec.Mesh.Elements{2}.elem.ATTR.id=size(E_face,1)+(1:1:size(E_rim,1))'; %Element id's\nfebio_spec.Mesh.Elements{2}.elem.VAL=E_rim; %The element matrix\n\n% -> NodeSets\nnodeSetName1='bcSupportList';\nfebio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;\nfebio_spec.Mesh.NodeSet{1}.node.ATTR.id=bcSupportList(:);\n\nnodeSetName2='bcPrescribeList';\nfebio_spec.Mesh.NodeSet{2}.ATTR.name=nodeSetName2;\nfebio_spec.Mesh.NodeSet{2}.node.ATTR.id=bcPrescribeList(:);\n\n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain{1}.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain{1}.ATTR.mat=materialName1;\n\nfebio_spec.MeshDomains.SolidDomain{2}.ATTR.name=partName2;\nfebio_spec.MeshDomains.SolidDomain{2}.ATTR.mat=materialName2;\n\n% -> Surfaces\nsurfaceName1='contactSurface1';\nfebio_spec.Mesh.Surface{1}.ATTR.name=surfaceName1;\nfebio_spec.Mesh.Surface{1}.tri3.ATTR.id=(1:1:size(F_contact_primary,1))';\nfebio_spec.Mesh.Surface{1}.tri3.VAL=F_contact_primary;\n\nsurfaceName2='contactSurface2';\nfebio_spec.Mesh.Surface{2}.ATTR.name=surfaceName2;\nfebio_spec.Mesh.Surface{2}.tri3.ATTR.id=(1:1:size(F_contact_secondary,1))';\nfebio_spec.Mesh.Surface{2}.tri3.VAL=F_contact_secondary;\n\n% -> Surface pairs\ncontactPairName='Contact1';\nfebio_spec.Mesh.SurfacePair{1}.ATTR.name=contactPairName;\nfebio_spec.Mesh.SurfacePair{1}.primary=surfaceName1;\nfebio_spec.Mesh.SurfacePair{1}.secondary=surfaceName2;\n\n%Boundary condition section \n% -> Fix boundary conditions\nfebio_spec.Boundary.bc{1}.ATTR.type='fix';\nfebio_spec.Boundary.bc{1}.ATTR.node_set=nodeSetName1;\nfebio_spec.Boundary.bc{1}.dofs='x,y,z';\n\nfebio_spec.Boundary.bc{2}.ATTR.type='fix';\nfebio_spec.Boundary.bc{2}.ATTR.node_set=nodeSetName2;\nfebio_spec.Boundary.bc{2}.dofs='x,y';\n\nfebio_spec.Boundary.bc{3}.ATTR.type='prescribe';\nfebio_spec.Boundary.bc{3}.ATTR.node_set=nodeSetName2;\nfebio_spec.Boundary.bc{3}.dof='z';\nfebio_spec.Boundary.bc{3}.scale.ATTR.lc=1;\nfebio_spec.Boundary.bc{3}.scale.VAL=displacementMagnitude_z;\nfebio_spec.Boundary.bc{3}.relative=0;\n\n%Contact section\nfebio_spec.Contact.contact{1}.ATTR.type='sliding-elastic';\nfebio_spec.Contact.contact{1}.ATTR.surface_pair=contactPairName;\nfebio_spec.Contact.contact{1}.two_pass=0;\nfebio_spec.Contact.contact{1}.laugon=laugon;\nfebio_spec.Contact.contact{1}.tolerance=0.2;\nfebio_spec.Contact.contact{1}.gaptol=0;\nfebio_spec.Contact.contact{1}.minaug=minaug;\nfebio_spec.Contact.contact{1}.maxaug=maxaug;\nfebio_spec.Contact.contact{1}.search_tol=0.01;\nfebio_spec.Contact.contact{1}.search_radius=0.1*sqrt(sum((max(V,[],1)-min(V,[],1)).^2,2)); \nfebio_spec.Contact.contact{1}.symmetric_stiffness=0;\nfebio_spec.Contact.contact{1}.auto_penalty=1;\nfebio_spec.Contact.contact{1}.penalty=contactPenalty;\nfebio_spec.Contact.contact{1}.fric_coeff=fric_coeff;\n\n%LoadData section\n% -> load_controller\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];\n\n%Output section\n% -> log file\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.node_data{1}.VAL=1:size(V,1);\n\nfebio_spec.Output.logfile.node_data{2}.ATTR.file=febioLogFileName_force;\nfebio_spec.Output.logfile.node_data{2}.ATTR.data='Rx;Ry;Rz';\nfebio_spec.Output.logfile.node_data{2}.ATTR.delim=',';\nfebio_spec.Output.logfile.node_data{2}.VAL=1:size(V,1);\n\nfebio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_strainEnergy;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='sed';\nfebio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.element_data{1}.VAL=1:size(E_face,1);\n\n%% Quick viewing of the FEBio input file structure\n% The |febView| function can be used to view the xml structure in a MATLAB\n% figure window.\n\n%%\n% |febView(febio_spec); %Viewing the febio file|\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function.\n\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n\n%% Running the FEBio analysis\n% To run the analysis defined by the created FEBio input file the\n% |runMonitorFEBio| function is used. The input for this function is a\n% structure defining job settings e.g. the FEBio input file name. The\n% optional output runFlag informs the user if the analysis was run\n% succesfully.\n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.disp_log_on=1; %Display convergence information in the command window\nfebioAnalysis.runMode=runMode;%'internal';\nfebioAnalysis.t_check=0.25; %Time for checking log file (dont set too small)\nfebioAnalysis.maxtpi=1e99; %Max analysis time\nfebioAnalysis.maxLogCheckTime=10; %Max log file checking time\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n\n%% Import FEBio results\n\nif runFlag==1 %i.e. a succesful run\n \n % Importing nodal displacements from a log file\n [time_mat, N_disp_mat,~]=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp)); %Nodal displacements\n time_mat=[0; time_mat(:)]; %Time\n \n N_disp_mat=N_disp_mat(:,2:end,:);\n sizImport=size(N_disp_mat);\n sizImport(3)=sizImport(3)+1;\n N_disp_mat_n=zeros(sizImport);\n N_disp_mat_n(:,:,2:end)=N_disp_mat;\n N_disp_mat=N_disp_mat_n;\n DN=N_disp_mat(:,:,end);\n \n V_def=V+DN;\n V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);\n X_DEF=V_DEF(:,1,:);\n Y_DEF=V_DEF(:,2,:);\n Z_DEF=V_DEF(:,3,:);\n \n C=sqrt(sum(DN(:,3).^2,2));\n \n %%\n % Importing element strain energies from a log file\n [~,E_energy,~]=importFEBio_logfile(fullfile(savePath,febioLogFileName_strainEnergy)); %Element strain energy\n \n %Remove nodal index column\n E_energy=E_energy(:,2:end,:);\n \n %Add initial state i.e. zero energy\n sizImport=size(E_energy);\n sizImport(3)=sizImport(3)+1;\n E_energy_mat_n=zeros(sizImport);\n E_energy_mat_n(:,:,2:end)=E_energy;\n E_energy=E_energy_mat_n;\n \n [FE_face,C_energy_face]=element2patch(E_face,E_energy(1:size(E_face,1),:,end),'tet4');\n [CV]=faceToVertexMeasure(FE_face,V,C_energy_face);\n \n %%\n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations\n cMap_c=gjet(250);\n cMap=[linspacen([1 1 1],cMap_c(1,:),50)'; cMap_c];\n \n% cMap=cMap(4:end,:);\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; %Open figure\n gtitle([febioFebFileNamePart,': Press play to animate']);\n \n gpatch(Ffc,Vf,cMap(1,:),'none',1)\n hp1=gpatch(Fb(Cb==1,:),V_def,CV,'none',1); %Add graphics object to animate\n hp1.FaceColor='Interp';\n hp2=gpatch(Fb_rim,V_def,'w','none',0.25); %Add graphics object to animate\n hp3=gpatch(F_mask,V_mask,'w','none',0.25);\n \n axisGeom(gca,fontSize); camlight headlight;\n colormap(cMap); colorbar;\n caxis([0 max(C_energy_face)/10]);\n axis([min(X_DEF(:)) max(X_DEF(:)) min(Y_DEF(:)) max(Y_DEF(:)) min(Z_DEF(:)) max(Z_DEF(:))]);\n axis tight; \n \n % Set up animation features\n animStruct.Time=time_mat; %The time vector\n for qt=1:1:size(N_disp_mat,3) %Loop over time increments\n DN=N_disp_mat(:,:,qt); %Current displacement\n V_def=V+DN; %Current nodal coordinates\n \n % C=sqrt(sum(DN(:,3).^2,2)); %New color\n [FE_face,C_energy_face]=element2patch(E_face,E_energy(1:size(E_face,1),:,qt),'tet4');\n [CV]=faceToVertexMeasure(FE_face,V,C_energy_face);\n \n u=mean(DN(bcPrescribeList,:),1);\n V_mask_def=V_mask+u(ones(size(V_mask,1),1),:);\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp1 hp1 hp2 hp3]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData','Vertices','Vertices'}; %Properties of objects to animate\n animStruct.Set{qt}={V_def,CV,V_def,V_mask_def}; %Property values for to set in order to animate\n end\n anim8(hf,animStruct); %Initiate animation feature\n drawnow; \n \nend\n\n%%\nfunction [varargout]=traceToSurf(V1,N1,F2,V2,optionStructRayTrace)\n\nif size(N1,1)==1\n N1=N1(ones(size(V1,1),1),:);\nend\n\nnumPoints=size(V1,1);\nindFacesIntersect=nan(size(V1,1),2);\nfor q=1:1:numPoints \n [P,indFaceIntersect,~,~]=triSurfRayTrace(V1(q,:),N1(q,:),F2,V2,optionStructRayTrace); \n if size(P,1)>1\n [~,indMin]=minDist(V1(q,:),P);\n % [~,indMin]=min(d);\n P=P(indMin,:); \n indFaceIntersect=indFaceIntersect(indMin,:);\n end \n if ~isempty(P)\n V1(q,:)=P;\n indFacesIntersect(q,:)=indFaceIntersect;\n end \nend\n\nvarargout{1}=V1;\nvarargout{2}=indFacesIntersect;\n\nend\n\nfunction [Fr,Vr]=roundMesh(indCurve,Vm,Nm,nc,stripRadius)\n\nE=[indCurve(1:end)' [indCurve(2:end) indCurve(1)]'];\nind1=indCurve(1:end)';\nind2=[indCurve(2:end) indCurve(1)]';\nind3=[indCurve(end) indCurve(1:end-1)]';\n\nN1f=Vm(ind2,:)-Vm(ind1,:);\nN1b=Vm(ind1,:)-Vm(ind3,:);\nNe=vecnormalize((N1f+N1b)/2);\n\n% Ne=vecnormalize(edgeVec(E,Vm));\nNf=-Nm(E(:,1),:);% -vecnormalize((Nm(E(:,1),:)+Nm(E(:,2),:))/2);\nNe2=vecnormalize(cross(Nf,Ne));\n\nX=repmat(Vm(E(:,1),1),1,nc);\nY=repmat(Vm(E(:,1),2),1,nc);\nZ=repmat(Vm(E(:,1),3),1,nc);\n\nt=repmat(linspace(0,pi/2,nc),size(Z,1),1);\n\nX=X+stripRadius.*sin(t).*repmat(Ne2(:,1),1,nc)-stripRadius.*cos(t).*repmat(Nf(:,1),1,nc)+stripRadius.*repmat(Nf(:,1),1,nc);\nY=Y+stripRadius.*sin(t).*repmat(Ne2(:,2),1,nc)-stripRadius.*cos(t).*repmat(Nf(:,2),1,nc)+stripRadius.*repmat(Nf(:,2),1,nc);\nZ=Z+stripRadius.*sin(t).*repmat(Ne2(:,3),1,nc)-stripRadius.*cos(t).*repmat(Nf(:,3),1,nc)+stripRadius.*repmat(Nf(:,3),1,nc);\n\nfor q=2:1:size(X,2) \n v=evenlySampleCurve([X(:,q) Y(:,q) Z(:,q)],size(X,1),'pchip',1); \n X(:,q)=v(:,1);\n Y(:,q)=v(:,2);\n Z(:,q)=v(:,3);\nend\n\n[Fr,Vr]=grid2patch(X,Y,Z,[],[1 0 0]);\n\nend\n%%\n\nfunction [F,V,X,Y,Z]=bezierLoft(P1,P4,N1,N4,pointSpacing,f)\n\nD12=sqrt(sum((P1-P4).^2,2));\nnumPoints=ceil(max(D12)./pointSpacing);\nif numPoints<2\n numPoints=2;\nend\n\nP2=P1+D12.*f.*N1;\nP3=P4-D12.*f.*N4;\n\nX=zeros(numPoints,size(P1,1));\nY=zeros(numPoints,size(P1,1));\nZ=zeros(numPoints,size(P1,1));\nfor q=1:1:size(P1,1)\n p=[P1(q,:); P2(q,:); P3(q,:); P4(q,:)]; %Control points \n V_bezier=bezierCurve(p,numPoints*2); %Compute bezier curve\n V_bezier=evenlySampleCurve(V_bezier,numPoints,'pchip'); %resample evenly\n X(:,q)=V_bezier(:,1);\n Y(:,q)=V_bezier(:,2);\n Z(:,q)=V_bezier(:,3);\nend\n\n%Create quad patch data\n[F,V] = surf2patch(X,Y,Z);\nI=[(1:size(Z,1)-1)' (1:size(Z,1)-1)' (2:size(Z,1))' (2:size(Z,1))' ];\nJ=[size(Z,2).*ones(size(Z,1)-1,1) ones(size(Z,1)-1,1) ones(size(Z,1)-1,1) size(Z,2).*ones(size(Z,1)-1,1)];\nF_sub=sub2ind(size(Z),I,J);\nF=[F;F_sub];\nF=fliplr(F);\n\nend\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \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/docs/DEMO_febio_0059_face_mask_loading.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.37208097387988337}} {"text": " function [B Bgx Bgy Bgz] = makeB(ig, kg, varargin)\n%|function [B Bgx Bgy Bgz] = makeB(ig, kg, [?])\n%|\n%| Create a Fatrix B operation of warping based on cubic B-spline\n%|\n%| in:\n%|\t'ig'\t\timage geometry \n%|\t'kg'\t\tknot geometry\n%|\n%| out:\n%|\tB\t\tfatrix operation for warping\n%|\tBgx\t\tfatrix operation for warping\n%|\tBgy\t\tfatrix operation for warping\n%|\tBgz\t\tfatrix operation for warping\n%|\n%| Copyright August 2006, Se Young Chun and Jeff Fessler, University of Michigan\n\nif nargin < 2, ir_usage, end\n\nargB.power = 0;\nargB.ig = ig;\nargB.kg = kg;\n[argB.kernelx argB.kernelgx] = makeKernel(3, kg.mx);\n[argB.kernely argB.kernelgy] = makeKernel(3, kg.my);\nif (kg.is3 == 1) \n\t[argB.kernelz argB.kernelgz] = makeKernel(3, kg.mz);\nend\n\nif (nargin == 2)\n\tB = Fatrix([ig.np kg.np], argB, 'forw', @makeB_forward, ...\n\t\t'back', @makeB_transpose, 'power', @makeB_power);\n\tBgx = Fatrix([ig.np kg.np], argB, 'forw', @makeBgx_forward, ...\n\t\t'back', @makeBgx_transpose);\n\tBgy = Fatrix([ig.np kg.np], argB, 'forw', @makeBgy_forward, ...\n\t\t'back', @makeBgy_transpose);\n\tif (kg.is3 == 1) \n\t\tBgz = Fatrix([ig.np kg.np], argB, 'forw', @makeBgz_forward, ...\n\t\t\t'back', @makeBgz_transpose);\n\tend\n\nelse\n\tif (kg.is3 == 1) \n\t\targB.WarpCell = varargin(1:3);\n\t\tBgz = Fatrix([ig.np kg.np],argB,'forw',@makeBgz_forwardwarp, ...\n\t\t\t'back', @makeBgz_transposewarp);\n\telse\n\t\targB.WarpCell = varargin(1:2);\n\tend\n\tB = Fatrix([ig.np kg.np], argB, 'forw', @makeB_forwardwarp, ...\n\t\t'back', @makeB_transposewarp);\n\tBgx = Fatrix([ig.np kg.np], argB, 'forw', @makeBgx_forwardwarp, ...\n\t\t'back', @makeBgx_transposewarp);\n\tBgy = Fatrix([ig.np kg.np], argB, 'forw', @makeBgy_forwardwarp, ...\n\t\t'back', @makeBgy_transposewarp);\nend\n\n\n\t\n%%%\nfunction DFM = makeB_forward(argB, alpha)\nalpha = double(reshape(alpha, argB.kg.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], {argB.kernelx, argB.kernely});\nelse\n\tDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t\t{argB.kernelx, argB.kernely, argB.kernelz});\nend\nDFM = single(DFM(:));\n\n\n\n%%%\nfunction ALP = makeB_transpose(argB, imgco)\nimgco = double(reshape(imgco, argB.ig.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tALP = BsplCo2ValTranZeroFilt(imgco, [argB.kg.nx argB.kg.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], {argB.kernelx, argB.kernely});\nelse\n\tALP = BsplCo2ValTranZeroFilt(imgco,[argB.kg.nx argB.kg.ny argB.kg.nz],...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t\t{argB.kernelx, argB.kernely, argB.kernelz});\nend\nALP = single(ALP(:));\n\n\n\n%%%\nfunction DFM = makeB_forwardwarp(argB, alpha)\nalpha = single(reshape(alpha, argB.kg.dim));\nif (argB.kg.is3 == 0) % 2D case\n DFM = BsplCo2ValZero(alpha, [argB.ig.nx, argB.ig.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], argB.WarpCell);\nelse\n DFM = BsplCo2ValZero(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nend\nDFM = DFM(:);\n\n\n\n%%%\nfunction ALP = makeB_transposewarp(argB, imgco)\nimgco = single(reshape(imgco, argB.ig.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tALP = BsplCo2ValTranZero(imgco, [argB.kg.nx, argB.kg.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], argB.WarpCell);\nelse\n\tALP = BsplCo2ValTranZero(imgco, [argB.kg.nx, argB.kg.ny argB.kg.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nend\nALP = ALP(:);\n\n\n\n%%%\nfunction DFM = makeBgx_forward(argB, alpha)\nalpha = double(reshape(alpha, argB.kg.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], {argB.kernelgx, argB.kernely});\nelse\n\tDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t\t{argB.kernelgx, argB.kernely, argB.kernelz});\nend\nDFM = single(DFM(:));\n\n\n\n%%%\nfunction ALP = makeBgx_transpose(argB, imgco)\nimgco = double(reshape(imgco, argB.ig.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tALP = BsplCo2ValTranZeroFilt(imgco, [argB.kg.nx argB.kg.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], ...\n\t\t{fliplr(argB.kernelgx), fliplr(argB.kernely)});\nelse\n\tALP = BsplCo2ValTranZeroFilt(imgco,[argB.kg.nx argB.kg.ny argB.kg.nz],...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t\t{fliplr(argB.kernelgx), fliplr(argB.kernely), ...\n\t\tfliplr(argB.kernelz)});\nend\nALP = single(ALP(:));\n\n\n\n%%%\nfunction DFM = makeBgx_forwardwarp(argB, alpha)\nalpha = single(reshape(alpha, argB.kg.dim));\nif (argB.kg.is3 == 0) % 2D case\n DFM = BsplCo2GdXZero(alpha, [argB.ig.nx, argB.ig.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], argB.WarpCell);\nelse\n DFM = BsplCo2GdXZero(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nend\nDFM = DFM(:);\n\n\n\n%%%\nfunction ALP = makeBgx_transposewarp(argB, imgco)\nimgco = single(reshape(imgco, argB.ig.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tALP = BsplCo2GdXTranZero(imgco, [argB.kg.nx, argB.kg.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], argB.WarpCell);\nelse\n\tALP = BsplCo2GdXTranZero(imgco, [argB.kg.nx, argB.kg.ny argB.kg.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nend\nALP = ALP(:);\n\n\n\n%%%\nfunction DFM = makeBgy_forward(argB, alpha)\nalpha = double(reshape(alpha, argB.kg.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], {argB.kernelx, argB.kernelgy});\nelse\n\tDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t\t{argB.kernelx, argB.kernelgy, argB.kernelz});\nend\nDFM = single(DFM(:));\n\n\n\n%%%\nfunction ALP = makeBgy_transpose(argB, imgco)\nimgco = double(reshape(imgco, argB.ig.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tALP = BsplCo2ValTranZeroFilt(imgco, [argB.kg.nx argB.kg.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], ...\n\t\t{fliplr(argB.kernelx), fliplr(argB.kernelgy)});\nelse\n\tALP = BsplCo2ValTranZeroFilt(imgco,[argB.kg.nx argB.kg.ny argB.kg.nz],...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t\t{fliplr(argB.kernelx), fliplr(argB.kernelgy), ...\n\t\tfliplr(argB.kernelz)});\nend\nALP = single(ALP(:));\n\n\n\n%%%\nfunction DFM = makeBgy_forwardwarp(argB, alpha)\nalpha = single(reshape(alpha, argB.kg.dim));\nif (argB.kg.is3 == 0) % 2D case\n DFM = BsplCo2GdYZero(alpha, [argB.ig.nx, argB.ig.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], argB.WarpCell);\nelse\n DFM = BsplCo2GdYZero(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nend\nDFM = DFM(:);\n\n\n\n%%%\nfunction ALP = makeBgy_transposewarp(argB, imgco)\nimgco = single(reshape(imgco, argB.ig.dim));\nif (argB.kg.is3 == 0) % 2D case\n\tALP = BsplCo2GdYTranZero(imgco, [argB.kg.nx, argB.kg.ny], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y], ...\n\t\t[argB.kg.mx argB.kg.my], argB.WarpCell);\nelse\n\tALP = BsplCo2GdYTranZero(imgco, [argB.kg.nx, argB.kg.ny argB.kg.nz], ...\n\t\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nend\nALP = ALP(:);\n\n\n\n%%%\nfunction DFM = makeBgz_forward(argB, alpha)\nalpha = double(reshape(alpha, argB.kg.dim));\nDFM = BsplCo2ValZeroFilt(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t{argB.kernelx, argB.kernely, argB.kernelgz});\nDFM = single(DFM(:));\n\n\n\n%%%\nfunction ALP = makeBgz_transpose(argB, imgco)\nimgco = double(reshape(imgco, argB.ig.dim));\nALP = BsplCo2ValTranZeroFilt(imgco,[argB.kg.nx argB.kg.ny argB.kg.nz],...\n\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t[argB.kg.mx argB.kg.my argB.kg.mz], ...\n\t{fliplr(argB.kernelx), fliplr(argB.kernely), ...\n\tfliplr(argB.kernelgz)});\nALP = single(ALP(:));\n\n\n\n%%%\nfunction DFM = makeBgz_forwardwarp(argB, alpha)\nalpha = single(reshape(alpha, argB.kg.dim));\nDFM = BsplCo2GdZZero(alpha, [argB.ig.nx, argB.ig.ny argB.ig.nz], ...\n\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nDFM = DFM(:);\n\n\n\n%%%\nfunction ALP = makeBgz_transposewarp(argB, imgco)\nimgco = single(reshape(imgco, argB.ig.dim));\nALP = BsplCo2GdZTranZero(imgco, [argB.kg.nx, argB.kg.ny argB.kg.nz], ...\n\t[argB.kg.offset_x argB.kg.offset_y argB.kg.offset_z], ...\n\t[argB.kg.mx argB.kg.my argB.kg.mz], argB.WarpCell);\nALP = ALP(:);\n\n\n\n%%%\nfunction ob = makeB_power(ob, sup)\n\nif (sup == 1)\n\nelseif ((sup == 2) && (ob.arg.power == 0))\n\tob.arg.power = 1;\nelse\n\terror('only squares of each element are supported');\nend\nob = ob;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/align/makeB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3720809594982576}} {"text": "%%*******************************************************************\n%% HKMrhsfun: compute the right-hand side vector of the\n%% Schur complement equation for the HKM direction.\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 [rhs,EinvRc,hRd] = HKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)\n\nm = length(rp);\nif (nargin > 8)\n corrector = 1;\nelse\n corrector = 0;\n hRd = zeros(m,1);\nend\nhEinvRc = zeros(m,1);\nEinvRc = cell(size(blk,1),1);\nrhsfree = [];\n%%\nfor p = 1:size(blk,1)\n pblk = blk(p,:);\n n = sum(pblk{2});\n if strcmp(pblk{1},'l')\n if iscell(sigmu)\n EinvRc{p} = sigmu{p}./Z{p} -X{p};\n else\n EinvRc{p} = sigmu./Z{p} -X{p};\n end\n Rq = sparse(n,1);\n if (corrector) && (norm(par.parbarrier{p})==0)\n Rq = dX{p}.*dZ{p}./Z{p};\n else\n tmp = par.dd{p}.*Rd{p};\n tmp2 = mexMatvec(At{p},tmp,1);\n hRd = hRd + tmp2;\n end\n EinvRc{p} = EinvRc{p} - Rq;\n tmp2 = mexMatvec(At{p,1},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'q')\n if iscell(sigmu)\n EinvRc{p} = qops(pblk,sigmu{p},par.Zinv{p},3) -X{p};\n else\n EinvRc{p} = sigmu*par.Zinv{p} -X{p};\n end\n Rq = sparse(n,1);\n if (corrector) && (norm(par.parbarrier{p})==0)\n ff{p} = qops(pblk,1./par.gamz{p},Z{p},3); %#ok\n hdx = qops(pblk,par.gamz{p},ff{p},5,dX{p});\n hdz = qops(pblk,par.gamz{p},ff{p},6,dZ{p});\n hdxdz = Arrow(pblk,hdx,hdz);\n Rq = qops(pblk,par.gamz{p},ff{p},6,hdxdz);\n else\n tmp = par.dd{p}.*Rd{p} ...\n + qops(pblk,qops(pblk,Rd{p},par.Zinv{p},1),X{p},3) ...\n + qops(pblk,qops(pblk,Rd{p},X{p},1),par.Zinv{p},3);\n tmp2 = mexMatvec(At{p,1},tmp,1);\n hRd = hRd + tmp2;\n end\n EinvRc{p} = EinvRc{p} - Rq;\n tmp2 = mexMatvec(At{p,1},EinvRc{p},1);\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'s')\n if iscell(sigmu)\n %%ss = [0,cumsum(pblk{2})];\n %%sigmuvec = zeros(n,1);\n %%for k = 1:length(pblk{2});\n %% sigmuvec(ss(k)+1:ss(k+1)) = sigmu{p}(k)*ones(pblk{2}(k),1);\n %%end\n sigmuvec = mexexpand(pblk{2},sigmu{p});\n EinvRc{p} = par.Zinv{p}*spdiags(sigmuvec,0,n,n) -X{p};\n else\n EinvRc{p} = sigmu*par.Zinv{p} -X{p};\n end\n Rq = sparse(n,n);\n if (corrector) && (norm(par.parbarrier{p})==0)\n Rq = Prod3(pblk,dX{p},dZ{p},par.Zinv{p},0);\n Rq = 0.5*(Rq+Rq');\n else\n tmp = Prod3(pblk,X{p},Rd{p},par.Zinv{p},0,par.nzlistAy{p});\n tmp = 0.5*(tmp+tmp');\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp});\n hRd = hRd + tmp2;\n end\n EinvRc{p} = EinvRc{p} - Rq;\n tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));\n hEinvRc = hEinvRc + tmp2;\n elseif strcmp(pblk{1},'u')\n rhsfree = [rhsfree; Rd{p}]; %#ok\n end\nend\n%%\nrhs = rp + hRd - hEinvRc;\nrhs = full([rhs; rhsfree]);\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/HKMrhsfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.37161754416178394}} {"text": "function [sttm] = tt_sparse_for_mv(ttm, cuttol)\n%Sparsify the TT matrix in TT1.0 matrix format\n% [STTM]=TT_SPARSE_FOR_MV(TTM,[CUTTOL]) Computes the sparse version of the\n% matrix in the TT1.0 matrix format. May work for certain operators\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\nif (nargin<2)||(isempty(cuttol))\n cuttol = 1e-14;\nend;\n\nd=size(ttm,1);\n\nsttm=cell(d+2,1);\nsttm{d+1}=zeros(d-1,1);\nsttm{d+2}=zeros(d,1);\n\nn=size(ttm{1},1);\nm=size(ttm{1},2);\nrm1=size(ttm{1},3);\nsttm{d+1}(1)=rm1;\nsttm{d+2}(1)=n;\nif (~issparse(ttm{1}))\n sttm{1}=reshape(permute(ttm{1},[1,3,2]),[n*rm1,m]);\n sttm{1}(abs(sttm{1})/max(max(abs(sttm{1})))1)\n n=size(ttm{d},1);\n m=size(ttm{d},2);\n rm1=size(ttm{d},3);\n sttm{d+1}(d-1)=rm1;\n sttm{d+2}(d)=n;\n if (~issparse(ttm{1}))\n sttm{d}=reshape(permute(ttm{d},[1,3,2]),[n*rm1,m]);\n sttm{d}(abs(sttm{d})/max(max(abs(sttm{d}))) space_thresh\n% ind_time: components with rval_time > time_thresh\n% MinPeakDist:\n\n% Written by Eftychios A. Pnevmatikakis, Simons Foundation, 2016\n% based on discussions with Matt Kaufman and Farzaneh Najafi, CSHL\n\ndefoptions = CNMFSetParms;\nif nargin < 6 || isempty(options)\n options = defoptions;\nend\n\nif ~isfield(options,'peak_int') || isempty(options.peak_int); int = defoptions.peak_int; else int = options.peak_int; end\nif ~isfield(options,'Npeaks') || isempty(options.peak_int); Np = defoptions.Npeaks; else Np = options.Npeaks; end\nif ~isfield(options,'A_thresh') || isempty(options.A_thresh); Athresh = defoptions.A_thresh; else Athresh = options.A_thresh; end\nif ~isfield(options,'space_thresh') || isempty(options.space_thresh); options.space_thresh = defoptions.space_thresh; end\nif ~isfield(options,'time_thresh') || isempty(options.time_thresh); options.time_thresh = defoptions.time_thresh; end\nif ~isfield(options,'MinPeakDist') || isempty(options.MinPeakDist); options.MinPeakDist = defoptions.MinPeakDist; end\n\nmemmaped = isobject(Yr);\n\n[K_m,T] = size(C);\npk = zeros(K_m,Np);\n\nparfor i = 1:K_m\n [~,pk_temp] = findpeaks(C(i,:),'SortStr','descend','Npeaks',Np,'MinPeakDistance',options.MinPeakDist);\n if ~isempty(pk_temp)\n if length(pk_temp) < Np\n pk_temp(length(pk_temp)+1:Np) = pk_temp(1);\n end\n pk(i,:) = pk_temp;\n end\nend\n\n%% expand intervals\nlint = length(int);\n\nlocs = repmat(pk,1,lint) + kron(int,ones(size(pk)));\nlocs = sort(locs,2,'ascend');\nlocs(locs<1)=1;\nlocs(locs>T)=T;\nLOCS = mat2cell(locs,ones(K_m,1),Np*lint);\nfor i = 1:K_m\n LOCS{i} = unique(LOCS{i});\nend\n\n%% compute r-values\nnA = full(sqrt(sum(A.^2)))';\ntAA = (A'*A)./(nA*nA') > Athresh;\ntAA(1:K_m+1:K_m^2) = 0;\n\nrval_space = zeros(K_m,1);\nrval_time = zeros(K_m,1);\n\nif options.d3 == 1; b_rs = reshape(b,options.d1,options.d2,[]); else b_rs = reshape(b,options.d1,options.d2,options.d3,[]); end\nif memmaped\n parfor i = 1:K_m\n ovlp_cmp = find(tAA(:,i));\n indeces = LOCS{i};\n for j = 1:length(ovlp_cmp)\n indeces = setdiff(indeces,LOCS{ovlp_cmp(j)});\n end\n a_temp = reshape(A(:,i),options.d1,options.d2*options.d3);\n [rows,temp] = find(a_temp>0);\n [cols,plns] = ind2sub([options.d2,options.d3],temp);\n if options.d3 > 1\n a_temp = reshape(full(A(:,i)),options.d1,options.d2,options.d3);\n a_temp = a_temp(min(rows):max(rows),min(cols):max(cols),min(plns):max(plns));\n else\n a_temp = a_temp(min(rows):max(rows),min(cols):max(cols));\n end\n\n if options.d3 == 1\n b_temp = reshape(b_rs(min(rows):max(rows),min(cols):max(cols),:),numel(a_temp),[]);\n else\n b_temp = reshape(b_rs(min(rows):max(rows),min(cols):max(cols),min(plns):max(plns),:),numel(a_temp),[]);\n end\n if ~isempty(indeces)\n if options.d3 == 1\n yytemp = Yr.Y(min(rows):max(rows),min(cols):max(cols),min(indeces):max(indeces));\n y_temp = yytemp(:,:,indeces-min(indeces)+1);\n else\n yytemp = Yr.Y(min(rows):max(rows),min(cols):max(cols),min(plns):max(plns),min(indeces):max(indeces));\n y_temp = yytemp(:,:,:,indeces-min(indeces)+1);\n end\n y_temp = reshape(y_temp,[],length(indeces));\n mY_space = double(mean(y_temp,2) - b_temp*mean(f(:,indeces),2));\n mY_time = double(mean(y_temp,1)-mean(b_temp,1)*f(:,indeces));\n rval_space(i) = corr(full(a_temp(:)),mY_space);\n rval_time(i) = corr(C(i,indeces)',mY_time');\n else\n rval_space(i) = NaN;\n rval_time(i) = NaN;\n end\n end\nelse\n parfor i = 1:K_m\n ovlp_cmp = find(tAA(:,i));\n indeces = LOCS{i};\n for j = 1:length(ovlp_cmp)\n indeces = setdiff(indeces,LOCS{ovlp_cmp(j)});\n end\n a_temp = reshape(A(:,i),options.d1,options.d2*options.d3);\n [rows,temp] = find(a_temp>0);\n [cols,plns] = ind2sub([options.d2,options.d3],temp);\n if options.d3 > 1\n a_temp = reshape(full(A(:,i)),options.d1,options.d2,options.d3);\n a_temp = a_temp(min(rows):max(rows),min(cols):max(cols),min(plns):max(plns));\n else\n a_temp = a_temp(min(rows):max(rows),min(cols):max(cols));\n end\n\n if options.d3 == 1\n b_temp = reshape(b_rs(min(rows):max(rows),min(cols):max(cols),:),numel(a_temp),[]);\n else\n b_temp = reshape(b_rs(min(rows):max(rows),min(cols):max(cols),min(plns):max(plns),:),numel(a_temp),[]);\n end\n if ~isempty(indeces)\n if options.d3 == 1\n y_temp = Yr(min(rows):max(rows),min(cols):max(cols),indeces);\n else\n y_temp = Yr(min(rows):max(rows),min(cols):max(cols),min(plns):max(plns),indeces);\n end \n y_temp = reshape(y_temp,[],length(indeces));\n mY_space = double(mean(y_temp,2) - b_temp*mean(f(:,indeces),2));\n mY_time = double(mean(y_temp,1)-mean(b_temp,1)*f(:,indeces));\n rval_space(i) = corr(full(a_temp(:)),mY_space);\n rval_time(i) = corr(C(i,indeces)',mY_time');\n else\n rval_space(i) = NaN;\n rval_time(i) = NaN;\n end\n end\nend\n\nind_space = rval_space > options.space_thresh;\nind_time = rval_time > options.time_thresh;", "meta": {"author": "flatironinstitute", "repo": "CaImAn-MATLAB", "sha": "49b7884e93348d50df7173e1619d7499468bb1f6", "save_path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB", "path": "github-repos/MATLAB/flatironinstitute-CaImAn-MATLAB/CaImAn-MATLAB-49b7884e93348d50df7173e1619d7499468bb1f6/utilities/classify_comp_corr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3715166698549421}} {"text": "function out = deriv(f, xx, varargin)\n%DERIV Evaluate a derivative of a CHEBFUN.\n%\n% DERIV(F, X) evaluates the first derivative of the CHEBFUN F at the points in\n% X. If F is a quasimatrix with columns F1, ..., FN, then the result will be\n% [F1(X), ..., FN(X)], the horizontal concatenation of the results of\n% evaluating each column at the points in X.\n%\n% DERIV(F, X, M) is the same as above, but returns the values of the Mth\n% derivative of F.\n%\n% DERIV(F, X, S) or DERIV(F, X, S, M) where S is one of the strings 'left',\n% 'right', '+', or '-', evaluates the left- or right-sided limit as described\n% in chebfun/feval.\n%\n% Example 1:\n% u = chebfun(@sin);\n% deriv(u, 1) % u'(1)\n% deriv(u, .5, 2) % u''(.5)\n% deriv(u, 0.1:0.01:0.2) % u'(0.1:0.01:0.2)\n%\n% Example 2:\n% x = chebfun('x')\n% u = abs(x);\n% deriv(u, 0, 'left') % ans = -1\n% deriv(u, 0, 'right') % ans = +1\n%\n% See also chebfun/diff, chebfun/feval.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% The most trivial case:\nif ( isempty(f) )\n return\nend\n\n% By default, compute first derivative:\nm = 1; \n\n% Parse the inputs:\nif ( nargin == 3 )\n if ( isnumeric(varargin{1}) ) % DERIV(F, X, M)\n m = varargin{1};\n varargin = {};\n else % DERIV(F, X, S)\n m = 1; % By default, compute first derivative\n end\nelseif ( nargin == 4 ) % DERIV(F, X, S, M)\n m = varargin{2};\n varargin{2} = [];\nend\n\nif ( m == 0 )\n % Trivial case\n out = feval(f, xx, varargin{:});\nelse\n out = feval(diff(f, m), xx, varargin{:});\nend\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/@chebfun/deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.371471145006881}} {"text": "classdef prtRvMultinomial < prtRv & prtRvMemebershipModel\n % prtRvMultinomial Multinomial random variable\n %\n % RV = prtRvMultinomial creates a prtRvMultinomial object\n % with an unknown number of categories with unspecified probabilities\n % These properties can be set manually or by using the MLE method.\n %\n % prtRvMultinomial operates on count matrices. Therfore, the DRAW()\n % method outputs a matrix that is N x nCategories and has a single 1\n % in each row. To draw integer categories you can use the\n % DRAWINTEGER() method. Similarly, the MLE function takes a count\n % matrix as an input. Type help prtRvMultinomial.mle for more\n % information.\n %\n % RV = prtRvMultinomial(PROPERTY1, VALUE1,...) creates a\n % prtRvMultinomial object RV with properties as specified by \n % PROPERTY/VALUE pairs.\n %\n % A prtRvMultinomial object inherits all properties from the\n % prtRv class. In addition, it has the following properties:\n %\n % nCategories - number of integers modeled by the RV\n % probabilities - A 1 x nCategories vector of doubles less than 1\n % that sum to 1, representing the probability of\n % each of the integers\n % \n % A prtRvMultinomial object inherits all methods from the prtRv\n % class. The MLE method can be used to set the parameters from data.\n % In addition, it has the the following methods:\n % \n % x = R.drawIntegers(N) - Draws N integers with the corresponding\n % probabilities\n %\n % Example:\n % \n % data = rand(100,5); % Uniformly random data\n % X = bsxfun(@eq,data,max(data,[],2)); % Generate data that has a \n % % single 1 in each row\n %\n % RV = prtRvMultinomial; % Generate a prtRvMultinomial\n % RV = mle(RV,X); % Estimate the parameters\n %\n % RV.plotPdf() % Plot the pdf (pmf)\n %\n % See also: prtRv, prtRvMvn, prtRvGmm, prtRvVq, prtRvKde\n\n\n\n\n\n\n\n properties (SetAccess = private)\n name = 'Multinomial Random Variable';\n nameAbbreviation = 'RVMulti';\n end\n \n properties (SetAccess = protected)\n isSupervised = false;\n isCrossValidateValid = true;\n end\n \n properties (Dependent)\n probabilities\n end\n \n properties (Dependent = true)\n nCategories % The number of categories\n end\n \n properties (Hidden = true, SetAccess='private', GetAccess='private')\n probabilitiesDepHelper\n end\n \n properties (Hidden = true, Dependent = true)\n nDimensions\n end\n \n properties (Hidden = true)\n approximatelyEqualThreshold = 1e-4;\n nDrawsPerObservationDraw = [];\n end\n \n methods\n % The Constructor\n function R = prtRvMultinomial(varargin)\n R = constructorInputParse(R,varargin{:});\n end\n \n function R = mle(R,X)\n % RV = RV.mle(X) computes the maximum likelihood estimate based\n % the data X. X should be nObservations x nDimensions. X must\n % be a count matrix, consisting of only zeros and ones. A one\n % in the ith column indicates that the sample in the jth row is\n % of class i.\n % \n \n % if ~isequal(unique(X(:)),[0;1])\n % error('prtRvMultinomial:invalidData','Input matrix must contain only ones and zeros');\n % end\n \n % Do we really want to or need to enforce this?\n % Can't we allow learning of the probability from multinomial\n % draws that had N greater than 1?\n % I don't see why not. - KDM 2013-03-01\n %if ~prtUtilApproxEqual(sum(X,2),1,1e-6);\n % error('prtRvMultinomial:invalidData','Rows of input data must contain no more than one \"1\"');\n %end\n \n X = R.dataInputParse(X); % Basic error checking etc\n \n N_bar = sum(X,1);\n R.probabilities = N_bar./sum(N_bar(:));\n end\n \n function vals = pdf(R,X)\n % PDF Output the pdf of the random variable evaluated at the points specified\n %\n % pdf = RV.pdf(X) returns the pdf of the prtRv\n % object evaluated at X. X must be an N x nDims matrix, where\n % N is the number of locations to evaluate the pdf, and nDims\n % is the same as the number of dimensions, nDimensions, of the\n % prtRv object RV.\n \n [isValid, reasonStr] = R.isValid;\n assert(isValid,'PDF cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n X = R.dataInputParse(X); % Basic error checking etc\n assert(isnumeric(X) && ndims(X)==2,'X must be a 2D numeric array.');\n assert(size(X,2) == R.nCategories,'Incorrect number of categories for this RV object. This RV object is defined to have %d categories, but the input data has only %d columns. Remember that prtRvMultinomial operates on count matrices.', R.nCategories, size(X,2))\n \n \n vals = sum(bsxfun(@times,X,R.probabilities),2);\n end\n \n function vals = logPdf(R,X)\n % LOGPDF Output the log pdf of the random variable evaluated at the points specified\n %\n % logpdf = RV.logpdf(X) returns the logarithm of value of the\n % pdf of the prtRv object evaluated at X. X must be an N x\n % nDims matrix, where N is the number of locations to evaluate\n % the pdf, and nDims is the same as the number of dimensions,\n % nDimensions, of the prtRv object RV.\n\n [isValid, reasonStr] = R.isValid;\n assert(isValid,'LOGPDF cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n vals = log(pdf(R,X));\n end\n \n function vals = draw(R,N)\n % DRAW Draw random samples from the distribution described by the prtRv object\n %\n % VAL = RV.draw(N) generates N random samples drawn from the\n % distribution described by the prtRv object RV. VAL will be a\n % N x nDimensions vector, where nDimensions is the number of\n % dimensions of RV.\n \n assert(numel(N)==1 && all(N==floor(N)) && all(N > 0),'N must be a positive integer scalar.')\n \n [isValid, reasonStr] = R.isValid;\n assert(isValid,'DRAW cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n if ~isempty(R.nDrawsPerObservationDraw)\n nObsToDraw = R.nDrawsPerObservationDraw;\n vals = zeros(N,R.nCategories);\n for iBag = 1:N\n cVals = zeros(nObsToDraw,R.nCategories);\n cVals(sub2ind([nObsToDraw, R.nCategories], (1:nObsToDraw)',drawIntegers(R,nObsToDraw))) = 1;\n vals(iBag,:) = sum(cVals,1);\n end\n else\n vals = zeros(N,R.nCategories);\n vals(sub2ind([N, R.nCategories], (1:N)',drawIntegers(R,N))) = 1;\n end\n end\n \n function vals = drawIntegers(R,N)\n % DRAW Draw random integer samples from the distribution described by the prtRv object\n %\n % VAL = RV.draw(N) generates N random integer samples drawn from the\n % distribution described by the prtRv object RV. VAL will be a\n % N x nDimensions vector, where nDimensions is the number of\n % dimensions of RV.\n \n [isValid, reasonStr] = R.isValid;\n assert(isValid,'DRAWINTEGERS cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n\n assert(numel(N)==1 && N==floor(N) && N > 0,'N must be a positive integer scalar.')\n \n vals = prtRvUtilRandomSample(R.probabilities, N);\n end\n \n function varargout = plotPdf(R,varargin)\n %plotPdf Plot the pdf of the RV\n %\n % rv.plotPdf() plots the pdf of rv\n [isValid, reasonStr] = R.isValid;\n assert(isValid,'plotPdf cannot yet be evaluated. This RV is not yet valid %s.',reasonStr);\n \n h = bar(1:R.nCategories,R.probabilities,'k');\n ylim([0 1])\n xlim(R.plotLimits());\n \n varargout = {};\n if nargout\n varargout = {h};\n end\n end\n \n function plotCdf(R,varargin) %#ok\n % plotCDF Not implemented for this prtRv\n error('prt:prtRvMultinomial','plotCdf is not implimented for this prtRv');\n end\n \n end\n \n % Set methods\n methods\n function R = set.probabilities(R,probs)\n assert(abs(sum(probs)-1) < R.approximatelyEqualThreshold,'Probability vector must must sum to 1.')\n \n R.probabilitiesDepHelper = probs(:)';\n end\n function R = set.nCategories(R,val) %#ok\n error('prt:prtRvMultinomial','nCategories is a dependent property that cannot be set by the user. To set the number of categories, set \"probabilities\" to be a vector of the desired length.');\n end\n end\n \n % Get methods\n methods\n function val = get.probabilities(R)\n val = R.probabilitiesDepHelper;\n end\n function val = get.nCategories(R)\n if ~isempty(R.probabilities)\n val = length(R.probabilities);\n else\n val = [];\n end\n end\n function val = get.nDimensions(R)\n val = R.nCategories;\n end\n end\n \n methods (Hidden = true)\n function [val, reasonStr] = isValid(R)\n if numel(R) > 1\n val = false(size(R));\n for iR = 1:numel(R)\n [val(iR), reasonStr] = isValid(R(iR));\n end\n return\n end\n \n val = ~isempty(R.probabilities);\n \n if val\n reasonStr = '';\n else\n reasonStr = 'because probabilities has not been set';\n end\n end\n \n \n function val = plotLimits(R)\n [isValid, reasonStr] = R.isValid;\n if isValid\n val = [0.5 0.5+R.nCategories];\n else\n \n error('multinomial:plotLimits','Plotting limits can not yet be determined. This RV is not yet valid %s.',reasonStr)\n end\n end\n \n function val = isPlottable(R) %#ok\n val = true; % Always plottable\n end\n \n function R = weightedMle(R,X,weights)\n assert(numel(weights)==size(X,1),'The number of weights must mach the number of observations.');\n \n weights = weights(:);\n \n N_bar = sum(bsxfun(@times,X,weights),1);\n \n R.probabilities = N_bar./sum(N_bar(:));\n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/rv/prtRvMultinomial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3713848217098147}} {"text": "function [mvector,scan] = bes(RF, pw, scantype, var1, var2, var3, var4, phase, M0, T1, T2)\n\n% Bloch Equation Simulator\n%\n% Required Arguments\n% RF 4xN definition of radio frequency pulse (phase, amplitude,\n% duration, gradient)\n% pw duration of pulse in milliseconds\n% scantype scan type: 'frequency', 'B1max', 'temporal'\n% B1max scan\n% var1 frequency / position (if gradient supplied in RF)\n% var2 upper bound B1\n% var3 lower bound B1\n% var4 steps\n% Frequency scan\n% var1 B1max\n% var2 upper bound frequency / position (if gradient supplied)\n% var3 lower bound frequency / position (if gradient supplied)\n% var4 steps\n% Temporal scan\n% var1 B1max\n% var2 frequency / position (if gradient supplied)\n% var3 ignored\n% var4 ignored\n% Optional Arguments\n% phase phase at which the RF pulse is applied (default 0)\n% M0 three component vector specifying the initial magnetization \n% a 3xSTEPS matrix is used to define a different MO for each\n% steps. Default is [0; 0; 1]\n% T1 T1 decay time (default INF)\n% T2 T2 decay time (default INF)\n%\n% Output\n% mvector 3xSTEPS matrix specifying the magnetization at each point\n% scan vector of frequency, B1max, or time steps modelled\n%\n% Units: B1 (kHz), frequencies (kHz), Phase (degrees), Time (ms),\n% Gradients (G/cm), Position (cm), gyro = 4.25763888 kHz/G\n\n% Author: L. Martyn Klassen\n% Copyright 2003 Robarts Research Institute\n% This program is copyrighted worldwide by the Robarts Research\n% Institute. Any distribution, copying or redistribution is expressly\n% forbidden.\n% 03/04/24 Added support for gradient changes during RF\n\nif nargin < 5\n error('BES requires five input arguments.');\nend\n\n% Initialize constants\nscantype = lower(scantype(1));\ngrad_flag = 0;\n\nif nargin < 11\n T2 = Inf;\n if nargin < 10\n T1 = Inf;\n if nargin < 9\n M0 = [0; 0; 1];\n if nargin < 8\n phase = 0;\n if (nargin < 7) && (scantype ~= 't')\n error('BES requires seven input arguments for specified scan type.');\n end\n end\n end\n end\nend\n\n% If only one column is defined in the RF pulse it is an amplitude\n% modulated pulse, and the phase, duration columns have to be added\nif ndims(RF) > 2\n error('BES: RF pulse cannot have more than 2 dimensions.');\nend\n\nsizRF = size(RF);\nif all(sizRF > 4)\n error('BES: RF pulse has too many columns (phase, amplitude, duration, grad)')\nelseif sizRF(2) > 4\n RF = RF';\nend\n\nswitch size(RF, 2)\n case 1\n % Single column is RF magnitude so you have to add phase, duration,\n % and gradients\n RF(:,2) = RF;\n RF(:,1) = phase;\n RF(:,3) = 1;\n RF(:,4) = 0;\n case 2\n % Two columns are phase and magnitude, add duration.\n % Add the desired phase to the waveform:\n RF(:,1) = RF(:,1) + phase;\n RF(:,3) = 1;\n case 3\n % Three columns are phase, magnitude and duration.\n % Add the desired phase to the waveform:\n RF(:,1) = RF(:,1) + phase;\n case 4\n % Convert from G/cm to kHz/cm\n RF(:,4) = RF(:,4) .* 4.25763888;\n grad_flag = 1;\n % Add the desired phase to the waveform:\n RF(:,1) = RF(:,1) + phase;\nend\n \n% Convert phase to radians\nRF(:,1) = RF(:,1) .* (pi / 180);\n\n% Find out how many cyles are required to step through the RF pulse\ncycles = size(RF, 1);\n\n% Scale the RF amplitude to be between -1 and 1\nRF(:,2) = RF(:,2)./max(abs(RF(:,2)));\n\n% Kill any points with zero duration\nRF = RF(RF(:,3) ~= 0, :);\n\n% The smallest duration allowed is 1.0\nminduration = min(RF(:,3));\nmaxduration = max(RF(:,3));\nif (minduration < 1)\n error('BES: Pulse step duration should be zero or positive integer.');\nend\n\n% Adjust durations to be integers\nRF(:,3) = round(RF(:,3));\n\n% Pulse width has to be a scalar\npw = pw(1);\n\n% Define the smallest time interval used in the pulse\ndt = pw./sum(RF(:,3));\n\n% A time scan uses the pulse squence to define the progression\n% through time and not steps\nif scantype == 't'\n steps = 1;\nelse\n steps = var4;\nend\n\n% Define M0\nif isempty(M0)\n % Default is alignment along z axis\n M0 = [0; 0; 1];\n if scantype ~= 't'\n mvector = M0(:,ones(steps, 1));\n end\nelseif prod(size(M0)) == 3\n % One vector must be repeated to size of the scan\n % Check to make sure that M0 is not too large\n if sum(M0.^2) > 1.0\n error('BES: Initial magnetization is greater than 1.0')\n else\n M0 = M0(:);\n if scantype ~= 't'\n mvector = M0(:,ones(steps, 1));\n end\n end \nelseif size(M0, 2) ~= steps\n if scantype ~= 't'\n % Otherwise M0 must be defined at each point in the scan\n error('BES: Initial M0 vector does not agree with number of steps (3xsteps).')\n else\n % Time requires it to 3x1 or 1x3 - previous if statement\n error('BES: Initial MO for time scan must be 3x1 vector')\n end\nelse\n if scantype == 't'\n error('BES: Initial MO for time scan must be 3x1 vector')\n end\n if any(sum(M0.^2, 1) > 1.000001)\n error('BES: Initial magnetization is greater than 1.0')\n end\n mvector = M0;\nend\n\n% Make sure lower limit is less than upper limit\n% switch if they are the wrong order\nif var2 < var3\n temp = var2;\n var2 = var3;\n var3 = temp;\n clear temp;\nend\n\nif (T2 > T1)\n error('BES: First Law Violation, T2 must be less than T1.');\nend\n\n% Calculate the matrices for the T1, T2 decay\nif T1 == 0\n if T2 == 0\n A = [0 0 0; 0 0 0; 0 0 1];\n else\n A = [exp(-dt/T2) 0 0; 0 exp(-dt/T2) 0; 0 0 1];\n end\n B = [0; 0; 0];\nelse\n if T2 == 0\n A = [0 0 0; 0 0 0; 0 0 1-exp(-dt/T1)];\n else\n A = [exp(-dt/T2) 0 0; 0 exp(-dt/T2) 0; 0 0 exp(-dt/T1)];\n end\n B = [0; 0; 1-exp(-dt/T1)];\nend\n\n% Setup for the three different types of simulations\nswitch scantype\ncase 'f' % Scan through frequency\n \n % Fixed value is B1max which has to be scaled for the RF pulse description\n % Also convert it to rad/millisecond\n B1max = var1.*(2*pi);\n \n % Limits are in frequency\n interval = (var2 - var3)/(steps-1);\n scan = [var3:interval:var2];\n\n % Rotate the matrix to align 1st RF with X\n cosa = cos(-RF(1,1));\n sina = sin(-RF(1,1));\n mvector = [cosa sina 0; -sina cosa 0; 0 0 1]*mvector;\n \n % Small tip angle vector\n theta = RF(:,2)*B1max.*dt;\n cosa = cos(theta);\n sina = sin(theta);\n \n % Free precession angle (rad)\n freq = scan .* (2*pi*dt);\n phi = freq; \n cos2a = cos(phi);\n sin2a = sin(phi);\n \n % Alignment angles\n dRF = -diff(RF(:,1));\n dRF(end+1) = RF(end, 1);\n\n % Loop through the RF pulse\n for t = 1:cycles\n % Compute the rotation matrix\n Rx=[1 0 0; 0 cosa(t) sina(t); 0 -sina(t) cosa(t)];\n \n % Added in the decay matrix\n Rx = A * Rx;\n \n if grad_flag\n phi = freq .* RF(t,4);\n cos2a = cos(phi);\n sin2a = sin(phi);\n end\n \n % For durations longer than one, repeat the small angle \n % approximation the prerquisite number of times\n for m = 1:RF(t,3)\n % Using small tip angle approximation to calculate the\n % new magnetization vector\n \n % Rotate the matrix by theta about X and let decay\n mvector = Rx*mvector;\n \n % Add the constant decay term\n mvector(3,:) = mvector(3,:) + B(3);\n \n % Free Precession angle with RF alignment on last increment\n if (m == RF(t,3)) & (dRF(t) ~= 0)\n phi2 = phi + dRF(t);\n cos3a = cos(phi2);\n sin3a = sin(phi2);\n \n temp = cos3a.*mvector(1,:) + sin3a.*mvector(2,:);\n mvector(2,:) = -sin3a.*mvector(1,:) + cos3a.*mvector(2,:);\n mvector(1,:) = temp;\n else\n % Rotate the vector by phi about Z\n temp = cos2a.*mvector(1,:) + sin2a.*mvector(2,:);\n mvector(2,:) = -sin2a.*mvector(1,:) + cos2a.*mvector(2,:);\n mvector(1,:) = temp; \n end\n end\n end\n \ncase 'b' % Scan through B1max\n \n % Fixed value is Frequency (rad/ms)\n freq = var1*2*pi;\n \n % Limits are in B1max which has to be scaled for the RF pulse description\n % and converted to rad/ms.\n interval = (var2 - var3)/(steps-1);\n B1max = [var3:interval:var2].*(2*pi);\n\n % Rotate the matrix to align 1st RF with X\n cosa = cos(-RF(1,1));\n sina = sin(-RF(1,1));\n mvector = [cosa sina 0; -sina cosa 0; 0 0 1]*mvector;\n\n % Free Precession rotation angle (rad)\n freq = freq*dt;\n phi = freq;\n % Compute the free precession matrix\n cosa = cos(phi);\n sina = sin(phi); \n Rfree =[cosa sina 0; -sina cosa 0; 0 0 1];\n \n % Add the decay term as well\n Rfree = A * Rfree;\n \n % Calculate RF alignment angles\n dRF = -diff(RF(:,1));\n % Last one must realign to zero\n dRF(end+1) = RF(end,1);\n cos2a = cos(phi + dRF);\n sin2a = sin(phi + dRF);\n \n % Loop through the RF pulse\n for t = 1:cycles\n % Compute theta for given RF power\n theta = B1max*RF(t,2)*dt;\n cosa = cos(theta);\n sina = sin(theta);\n \n if grad_flag\n phi = freq * RF(t,4);\n end\n \n % For durations longer than one, repeat the small angle \n % approximation the prerequisite number of times\n for m = 1:RF(t,3)\n % Using small tip angle approximation to calculate the\n % new magnetization vector\n \n % Rotate the matrix by theta about X\n temp = cosa.*mvector(2,:) + sina.*mvector(3,:);\n mvector(3,:) = -sina.*mvector(2,:) + cosa.*mvector(3,:);\n mvector(2,:) = temp;\n \n % On last time through apply free precession and rotate the matrix\n % to undo the previous alignment with the RF and also align the next\n % RF with X, otherwise just apply free precession\n if grad_flag\n % Compute the free precession matrix and apply\n cosa = cos(phi + dRF(t));\n sina = sin(phi + dRF(t)); \n mvector = (A * [cosa sina 0; -sina cosa 0; 0 0 1])*mvector;\n elseif (m == RF(t,3)) & (dRF(t) ~= 0)\n mvector=(A * [cos2a(t) sin2a(t) 0; -sin2a(t) cos2a(t) 0; 0 0 1])*mvector;\n else\n mvector = Rfree*mvector;\n end\n mvector(3,:) = mvector(3,:) + B(3);\n end\n end\n \n % Convert scan from rad/ms to kHz\n scan = B1max./(2*pi);\n \ncase 't'\n % Scan through time\n \n % Fixed value are B1max and freq\n B1max = var1.*(2*pi);\n freq = var2.*2*pi;\n \n mvector = zeros(3, sum(RF(:,3))+1);\n count = 1;\n \n % Store the starting magnetization\n mvector(:,count) = M0;\n \n % Free Precession rotation\n freq = freq*dt;\n phi = freq;\n \n % Loop through the RF pulse\n for t = 1:cycles\n if grad_flag\n phi = freq .* RF(t,4);\n end\n \n % Rotate the matrix to align RF with X\n cosa = cos(-RF(t,1));\n sina = sin(-RF(t,1));\n Rz1 = [cosa sina 0; -sina cosa 0; 0 0 1];\n \n % Compute the RF rotation matrix\n theta = B1max*RF(t,2)*dt;\n cosa = cos(theta);\n sina = sin(theta);\n Rx=[1 0 0; 0 cosa sina; 0 -sina cosa];\n\n % Also rotate the matrix to undo the previous alignment with the RF\n % and free precession\n cosa = cos(phi + RF(t,1));\n sina = sin(phi + RF(t,1)); \n Rz2=[cosa sina 0; -sina cosa 0; 0 0 1];\n \n % Add in the decay terms\n Rz2 = A * Rz2;\n \n % For durations longer than one, repeat the small angle \n % approximation the prerquisite number of times\n for m = 1:RF(t,3)\n % Using small tip angle approximation to calculate the\n % new magnetization vector\n\n % RF alignment\n M0 = Rz1*M0;\n \n % Rotate the matrix by theta about X\t\n M0 = Rx*M0;\n \n % Free precesion, realignment and decay\n M0 = Rz2*M0 + B;\n \n % Store the magnetization vector\n count = count + 1;\n mvector(:,count) = M0;\n end\n end\n \n scan = [0:sum(RF(:,3))].*dt;\n \notherwise\n error('BES: Scan type is frequency, B1max, or time');\nend\n\nreturn\n", "meta": {"author": "CIC-methods", "repo": "FID-A", "sha": "c24da581e376f6eed66979dcc662ec26903a2eef", "save_path": "github-repos/MATLAB/CIC-methods-FID-A", "path": "github-repos/MATLAB/CIC-methods-FID-A/FID-A-c24da581e376f6eed66979dcc662ec26903a2eef/rfPulseTools/mklassenTools/bes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3710782872206114}} {"text": "function [FitResult,Spectrum] = multi_comp_fit_v2(data_vol, EchoTimes, DecayMatrix, T2, Opt, varargin)\n%\n% multi_comp_fit_v2(data_file_name, EchoTimes, DecayMatrix, T2, Opt, ['ROI', roi_vol, 'tissue', mask_vol])\n%\n%**************************************************************************\n% DESCRIPTION:\n%\n% A script to compute the multi-component T2 or T2* spectrum for an\n% echo train data set using regularized (and unregulatrized) NNLS. \n%\n% If an ROI mask if given, the user will be prompted to proceed with a\n% voxel-wise or ROI analysis. \n% voxel-wise analysis: The script will output superimposed plots of the T2/T2*\n% spectrum for each voxel, and calculate the average \n% MWF and gmT2/T2* for the ROI.\n% ROI analysis: The script will output plots of the average T2/T2* spectrum and \n% the average raw data + fits for that ROI. \n%\n% If no mask is given then the script will output maps of the geometric \n% mean T2/T2* (), the myelin water fraction (MWF) and the mono \n% exponential T2/T2*. \n%\n% If a tissue classification mask is given (cls_file_name), the user will \n% be prompted as to which tissue he/she wishes to analyze, and the maps \n% will be created for that tissue only.\n%\n%**************************************************************************\n% INPUTS:\n%\n% * data_vol = echo train data set to be analyzed\n% * EchoTimes = vector with all echo times \n% * DecayMatrix = matrix \n% * Opt = struct that must contains:\n% 1) RelaxationType : 'T2' or 'T2star'\n% 2) Sigma : noise's sigma\n% 3) lower_cutoff_MW : lower cutoff on Myelin Water T2 \n% 4) upper_cutoff_MW : upper cutoff on Myelin Water T2 \n% 5) upper_cutoff_IEW : upper cutoff on Intra/Extracellular Water T2\n% * 'ROI' = ROI processing flag\n% * roi_vol = ROI mask\n% * 'tissue' = tissue processing flag\n% * mask_vol = tissue mask, can be used to limit processing time\n% * varargin = optional file limiting the number of echoes to be used\n% for analysis. This can be:\n% 1) max_echoes.mnc file obtained from'in_plane_correction.m' \n% to perform in-plane field inhomogeneity correction\n% 2) correction_mask.mnc, obtained from 'Gz_correction.m'.\n% This binary file has voxels where the field gradient (Gz) \n% was > 2mG/cm set to 0 (no field inhomog. correction performed*), \n% and areas where Gz was < 2mG/cm set to 1. \n% *The correction fails where Gz > 2mG/cm. In order to limit \n% effect of field inhomogeneities in these voxels,\n% processing is limited to 45 echoes, instead of 64. \n%\n%**************************************************************************\n% EXAMPLE USES:\n% multi_comp_fit_v2(EchoTimes, DecayMatrix, T2, Opt, 'tissue', cls_mask)\n% --> Analyze vol T2 relaxation data, using a\n% tissue classification mask: cls_mask.\n% \n% AUTHOR: Eva Alonso Ortiz (eva.alonso.ortiz@gmail.com)\n% DATE LAST MODIFIED: \n% March 2016 - WIP: complex data anaylis is not currently working, do not\n% attempt to use it!\n%\n%**************************************************************************\n% SPECIAL VERSION adapted for qMRLab\n% By Ian Gagnon, 2017\n% For the original version, see multi_comp_fit.m\n% *************************************************************************\n\n%%-------------------------------------------------------------------------\n%% check existence of data files\n%%-------------------------------------------------------------------------\n\n% set processing labels\nROI_flag = 0;\nvoxelwise_ROI_flag = 0;\ntissue_flag = 0;\nmask_flag = 0;\n\n% default number of inputs\nndef_inputs = 5;\n\nif nargin > ndef_inputs \n if nargin < ndef_inputs+3\n mask_opts = nargin - ndef_inputs;\n else\n mask_opts = nargin - ndef_inputs - 1;\n end\n \n for counter = 2:2:(mask_opts)\n switch varargin{counter-1}\n case{'ROI'}\n roi_vol = varargin{counter};\n ROI_flag = 1;\n voxelwise_ROI_flag = input('Voxel-wise ROI analysis (1) or average ROI analysis (0)?: ');\n case{'tissue'}\n mask_vol = varargin{counter};\n tissue_flag = 1; \n end\n end\nend\n\n\n%%-------------------------------------------------------------------------\n%% Data informations\n%%------------------------------------------------------------------------- \n\ndata_dim = size(data_vol);\ndata_slices = data_dim(1,3);\ndata_height = data_dim(1,1);\ndata_width = data_dim(1,2);\ndata_voxels = data_height*data_width;\nnum_echoes = data_dim(1,4);\n\n%%-------------------------------------------------------------------------\n%% Compatibility mask/data\n%%-------------------------------------------------------------------------\n\nif ROI_flag == 1 \n roi_voxels = size(roi_vol,1)*size(roi_vol,2);\n if roi_voxels ~= data_voxels\n error(sprintf('\\nError in multi_comp_fit_v2: Mask file dimensions do not match data image file.\\n')); \n end\nend\n\nif tissue_flag ~= 0 \n mask_voxels = size(mask_vol,1)*size(mask_vol,2); \n if mask_voxels ~= data_voxels\n error(sprintf('\\nError in multi_comp_fit_v2: Mask file dimensions do not match data image file.\\n')); \n end \nend\n\n%%-------------------------------------------------------------------------\n%% default values for NNLS fitting\n%%-------------------------------------------------------------------------\n\nT2.num = 120;\n \n% set default values for reg-NNLS (taken from C. Chia)\nif ~moxunit_util_platform_is_octave\n set(0,'RecursionLimit',5000)\nend\nmu = 0.25;\nchi2range = [2 2.5];\nchi2_min = chi2range(1);\nchi2_max = chi2range(2);\n \n%%-------------------------------------------------------------------------\n%% apply ROI mask to data volumes\n%%-------------------------------------------------------------------------\n\nif (ROI_flag == 1 && voxelwise_ROI_flag == 0) \n mean_roi_data = get_avgROI_data(roi_vol, data_vol, data_dim);\nend\n\n%%-------------------------------------------------------------------------\n%% NNLS fitting routine presets\n%%-------------------------------------------------------------------------\n\n% find cutoff indices\nlower_cutoff_MW_index = find_cutoff_index(Opt.lower_cutoff_MW, T2.vals);\nupper_cutoff_MW_index = find_cutoff_index(Opt.upper_cutoff_MW, T2.vals);\nupper_cutoff_IEW_index = find_cutoff_index(Opt.upper_cutoff_IEW, T2.vals);\n\n%%-------------------------------------------------------------------------\n%% data fitting and analysis\n%%-------------------------------------------------------------------------\nif (ROI_flag == 1 && voxelwise_ROI_flag == 0)\n \n for slice = 1:data_slices\n \n %------------------------------\n % Do multi-exponential fitting\n %------------------------------ \n\n % Do non-regularized NNLS\n [spectrum_NNLS(slice,:), chi2_NNLS(slice)] = do_NNLS(DecayMatrix, double(squeeze(mean_roi_data(slice,:))), Opt.Sigma(slice));\n \n ssq_res_NNLS(slice) = sum((DecayMatrix*squeeze(spectrum_NNLS(slice,:)') - squeeze(mean_roi_data(slice,:))').^2);\n s0_NNLS(slice) = sum(spectrum_NNLS(slice,:));\n mwf_NNLS(slice) = sum(spectrum_NNLS(slice,lower_cutoff_MW_index:upper_cutoff_MW_index))/s0_NNLS(slice);\n\n if isnan(ssq_res_NNLS(slice))\n ssq_res_NNLS(slice) = 0;\n end\n if isnan(s0_NNLS(slice))\n s0_NNLS(slice) = 0;\n end\n if isnan(mwf_NNLS(slice))\n mwf_NNLS(slice) = 0;\n end\n \n % Calculate the geometric mean of the T2 distribition for the non-reg NNLS \n gm_t2_NNLS(slice) = exp(sum(squeeze(spectrum_NNLS(slice,:))'.*log(T2.vals))/sum(spectrum_NNLS(slice,:)));\n gm_IEW_t2_NNLS(slice) = exp(sum(squeeze(spectrum_NNLS(slice,upper_cutoff_MW_index:upper_cutoff_IEW_index))'.*log(T2.vals(upper_cutoff_MW_index:upper_cutoff_IEW_index)))/sum(spectrum_NNLS(slice,upper_cutoff_MW_index:upper_cutoff_IEW_index)));\n\n if isnan(gm_t2_NNLS(slice))\n gm_t2_NNLS(slice) = 0;\n end\n if isnan(gm_IEW_t2_NNLS(slice))\n gm_IEW_t2_NNLS(slice) = 0;\n end\n \n % Do regulaized NNLS \n [spectrum_regNNLS(slice,:), chi2_regNNLS(slice)] = ...\n iterate_NNLS(mu,chi2_min,chi2_max,T2.num,double(squeeze(mean_roi_data(slice,:))),DecayMatrix,chi2_NNLS(slice),Opt.Sigma(slice));\n\n ssq_res_regNNLS(slice) = sum((DecayMatrix*squeeze(spectrum_regNNLS(slice,:)') - squeeze(mean_roi_data(slice,:))').^2);\n s0_regNNLS(slice) = sum(spectrum_regNNLS(slice,:));\n mwf_regNNLS(slice) = sum(spectrum_regNNLS(slice,1:upper_cutoff_MW_index))/s0_regNNLS(slice);\n\n if isnan(ssq_res_regNNLS(slice))\n ssq_res_regNNLS(slice) = 0;\n end\n if isnan(s0_regNNLS(slice))\n s0_regNNLS(slice) = 0;\n end\n if isnan(mwf_regNNLS(slice))\n mwf_regNNLS(slice) = 0;\n end\n \n % Calculate the geometric mean of the T2 distribition for the reg NNLS \n gm_t2_regNNLS(slice) = exp(sum(squeeze(spectrum_regNNLS(slice,:))'.*log(T2.vals))/sum(spectrum_regNNLS(slice,:)));\n gm_IEW_t2_regNNLS(slice) = exp(sum(squeeze(spectrum_regNNLS(slice,upper_cutoff_MW_index:upper_cutoff_IEW_index))'.*log(T2.vals(upper_cutoff_MW_index:upper_cutoff_IEW_index)))/sum(spectrum_regNNLS(slice,upper_cutoff_MW_index:upper_cutoff_IEW_index))); \n \n if isnan(gm_t2_regNNLS(slice))\n gm_t2_regNNLS(slice) = 0;\n end\n if isnan(gm_IEW_t2_regNNLS(slice))\n gm_IEW_t2_regNNLS(slice) = 0;\n end\n \n %-----------------------------\n % Do mono-exponential fitting \n %-----------------------------\n\n % Fit to single T2 decay component for comparison\n t2_guess = 100;\n guess = [t2_guess, mean_roi_data(slice,1)];\n\n [s0_fit(slice), t2_fit(slice)] = mono_exp_fit(double(squeeze(mean_roi_data(slice,:))), EchoTimes, double(guess));\n \n if isnan(s0_fit(slice))\n s0_fit(slice) = 0;\n end\n if isnan(s0_fit(slice))\n s0_fit(slice) = 0;\n end\n end\n \nelse\n if (ROI_flag == 1 && voxelwise_ROI_flag == 1) \n mask_flag = 1;\n mask_vol = roi_vol; \n else \n if (tissue_flag == 0 && voxelwise_ROI_flag == 0)\n \n % create brain mask to limit processing time (and mask out noise in\n % images!) \n% create_brainmask(data_file_name);\n mask_flag = 1;\n % open brain mask\n else\n mask_flag = tissue_flag;\n end\n end\n\n % initialize all data vectors to zero\n spectrum_NNLS = zeros(data_height,data_width,data_slices,T2.num);\n chi2_NNLS = zeros(data_height,data_width,data_slices);\n gm_t2_NNLS = zeros(data_height,data_width,data_slices);\n gm_IEW_t2_NNLS = zeros(data_height,data_width,data_slices);\n ssq_res_NNLS = zeros(data_height,data_width,data_slices);\n s0_NNLS = zeros(data_height,data_width,data_slices);\n mwf_NNLS = zeros(data_height,data_width,data_slices);\n\n spectrum_regNNLS = zeros(data_height,data_width,data_slices, T2.num);\n spectrum_regNNLS_A = zeros(data_height,data_width,data_slices, T2.num);\n spectrum_regNNLS_B = zeros(data_height,data_width,data_slices, T2.num);\n amp_spectrum_regNNLS = zeros(data_height,data_width,data_slices, T2.num);\n phase_spectrum_regNNLS = zeros(data_height,data_width,data_slices, T2.num);\n chi2_regNNLS = zeros(data_height,data_width,data_slices);\n gm_t2_regNNLS = zeros(data_height,data_width,data_slices);\n gm_IEW_t2_regNNLS = zeros(data_height,data_width,data_slices);\n gm_MW_t2_regNNLS = zeros(data_height,data_width,data_slices);\n ssq_res_regNNLS = zeros(data_height,data_width,data_slices);\n s0_regNNLS = zeros(data_height,data_width,data_slices);\n mwf_regNNLS = zeros(data_height,data_width,data_slices);\n mw_delf_regNNLS = zeros(data_height,data_width,data_slices);\n\n s0_fit = zeros(data_height,data_width,data_slices);\n t2_fit = zeros(data_height,data_width,data_slices);\n\n if (ROI_flag == 1 && voxelwise_ROI_flag == 1)\n \n %-------------------------------------------\n % Prepare figure for superimposed spectrum\n %-------------------------------------------\n figure; hold on;\n set(gca,'xscale','log','FontSize',20,'XMinorTick','on')\n xlim([T2.range(1) T2.range(2)])\n ylabel('Normalized Signal');\n if strcmp(Opt.RelaxationType,'T2')\n xlabel('T2 (ms)');\n title('T_2 Spectrum','FontSize',20);\n elseif strcmp(Opt.RelaxationType,'T2star')\n xlabel('T2* (ms)');\n title('T_2^* Spectrum','FontSize',20); \n end\n x = [Opt.upper_cutoff_MW, Opt.upper_cutoff_MW];\n y = [0, 1];\n plot(x,y,'r-','LineWidth', 4);\n grid minor;\n\n end\n \n for slice = 1:data_slices\n\n for i = 1:data_height\n for j = 1:data_width\n\n % only fill in what corresponds to the mask\n if mask_vol(i,j,slice) == mask_flag \n this_echo_times = EchoTimes;\n this_num_echoes = num_echoes;\n this_DecayMatrix = DecayMatrix;\n this_lower_cutoff_MW_index = lower_cutoff_MW_index;\n this_upper_cutoff_MW_index = upper_cutoff_MW_index;\n this_upper_cutoff_IEW_index = upper_cutoff_IEW_index;\n \n % Do non-regularized NNLS\n [spectrum_NNLS(i,j,slice,:), chi2_NNLS(i,j,slice)] = do_NNLS(this_DecayMatrix, double(squeeze(data_vol(i,j,slice,1:this_num_echoes)))', Opt.Sigma(slice));\n\n % Do regulaized NNLS \n [spectrum_regNNLS(i,j,slice,:), chi2_regNNLS(i,j,slice)] = ...\n iterate_NNLS(mu,chi2_min,chi2_max,double(squeeze(data_vol(i,j,slice,1:this_num_echoes)))',this_DecayMatrix,chi2_NNLS(i,j,slice),Opt.Sigma(slice));\n %------------------------------\n % Do multi-exponential fitting\n %------------------------------ \n \n s0_regNNLS(i,j,slice) = sum(spectrum_regNNLS(i,j,slice,:));\n mwf_regNNLS(i,j,slice) = sum(spectrum_regNNLS(i,j,slice,1:this_upper_cutoff_MW_index))/s0_regNNLS(i,j,slice);\n\n % Calculate the geometric mean of the T2 distribition for the reg NNLS \n gm_t2_regNNLS(i,j,slice) = exp(sum(squeeze(spectrum_regNNLS(i,j,slice,:)).*log(T2.vals))/sum(spectrum_regNNLS(i,j,slice,:)));\n gm_IEW_t2_regNNLS(i,j,slice) = exp(sum(squeeze(spectrum_regNNLS(i,j,slice,this_upper_cutoff_MW_index:this_upper_cutoff_IEW_index)).*log(T2.vals(this_upper_cutoff_MW_index:this_upper_cutoff_IEW_index)))/sum(spectrum_regNNLS(i,j,slice,this_upper_cutoff_MW_index:this_upper_cutoff_IEW_index)));\n gm_MW_t2_regNNLS(i,j,slice) = exp(sum(squeeze(spectrum_regNNLS(i,j,slice,this_lower_cutoff_MW_index:this_upper_cutoff_MW_index)).*log(T2.vals(this_lower_cutoff_MW_index:this_upper_cutoff_MW_index)))/sum(spectrum_regNNLS(i,j,slice,this_lower_cutoff_MW_index:this_upper_cutoff_MW_index)));\n\n if isnan(gm_t2_regNNLS(i,j,slice))\n gm_t2_regNNLS(i,j,slice) = 0;\n end\n if isnan(gm_IEW_t2_regNNLS(i,j,slice))\n gm_IEW_t2_regNNLS(i,j,slice) = 0;\n end\n if isnan(gm_MW_t2_regNNLS(i,j,slice))\n gm_MW_t2_regNNLS(i,j,slice) = 0;\n end \n if isnan(s0_regNNLS(i,j,slice))\n s0_regNNLS(i,j,slice) = 0;\n end\n if isnan(mwf_regNNLS(i,j,slice))\n mwf_regNNLS(i,j,slice) = 0;\n end\n \n %-----------------------------\n % Do mono-exponential fitting \n %-----------------------------\n \n if (ROI_flag == 1 && voxelwise_ROI_flag == 1)\n \n %-----------------------------\n % Plot the T2 spectrum\n %-----------------------------\n\n % Normalize distributions\n norm_spectrum_NNLS(i,j,slice,:) = spectrum_NNLS(i,j,slice,:)/max(spectrum_NNLS(i,j,slice,:));\n norm_spectrum_regNNLS(i,j,slice,:) = spectrum_regNNLS(i,j,slice,:)/max(spectrum_regNNLS(i,j,slice,:));\n\n plot(T2.vals,squeeze(norm_spectrum_regNNLS(i,j,slice,:)), 'b-','LineWidth',0.1);\n print('-djpeg','superimposed_spectrum.jpeg');\n \n end\n end\n end\n end\n end\nend\n\n\n%--------------------------------------------------------------------------\n\nif ( ROI_flag == 1 && voxelwise_ROI_flag == 0 )\n\n for slice = 1:data_slices\n \n %% Plot the T2 spectrum\n\n % Normalize distributions\n norm_spectrum_NNLS(slice,:) = spectrum_NNLS(slice,:)/max(spectrum_NNLS(slice,:));\n norm_spectrum_regNNLS(slice,:) = spectrum_regNNLS(slice,:)/max(spectrum_regNNLS(slice,:));\n\n figure; hold on;\n grid minor;\n %bar1 = bar(T2.vals,norm_spectrum_NNLS(slice,:),'FaceColor', 'g', 'EdgeColor', 'g','LineWidth',1);\n %set(bar1,'BarWidth',0.1); \n \n% %--------------------\n% % If the data is simulated: Plot \"true\" spectrum (otherwise,\n% % comment this out)\n% %--------------------\n% T2 = [5 50]';\n% frac = [0.12 0.88]';\n% \n% true_spectrum = zeros(size(T2.vals));\n% for j = 1: size(T2)\n% for i = 1:(size(T2.vals)-1)\n% if i == 1\n% if T2(j) == T2.vals(i)\n% true_spectrum(i) = frac(j);\n% end\n% end\n% \n% if ((T2.vals(i+1) >= T2(j)) && (T2.vals(i) <= T2(j)))\n% true_spectrum(i) = frac(j);\n% end\n% end\n% end\n% bar2 = bar(T2.vals,true_spectrum(:),'FaceColor', 'm', 'EdgeColor', 'm','LineWidth',1);\n% %set(bar2,'BarWidth',0.1); \n% %--------------------\n \n plot(T2.vals,norm_spectrum_regNNLS(slice,:), 'b-','LineWidth',1.5);\n set(gca,'xscale','log','FontSize',20)\n xlim([T2.range(1) T2.range(2)])\n %xlim([0.002*1e3 4*1e3]) %keep T2* and T2 ranges the same for plot\n ylabel('Normalized Signal');\n if strcmp(Opt.RelaxationType,'T2')\n xlabel('T2 (ms)');\n title('T_2 Spectrum','FontSize',20);\n elseif strcmp(Opt.RelaxationType,'T2star')\n xlabel('T2* (ms)');\n title('T_2^* Spectrum','FontSize',20); \n end\n x = [Opt.lower_cutoff_MW, Opt.upper_cutoff_MW];\n y = [0, 1];\n plot(x,y,'r-','LineWidth', 2);\n% legend('location', 'NorthEast','NNLS multi-exp fit','True Spectrum','regularized NNLS multi-exp fit')\n% legend('location', 'NorthEast','NNLS multi-exp fit','regularized NNLS multi-exp fit')\n% legend('location', 'NorthEast','regularized NNLS multi-exp fit')\n print('-djpeg','spectrum.jpeg')\n \n %% Plot the decay curve and fitted line\n\n % Reconstruct the signal intensities and plot back on \n % top of the original data.\n\n single_sig_recon(slice,:) = s0_fit(slice).*exp(-EchoTimes/t2_fit(slice));\n multi_sig_recon(slice,:) = DecayMatrix * spectrum_NNLS(slice,:)';\n reg_multi_sig_recon(slice,:) = DecayMatrix * spectrum_regNNLS(slice,:)';\n\n figure; hold on;\n plot(EchoTimes, mean_roi_data(slice,:), 'kx', 'MarkerSize',10);\n% plot(echo_times, single_sig_recon(slice,:), 'g-.','LineWidth',2);\n% plot(echo_times, multi_sig_recon(slice,:), 'b-','LineWidth',2);\n plot(EchoTimes, reg_multi_sig_recon(slice,:), 'r--','LineWidth',2);\n if strcmp(Opt.RelaxationType,'T2')\n% legend('location', 'best', 'SE data','mono-exponential fit','NNLS multi-exp fit','regularized NNLS multi-exp fit');\n legend('location', 'best', 'SE data','regularized NNLS multi-exp fit');\n elseif strcmp(Opt.RelaxationType,'T2star')\n% legend('location', 'best','GRE data','mono-exponential fit','NNLS multi-exp fit','regularized NNLS multi-exp fit');\n legend('location', 'best', 'SE data','regularized NNLS multi-exp fit');\n end\n xlabel('TE (ms)');\n ylabel('Signal (arb)');\n grid on;\n print('-djpeg','signal_decay.jpeg');\n\n if strcmp(Opt.RelaxationType,'T2')\n %disp(fprintf('\\nmulti-exp NNLS (slice %d) => : %3.2f ms, MWF: %3.2f', slice, gm_t2_NNLS(slice), mwf_NNLS(slice))); \n disp(fprintf('multi-exp regNNLS (slice %d) => IE water : %3.2f ms, MWF: %3.2f', slice, gm_IEW_t2_regNNLS(slice), 100*mwf_regNNLS(slice))); \n %disp(fprintf('Mono-exponential T2 fit (slice %d): %3.2f ms', slice, t2_fit(slice))); \n elseif strcmp(Opt.RelaxationType,'T2star')\n %disp(fprintf('\\nmulti-exp NNLS (slice %d) => : %3.2f ms, MWF: %3.2f', slice, gm_t2_NNLS(slice), mwf_NNLS(slice))); \n disp(fprintf('multi-exp regNNLS (slice %d) => IE water : %3.2f ms, MWF: %3.2f', slice, gm_IEW_t2_regNNLS(slice), 100*mwf_regNNLS(slice))); \n %disp(fprintf('Mono-exponential T2* fit (slice %d): %3.2f ms', slice, t2_fit(slice))); \n end\n \n end\n\nelseif ROI_flag == 0 \n FitResult.MWF = 100*mwf_regNNLS;\n FitResult.T2IEW = gm_IEW_t2_regNNLS; \n FitResult.T2MW = gm_MW_t2_regNNLS;\n Spectrum = squeeze(spectrum_regNNLS);\nend \n\nif ( tissue_flag ~= 0 || voxelwise_ROI_flag == 1 )\n mwf_regNNLS = reshape(mwf_regNNLS,data_voxels,data_slices);\n gm_IEW_t2_regNNLS = reshape(gm_IEW_t2_regNNLS,data_voxels,data_slices);\n for slice = 1:data_slices\n mROI_mwf_regNNLS(slice) = mean(nonzeros(mwf_regNNLS(:,slice)));\n valtmp = std(nonzeros(mwf_regNNLS(:,slice))); \n if isempty(valtmp), stdROI_regNNLS(slice) = nan; else stdROI_regNNLS(slice) = valtmp; end\n mROI_gm_IEW_t2_regNNLS(slice) = mean(nonzeros(gm_IEW_t2_regNNLS(:,slice)));\n valtmp = std(nonzeros(gm_IEW_t2_regNNLS(:,slice))); \n if isempty(valtmp), stdROI_gm_IEW_t2_regNNLS(slice) = nan; else stdROI_gm_IEW_t2_regNNLS(slice) = valtmp; end\n\n% mROI_gm_MW_t2_regNNLS(slice) = mean(nonzeros(gm_MW_t2_regNNLS(:,slice)));\n% stdROI_gm_MW_t2_regNNLS(slice) = std(nonzeros(gm_MW_t2_regNNLS(:,slice))); \n% disp(fprintf('\\nAverage regMWF over tissue mask (slice %d): %3.2f +/- %3.2f %%', slice, 100*mROI_mwf_regNNLS(slice), 100*stdROI_regNNLS(slice))); \n% disp(fprintf('\\nAverage IE water gm_T2 over tissue mask (slice %d): %3.2f +/- %3.2f ms', slice, mROI_gm_IEW_t2_regNNLS(slice), stdROI_gm_IEW_t2_regNNLS(slice))); \n% disp(fprintf('\\nAverage Myelin water gm_T2 over tissue mask (slice %d): %3.2f +/- %3.2f ms', slice, mROI_gm_MW_t2_regNNLS(slice), stdROI_gm_MW_t2_regNNLS(slice))); \n end\nend\n\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_Functions/MWF/met2_eva/multi_comp_fit_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3708743489707647}} {"text": "function [FF,II] = remesh_at_points(V,F,P)\n % REMESH_AT_POINTS Given a surface mesh (V,F) and a list of points on/near the\n % surface P, subdivide triangles of (V,F) so that P are now contained in the\n % vertex set.\n %\n % Inputs:\n % V #V by 3 list of vertex positions\n % F #F by 3 list of face indices into V\n % P #P by 3 list of point positions\n % Outputs:\n % FF #FF by 3 list of face indices into [V;P]\n % II #FF list of indices into F revealing birth face\n %\n % Example:\n % P = random_points_on_mesh(V,F,size(F,1));\n % [FF,II] = remesh_at_points(V,F,P);\n % tsurf(FF,[V;P],'CData',II)\n %\n\n VV = V;\n FF = F;\n II = (1:size(F,1))';\n JJ = zeros(size(V,1),1);\n L = (1:size(P,1))';\n PP = P;\n while true\n %clf;hold on;tsurf(FF,VV,'CData',II);scatter3(PP(:,1),PP(:,2),PP(:,3));hold off;pause\n % Find closest points/faces on mesh (This is a bit redundant. Really we\n % should only look at faces that _were_ affected last round, since those\n % must have had multiple points.)\n [~,IC,C] = point_mesh_squared_distance(PP,VV,FF);\n % Only keep one closest point per face\n [I,J] = unique(IC);\n % append keepers\n n = size(VV,1);\n JJ = [JJ;L(J)];\n VV = [VV;C(J,:)];\n nCI = n+(1:numel(J))';\n unaffected = setdiff(1:size(FF,1),I);\n II = [II(unaffected);repmat(II(I),3,1)];\n FF = [ ...\n FF(unaffected,:);\n FF(I,[1 2]) nCI; ...\n FF(I,[2 3]) nCI; ...\n FF(I,[3 1]) nCI];\n % Leftovers\n L = L(setdiff(1:end,J));\n PP = P(L,:);\n if isempty(PP)\n break;\n end\n end\n\n %% Re-order so that output is simply VV = [V;C]\n %C = zeros(size(P));\n %C(JJ(size(V,1)+1:end),:) = VV(size(V,1)+1:end,:);\n I = JJ+size(V,1);\n I(1:size(V,1)) = 1:size(V,1);\n FF = I(FF);\n %VV = [V;C];\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_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.37068254761517805}} {"text": "function [newpt elemid weight]=proj2mesh(v,f,pt,nv,cn,radmax)\n% [newpt elemid weight]=proj2mesh(v,f,pt,nv,cn)\n%\n% project a point cloud on to the surface mesh (surface can only be triangular)\n%\n% author: Qianqian Fang \n% date: 12/12/2008\n%\n% parameters: \n% v: node coordinate of the surface mesh (nn x 3)\n% f: element list of the surface mesh (3 columns for \n% triangular mesh, 4 columns for cubic surface mesh)\n% pt: points to be projected, 3 columns for x,y and z respectively\n% nv: nodal norms (vector) calculated from nodesurfnorm.m\n% with dimensions of (size(v,1),3)\n% cn: a integer vector with the length of p, denoting the closest\n% surface nodes (indices of v) for each point in p. this \n% value can be calculated from dist2surf.m\n% radmax: if speicified, the search for elements to project will be\n% limited to those within a bounding box with half-edge-length \n% of radmax centered at the point to be projected\n%\n% if nv and cn are not supplied, proj2mesh will project the point\n% cloud onto the surface by the direction pointing to the centroid\n% of the mesh\n%\n% outputs:\n% newpt: the projected points from p\n% elemid: a vector of length of p, denotes which surface trangle (in elem)\n% contains the projected point\n% weight: the barycentric coordinate for each projected points, these are\n% the weights \n%\n% Please find more information at http://iso2mesh.sf.net/cgi-bin/index.cgi?metch\n%\n% this function is part of \"metch\" toobox, see COPYING for license\n\ncent=mean(v);\nenum=length(f);\nec=reshape(v(f(:,1:3)',:)', [3 3,enum]);\ncentroid=squeeze(mean(ec,2));\nnewpt =zeros(size(pt,1),3);\nelemid=zeros(size(pt,1),1);\nweight=zeros(size(pt,1),3);\n[idoldmesh,loc]=ismember(pt,v,'rows');\nidnode=find(idoldmesh);\nif(~isempty(idnode))\n [tt,ll]=ismember(loc(idnode),f);\n [p1,p2]=ind2sub(size(f),ll); % p1 is the index in f\n newpt(idnode,:)=pt(idnode,:);\n elemid(idnode)=p1;\n weight(sub2ind(size(weight),idnode,p2))=1;\nend\nradlimit=-1;\n\nif(nargin>=5) \n % if nv and cn are supplied, use nodal norms to project the points\n direction=nv(cn,:);\n if(nargin>=6) \n radlimit=radmax;\n end\nelseif(nargin==3)\n % otherwise, project toward the centroid\n direction=pt-repmat(cent,size(pt,1),1);\nend\n\nfor t=1:size(pt,1)\n if(idoldmesh(t)~=0) continue; end\n maxdist=sqrt(sum((pt(t,:)-cent).*(pt(t,:)-cent)));\n \n if(radlimit>0)\n maxdist=radlimit;\n end\n \n idx=find(centroid(1,:)>pt(t,1)-maxdist & ...\n centroid(1,:)pt(t,2)-maxdist & ...\n centroid(2,:)pt(t,3)-maxdist & ...\n centroid(3,:)DUNEuro Wiki page.');\n return\nend\n\nheadmodel.type = 'duneuro';\nheadmodel.forward = forward;\nheadmodel.electrodes = electrodes;\nheadmodel.subentities = subentities;\nheadmodel.intorderadd = intorderadd;\nheadmodel.intorderadd_lb = intorderadd_lb;\nheadmodel.initialization = initialization;\nheadmodel.numberOfMoments = numberOfMoments;\nheadmodel.referenceLength = referenceLength;\nheadmodel.relaxationFactor = relaxationFactor;\nheadmodel.restrict = restrict;\nheadmodel.weightingExponent = weightingExponent;\nheadmodel.mixedMoments = mixedMoments;\nheadmodel.post_process = post_process;\nheadmodel.subtract_mean = subtract_mean;\nheadmodel.reduction = reduction;\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/forward/ft_headmodel_duneuro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5, "lm_q1q2_score": 0.37008718101950816}} {"text": "function [y,ev] = dmrg_eigb(a,k,eps,varargin)\n%Find several minimal eigenvalues of a TT-matrix using DMRG method\n% [Y,EV]=DMRG_EIGB(A,K,EPS,OPTIONS) Attempts to find K minimal\n% eigenvalues of a TT-matrix A with accuracy EPS. We use minimization of\n% Block-Rayleigh quotient to do this. The solution is returned a block\n% TT-tensor (i.e, r(d+1) is equal to K).\n% 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 y0 - initial approximation [random rank-5 tensor]\n% o rmax - maximal TT-rank of the (block) solution [2500]\n% o nswp - maximal number of sweeps [4]\n% o kick_rank - stabilization parameter, the larger, the better\n% accuracy but the higher complexity [5]\n% o verb - print debug info [ {true} | false ]\n% o msize - the size of local matrix when the iterative solver is\n% used\n% Example:\n% d=8; f=3;\n% mat=tt_qlaplace_dd(d*ones(1,f)); %Laplace in the QTT-format\n% [v,ev]=dmrg_eigb(mat,5,1e-6); %5 lowest eigenvalues \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\nwarning('This realisation is old and not optimal. Consider using dmrg_eig');\n\n%Default parameters\ny0=[];\nnswp=4;\nmsize=1;\nmax_l_steps=200;\nkickrank=4;\nverb=1;\nrmax = Inf;\nfor i=1:2:length(varargin)-1\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'kickrank'\n kickrank=lower(varargin{i+1});\n case 'x0'\n y0=varargin{i+1};\n case 'msize'\n msize=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'rmax'\n rmax=varargin{i+1};\n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n \n end\nend\n\nn=a.n; \nd=a.d;\nif ( isempty(y0) )\n kk=max(5,k);\n r=kk*ones(1,d+1);\n r(d+1)=k;\n r(1)=1;\n y0=tt_random(n,d,r);\nend\ny=round(y0,0);\n\nlocal_eps = eps/sqrt(d);\n\n%We start from the orthogonalization of the y vector from left-to-right\n%(it does not influence the TT-ranks)\n\npsy=y.ps;\nry=y.r;\ntta=a.tt;\npsa=tta.ps;\nra=tta.r;\ncra=tta.core;\ncry=y.core;\nrm=1; \n%Also we will need to compute phi-matrices\nphi=cell(d+1,1);\nphi{1}=1; %This one is right now unchanged\nphi{d+1}=1; %Seems to be unchanged also\npos1=1;\nfor i=1:d\n cr=cry(psy(i):psy(i+1)-1);\n cr=reshape(cr,[ry(i),n(i)*ry(i+1)]);\n cr=rm*cr; \n ry(i)=size(cr,1); \n cr=reshape(cr,[ry(i)*n(i),ry(i+1)]);\n [u,rm]=qr(cr,0);\n rnew=size(u,2); \n %ry(i+1)=rnew;\n cry(pos1:pos1+ry(i)*n(i)*rnew-1)=u(:); \n pos1=pos1+ry(i)*n(i)*rnew;\n %With this new core compute (Ax,x) to the phi matrix\n %u=reshape(u,[ry(i),n(i),ry(i+1)]);\n crm=cra(psa(i):psa(i+1)-1);\n crm=reshape(crm,[ra(i),n(i),n(i),ra(i+1)]); \n phx=phi{i};\n phx=reshape(phx,[ra(i),ry(i),ry(i)]); phx=permute(phx,[1,3,2]);\n x0=u;\n x0=reshape(x0,[ry(i),n(i)*rnew]);\n phx=reshape(phx,[ra(i)*ry(i),ry(i)]);\n phx=phx*x0; %phx is ra(i)*ry(i)*n(i)*ry(i+1)\n phx=reshape(phx,[ra(i),ry(i),n(i),rnew]);\n crm=permute(crm,[1,3,2,4]); crm=reshape(crm,[ra(i)*n(i),n(i)*ra(i+1)]);\n %Convolve over (ak-1) j with the matrix\n phx=permute(phx,[2,4,1,3]); \n phx=reshape(phx,[ry(i)*rnew,ra(i)*n(i)]);\n phx=phx*crm; %ry(i)*ry(i+1)*n(i)*ra(i+1)\n phx=reshape(phx,[ry(i),rnew,n(i),ra(i+1)]);\n phx=permute(phx,[2,4,1,3]);\n phx=reshape(phx,[rnew*ra(i+1),ry(i)*n(i)]);\n x0=u;\n x0=reshape(x0,[ry(i)*n(i),rnew]);\n phx=phx*x0; \n phx=reshape(phx,[rnew,ra(i+1),rnew]); \n phx=permute(phx,[2,1,3]);\n phi{i+1}=phx;\n %phi{i+1}=permute(phi{i+1},[1,3,2]);\nend\n\nry(d+1)=rnew; %This value should not be modified :(((\n%Truncate the core\ncry=cry(1:pos1-1);\ny.r=ry;\ny.core=cry;\ny.ps=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n %Test back transform\n% y0=y;\n% y0.n=[2*ones(d,1);k];\n% y0.r=[y.r;1];\n% y0.d=d;\n% e0=eye(ry(d));\n% cry=[cry,e0(:)'];\n% y0.core=cry;\n% ww1=full(y0); ww1=reshape(ww1,[numel(ww1)/k,k]);\n% bm=ww0'*ww1;\n% norm(ww1-ww0*bm)\n%keyboard;\nphi{d+1}=1; %Bydlocode, but seems necessary\ny.r=ry;\ny.core=cry;\ny.ps=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\npsy=y.ps;\n%Now start the main DMRG sweep\nswp=1;\nnot_converged=true;\nerr_max = 0;\n%ry(1)=1;\nry(d+1)=1;\ndir='rl';\ni=d-1;\ncry_left=cry(1:psy(d)-1);\ncry_right=cry(psy(d):psy(d+1)-1);\nwhile ( swp <= nswp && not_converged )\n %As usual, compute (local) B-matrix in the TT-format\n cra1=cra(psa(i):psa(i+1)-1); \n cra2=cra(psa(i+1):psa(i+2)-1);\n px1=phi{i}; px1=reshape(px1,[ra(i),ry(i),ry(i)]); \n %px1=permute(px1,[1,2,3]); \n px1=permute(px1,[1,3,2]);\n px1=reshape(px1,[ra(i),ry(i)*ry(i)]);\n px2=phi{i+2}; \n px2=reshape(px2,[ra(i+2),ry(i+2),ry(i+2)]);\n %px2=permute(px2,[1,3,2]);\n %Compute the local matrix just by putting px1 into cra1, px2 into\n %cra2\n cra2=reshape(cra2,[ra(i+1)*n(i+1)*n(i+1),ra(i+2)]);\n px2=reshape(px2,[ra(i+2),ry(i+2)*ry(i+2)]);\n b2=cra2*px2; % \n b1=px1.'*reshape(cra1,[ra(i),numel(cra1)/ra(i)]);\n b1=reshape(b1,[ry(i),ry(i),n(i),n(i),ra(i+1)]); b1_save=b1; %Save for phi computations\n b1=permute(b1,[1,3,2,4,5]); \n b1=reshape(b1,[ry(i)*n(i),ry(i)*n(i),ra(i+1)]);\n b2=reshape(b2,[ra(i+1),n(i+1),n(i+1),ry(i+2),ry(i+2)]);\n b2_save=b2; %Save for phi computations\n b2=permute(b2,[2,4,3,5,1]); \n b2=reshape(b2,[n(i+1)*ry(i+2),n(i+1)*ry(i+2),ra(i+1)]);\n mm=cell(2,1); mm{1}=b1; mm{2}=b2;\n cry=[cry_left(:);cry_right(:)];\n y.r=ry;\n y.core=cry;\n y.ps=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\n %mm1=tt_matrix(mm);\n %Now setup the initial guess: i the core \n if ( strcmp(dir,'rl') ) %The block index is in the second core\n pos=numel(cry_left);\n cry1=cry_left(pos-ry(i)*n(i)*ry(i+1)+1:pos);\n cry2=cry_right(1:ry(i+1)*n(i+1)*k*ry(i+2));\n cry1=reshape(cry1,[ry(i)*n(i),ry(i+1)]);\n cry2=reshape(cry2,[ry(i+1),n(i+1)*k*ry(i+2)]);\n w=cry1*cry2; w=reshape(w,[ry(i),n(i),n(i+1),k,ry(i+2)]);\n w=permute(w,[1,2,3,5,4]); w=reshape(w,[numel(w)/k,k]);\n else %The block index is in the first core\n pos=numel(cry_left); \n cry1=cry_left(pos-ry(i)*n(i)*k*ry(i+1)+1:pos);\n cry2=cry_right(1:ry(i+1)*n(i+1)*ry(i+2));\n cry1=reshape(cry1,[ry(i)*n(i)*k,ry(i+1)]);\n cry2=reshape(cry2,[ry(i+1),n(i+1)*ry(i+2)]);\n w=cry1*cry2; w=reshape(w,[ry(i),n(i),k,n(i+1),ry(i+2)]);\n w=permute(w,[1,2,4,5,3]); w=reshape(w,[numel(w)/k,k]);\n end\n %Now run the eigenvalue solver\n bw=bfun(mm,w); ev=bw'*w; \n %er0=norm(bw-w*ev,'fro')/norm(w,'fro');\n er_old=bw-w*ev; \n erc=zeros(1,size(w,2));\n for j=1:size(w,2)\n erc(j)=norm(er_old(:,j));\n end\n er0=norm(er_old,'fro')/norm(w,'fro'); \n if ( size(w,1) >= max(5*k,msize) )\n matvec='bfun';\n [wnew,ev,fail_flag]=lobpcg(w,@(x) bfun(mm,x),local_eps,max_l_steps);\n else\n matvec='full';\n fm=full(tt_matrix(mm)); \n [v,dg]=eig(fm);\n %[v,dg]=eigs(sparse(fm),k+1);\n %keyboard;\n ev=diag(dg);\n [ev,ind]=sort(ev,'ascend');\n v=v(:,ind);\n wnew=v(:,1:k);\n ev=ev(1:k);\n end\n er1=norm(bfun(mm,wnew)-wnew*diag(ev),'fro')/norm(wnew,'fro');\n \n % Check the distance between iterations\n dx = norm(wnew*(wnew'*w)-w);\n\n fv=sum(ev); %The functional we minimize;\n if ( verb>1 )\n fprintf('sweep=%d block=%d fv=%10.15f loc solve=%3.2e old_solve=%3.2e \\n',swp,i,fv,er1,er0);\n disp(erc);\n end\n if ( strcmp(dir,'rl') ) %Implant the auxiliary core into the i-th core\n %(a1,i1,a2,a2,i2*g,a3)-> (a1,i1*g,a2,a2,i2,a3)\n %Delete old block from the core_left, add new block to the core\n %right\n \n %Prepare the truncation block\n rhs=wnew*diag(ev); \n if (strcmp(matvec,'full'))\n res_true = norm(fm*wnew-rhs)/norm(rhs);\n else\n res_true = norm(bfun(mm,wnew)-rhs)/norm(rhs);\n end;\n\n \n wnew=reshape(wnew,[ry(i),n(i),n(i+1),ry(i+2),k]);\n wnew=permute(wnew,[1,2,5,3,4]); wnew=reshape(wnew,[ry(i)*n(i)*k,n(i+1)*ry(i+2)]);\n [u,s,v]=svd(wnew,'econ'); s=diag(s); \n %Truncation block\n rnew=my_chop2(s,local_eps*norm(s));\n \n %%%\n rnew = min(rnew, numel(s));\n rnew = min(rnew, rmax);\n %%%%\n \n u=u(:,1:rnew); s=s(1:rnew); v=v(:,1:rnew);% v=v';\n u=u*diag(s); %u has to be reshaped \n \n % Residual truncation\n% r0=1; r1=min(numel(s),rmax);\n% r=1; \n% while ( (r ~= r0 || r ~= r1) && r0 <= r1)\n% r=min(floor((r0+r1)/2),rmax);\n% %er0=norm(s(r+1:numel(s)));\n% u1=u(:,1:r)*diag(s(1:r)); \n% %Sonate u1\n% u1=reshape(u1,[ry(i)*n(i),k,r]);\n% u1=permute(u1,[1,3,2]);\n% u1=reshape(u1,[numel(u1)/k,k]);\n% [u2,~,v2]=svd(u1,'econ');\n% u1=u2*v2';\n% u1=reshape(u1,[ry(i)*n(i),r,k]);\n% u1=permute(u1,[1,3,2]);\n% u1=reshape(u1,[numel(u1)/r,r]);\n% sol = u1*(v(:,1:r))';\n% \n% sol = reshape(sol,[ry(i),n(i),k,n(i+1),ry(i+2)]);\n% sol=permute(sol,[1,2,4,5,3]); sol=reshape(sol,[numel(sol)/k,k]);\n% %if ( norm(sol'*sol-eye(k))>1e-3 )\n% % keyboard\n% %end\n% if (strcmp(matvec,'full'))\n% resid = norm(fm*sol-rhs)/norm(rhs);\n% else\n% resid = norm(bfun(mm,sol)-rhs)/norm(rhs);\n% end;\n% if ( verb )\n% fprintf('sweep %d, block %d, r0=%d, r1=%d, r=%d, resid=%g, MatVec=%s\\n', swp, i, r0, r1, r, resid,matvec);\n% end\n% if ((resid 1e-7 )\n% keyboard;\n% end\n %u=u(:,1:rnew); s=s(1:rnew); v=v(:,1:rnew);% v=v';\n %u=u*diag(s); %u has to be reshaped \n \n \n %Random restart block\n radd=min(kickrank,size(v,1)-rnew);\n rnew=rnew+radd;\n if ( radd > 0 )\n vr=randn(size(v,1),radd);\n ur=zeros(size(u,1),radd); \n %Orthogonalize vr to v by Golub-Kahan reorth\n mvr=v'*vr; vnew=vr-v*mvr; \n reort_flag=false;\n for j=1:radd\n if ( norm(vnew(:,j)) <= 0.5*norm(vr(:,j)))\n reort_flag=true;\n end\n end\n if (reort_flag)\n sv=v'*vnew;\n %mvr=mvr+v'*vnew; \n vnew=vnew-v*sv; \n end\n [vnew,~]=qr(vnew,0); \n \n v=[v,vnew];\n u=[u,ur];\n %norm(u*v'-u1*v1');\n %keyboard;\n %keyboard;\n end\n v=v';\n \n \n \n \n %Memory stuff\n pos=numel(cry_left);\n cry_left(pos-ry(i)*n(i)*ry(i+1)+1:pos)=[];\n cry_right(1:ry(i+1)*n(i+1)*k*ry(i+2))=[]; %Delete the top core from cry_right\n cry_right=[u(:)', v(:)',cry_right]; %Simply add new block to cry_right\n ry(i+1)=rnew;\n \n %Recalculate phi block; we need to recalculate phi{i+1} here\n %using phi{i+2} \n %px2(ra(i+2),ry(i+2),ry(i+2))*cra2(ra(i+1),n(i),m(i),ra(i+2)*v(ry(i+1),n(i+1),ry(i+2))*v(ry(i+1),n(i+1),ry(i+2))\n %we already have b2 --- (b2_save)\n %(ra(i+1),n(i+1),n(i+1),ry(i+2),ry(i+2)), convolve over the \n %n(i+1),ry(i+2)\n phx=reshape(b2_save,[ra(i+1),n(i+1),n(i+1),ry(i+2),ry(i+2)]); \n phx=permute(phx,[2,4,1,3,5]);\n %phx=permute(phx,[3,4,1,2,5]);\n %phx=permute(phx,[3,5,1,2,4]);\n % phx=permute(phx,[2,5,1,3,4]);\n phx=reshape(phx,[n(i+1)*ry(i+2),ra(i+1)*n(i+1)*ry(i+2)]);\n v0=v;\n v0=reshape(v0,[ry(i+1),n(i+1)*ry(i+2)]);\n phx=v0*phx;\n phx=reshape(phx,[ry(i+1),ra(i+1),n(i+1),ry(i+2)]);\n phx=permute(phx,[3,4,1,2]); \n phx=reshape(phx,[n(i+1)*ry(i+2),ry(i+1)*ra(i+1)]);\n phx=v0*phx;\n phx=reshape(phx,[ry(i+1),ry(i+1),ra(i+1)]);\n %phx=permute(phx,[3,2,1]); \n phx=permute(phx,[3,2,1]);\n phi{i+1}=phx; \n else %Implant the auxiliary core from the left block to the right block\n \n %Prepare the truncation block\n rhs=wnew*diag(ev); \n if (strcmp(matvec,'full'))\n res_true = norm(fm*wnew-rhs)/norm(rhs);\n else\n res_true = norm(bfun(mm,wnew)-rhs)/norm(rhs);\n end; \n wnew=reshape(wnew,[ry(i),n(i),n(i+1),ry(i+2),k]); \n wnew=permute(wnew,[1,2,3,5,4]); wnew=reshape(wnew,[ry(i)*n(i),n(i+1)*k*ry(i+2)]);\n [u,s,v]=svd(wnew,'econ'); s=diag(s);\n rnew=my_chop2(s,local_eps*norm(s)); \n \n %%%%\n rnew = min(rnew, rmax);\n rnew = min(rnew, numel(s));\n %%%%\n \n u=u(:,1:rnew); s=s(1:rnew); v=v(:,1:rnew);% v=v';\n v=v*diag(s); %u has to be reshaped \n \n \n % Residual truncation\n% r0=1; r1=min(size(s,1),rmax);\n% r=1; \n% while ( (r ~= r0 || r ~= r1) && r0 <= r1)\n% r=min(floor((r0+r1)/2),rmax);\n% %er0=norm(s(r+1:numel(s)));\n% v1=v(:,1:r)*diag(s(1:r)); \n% %Sonate v1\n% v1=reshape(v1,[n(i+1),k,ry(i+2),r]);\n% v1=permute(v1,[1,3,4,2]);\n% v1=reshape(v1,[numel(v1)/k,k]);\n% [u2,~,v2]=svd(v1,'econ');\n% v1=u2*v2';\n% v1=reshape(v1,[n(i+1),ry(i+2),r,k]);\n% v1=permute(v1,[1,4,2,3]);\n% v1=reshape(v1,[numel(v1)/r,r]);\n% sol=u(:,1:r)*v1';\n% sol = reshape(sol,[ry(i),n(i),n(i+1),k,ry(i+2)]);\n% sol=permute(sol,[1,2,3,5,4]); sol=reshape(sol,[numel(sol)/k,k]);\n% if (strcmp(matvec,'full'))\n% resid = norm(fm*sol-rhs)/norm(rhs);\n% else\n% resid = norm(bfun(mm,sol)-rhs)/norm(rhs);\n% end;\n% if ( verb )\n% fprintf('sweep %d, block %d, r0=%d r1=%d r=%d, resid=%g, MatVec=%s\\n', swp, i, r0, r1, r, resid,matvec);\n% end\n% if ((resid 0 )\n vr=zeros(size(v,1),radd);\n ur=randn(size(u,1),radd); \n %Orthogonalize vr to v by Golub-Kahan reorth\n mur=u'*ur; unew=ur-u*mur; \n reort_flag=false;\n for j=1:radd\n if ( norm(unew(:,j)) <= 0.5*norm(ur(:,j)))\n reort_flag=true;\n end\n end\n if (reort_flag)\n sv=u'*unew;\n %mvr=mvr+v'*vnew; \n unew=unew-u*sv; \n end\n [unew,~]=qr(unew,0); \n \n u=[u,unew];\n v=[v,vr];\n end\n v=v';\n \n \n \n cry_right(1:ry(i+1)*n(i+1)*ry(i+2))=[];\n pos=numel(cry_left);\n cry_left(pos-ry(i)*n(i)*k*ry(i+1)+1:pos)=[];\n cry_left=[cry_left,u(:)',v(:)'];\n \n \n \n \n \n \n \n ry(i+1)=rnew;\n \n \n \n \n %Recalculate phi block; we need to recalculate phi{i+1} using\n %phi{i}\n phx=reshape(b1_save,[ry(i),ry(i),n(i),n(i),ra(i+1)]);\n u0=u; u0=reshape(u0,[ry(i)*n(i),ry(i+1)]);\n phx=permute(phx,[1,3,5,2,4]); \n %phx=permute(phx,[2,4,5,1,3]); \n %phx=permute(phx,[1,4,5,2,3]);\n %phx=permute(phx,[2,3,5,1,4]);\n phx=reshape(phx,[ry(i)*n(i)*ra(i+1),ry(i)*n(i)]);\n phx=phx*u0; \n phx=reshape(phx,[ry(i),n(i),ra(i+1),ry(i+1)]);\n phx=permute(phx,[3,4,1,2]); \n phx=reshape(phx,[ra(i+1)*ry(i+1),ry(i)*n(i)]);\n phx=phx*u0; phx=reshape(phx,[ra(i+1),ry(i+1),ry(i+1)]);\n phx=permute(phx,[1,2,3]);\n phi{i+1}=phx;\n end\n \n err_max = max(err_max, dx);\n %Choose the next direction block; now implement the simple case\n if ( strcmp(dir,'rl') )\n if ( i > 1 )\n i=i-1;\n else %Change direction %The last optimization was for (1,2) core \n dir='lr';\n %One block should go from cry_right to cry_left\n cry_left=cry_right(1:ry(1)*n(1)*ry(2)*k); %This seems correct\n cry_right(1:ry(1)*n(1)*ry(2)*k)=[];\n if (verb>0)\n fprintf('--- sweep=%d, err_max=%3.3e \\n',swp, err_max);\n end;\n swp=swp+1;\n not_converged = (err_max>eps);\n err_max = 0;\n end\n else\n if ( i < d-1 )\n i=i+1;\n else\n dir='rl';\n pos=numel(cry_left);\n cry_right=cry_left(pos-ry(d)*n(d)*ry(d+1)*k+1:pos); \n cry_left(pos-ry(d)*n(d)*ry(d+1)*k+1:pos)=[];\n if (verb>0)\n fprintf('--- sweep=%d, err_max=%3.3e \\n',swp, err_max);\n end; \n swp=swp+1;\n not_converged = (err_max>eps);\n err_max = 0; \n %One block should go from cry_left to cry_right (?) --- seems no :)\n end\n end\n \n\nend\n %Gather the solution \n \n ry(d+1)=k; %This is the final\n y.r=ry;\n cry=[cry_left,cry_right];\n y.core=cry;\n y.r=ry; \n y.d=d;\n y.ps=cumsum([1;n.*ry(1:d).*ry(2:d+1)]);\nend\n\n function [x]=bfun(a,x)\n %[Y]=BFUN(A,X,K)\n %a is given as U(i1,j1,s)*V(i2,j2,s)\n %\\sum_{j1,j2,s} U(i1,j1,s)*V(i2,j2,s)*X(j1,j2,q)\n re=size(x,2);\n ul=a{1}; vl=a{2};\n n1=size(ul,1);m1=size(ul,2); ral=size(ul,3);\n n2=size(vl,1); m2=size(vl,2);\n ul=permute(ul,[1,3,2]); ul=reshape(ul,[numel(ul)/m1,m1]);\n x=reshape(x,[m1,numel(x)/m1]);\n x=ul*x; %x is i1xsxj2xq s,j2\n x=reshape(x,[n1,ral,m2,re]);\n x=permute(x,[3,2,1,4]); \n x=reshape(x,[m2*ral,n1*re]);\n vl=reshape(vl,[n2,m2*ral]); \n x=vl*x; %is n2*n1*k\n x=reshape(x,[n2,n1,re]); \n x=permute(x,[2,1,3]); \n x=reshape(x,[numel(x)/re,re]);\n return\n end\n\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/misc/old_dmrg_eigb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3700198122393344}} {"text": "function [optimState,t_func] = initdesign_vbmc(optimState,Ns,funwrapper,t_func,options)\n%INITDESIGN_VBMC Initial sample design (provided or random box).\n\nx0 = optimState.Cache.X_orig;\n[N0,D] = size(x0);\n\nif N0 <= Ns\n Xs = x0;\n ys = optimState.Cache.y_orig;\n if N0 < Ns\n switch lower(options.InitDesign)\n case 'plausible'\n % Uniform random samples in the plausible box (in transformed space)\n Xrnd = bsxfun(@plus,bsxfun(@times,rand(Ns-N0,D),optimState.PUB-optimState.PLB),optimState.PLB);\n case 'narrow'\n xstart = warpvars_vbmc(x0(1,:),'dir',optimState.trinfo);\n Xrnd = bsxfun(@plus,bsxfun(@times,rand(Ns-N0,D)-0.5,0.1*(optimState.PUB-optimState.PLB)),xstart);\n Xrnd = bsxfun(@min,bsxfun(@max,Xrnd,optimState.PLB),optimState.PUB);\n otherwise\n error('Unknown initial design for VBMC.');\n end\n Xrnd = warpvars_vbmc(Xrnd,'inv',optimState.trinfo); % Convert back to original space\n Xs = [Xs; Xrnd];\n ys = [ys; NaN(Ns-N0,1)];\n end\n idx_remove = true(N0,1);\n\nelseif N0 > Ns\n % Cluster starting points\n kmeans_options = struct('Display','off','Method',2,'Preprocessing','whiten');\n idx = fastkmeans(x0,Ns,kmeans_options);\n\n % From each cluster, take points with higher density in original space\n Xs = NaN(Ns,D); ys = NaN(Ns,1); idx_remove = false(N0,1);\n for iK = 1:Ns\n idxK = find(idx == iK);\n xx = optimState.Cache.X_orig(idxK,:);\n yy = optimState.Cache.y_orig(idxK);\n [~,idx_y] = max(yy);\n Xs(iK,:) = xx(idx_y,:);\n ys(iK) = yy(idx_y); \n idx_remove(idxK(idx_y)) = true;\n end\nend\n% Remove points from starting cache\noptimState.Cache.X_orig(idx_remove,:) = [];\noptimState.Cache.y_orig(idx_remove) = [];\n\nXs = warpvars_vbmc(Xs,'d',optimState.trinfo);\n\nfor is = 1:Ns\n timer_func = tic;\n if isnan(ys(is)) % Function value is not available\n [~,optimState] = funlogger_vbmc(funwrapper,Xs(is,:),optimState,'iter');\n else\n [~,optimState] = funlogger_vbmc(funwrapper,Xs(is,:),optimState,'add',ys(is));\n end\n t_func = t_func + toc(timer_func);\nend\n\nend\n", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/misc/initdesign_vbmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36971524648927734}} {"text": "function [output_stack, IRR, ORR, ARR] = evalfisx(input_stack, fis)\n%EVALFISX Evaluation of a fuzzy inference system.\n% \n% See evalfis1 for syntax and explanation.\n% \n% It is completely based on MATLAB's evalfis1 \n% with some modifications, so it's compatible\n% with extendent fuzzy rule structure.\n% \n% Compare also code of this function\n% with code of original the evalfis1.\n% \n% Example:\n% load carsmall;\n% fis = genfis4([Weight, Displacement], Acceleration, 'mamdani');\n% out = evalfisx([2000 100; 2000 200; 2000 300], fis);\n\n% Per Konstantin A. Sidelnikov, 2009.\n\npersistent CURRENT_FIS;\npersistent FIS_NAME FIS_TYPE IN_N OUT_N IN_MF_N OUT_MF_N RULE_N;\npersistent AND_METHOD OR_METHOD IMP_METHOD AGG_METHOD DEFUZZ_METHOD;\npersistent BOUND IN_MF_TYPE OUT_MF_TYPE;\npersistent IN_RULE_LIST OUT_RULE_LIST AND_OR RULE_WEIGHT;\npersistent IN_PARAM OUT_PARAM;\npersistent OUT_TEMPLATE_MF OUT_MF QUALIFIED_OUT_MF OVERALL_OUT_MF;\n\npoint_n = 101;\nmf_para_n = 4;\n\ninitialization = 1;\n% Check if initialization necessary.\nif isequal(fis, CURRENT_FIS)\n initialization = 0;\nend\n\n% Unpack data and initialize global variables.\nif initialization\n CURRENT_FIS = fis;\n FIS_NAME = fis.name;\n FIS_TYPE = fis.type;\n IN_N = length(fis.input);\n OUT_N = length(fis.output); \n \n for i = 1 : IN_N\n IN_MF_N(i) = length(fis.input(i).mf);\n end\n for i = 1 : OUT_N\n OUT_MF_N(i) = length(fis.output(i).mf);\n end\n \n RULE_N = length(fis.rule);\n \n AND_METHOD = fis.andMethod;\n OR_METHOD = fis.orMethod;\n IMP_METHOD = fis.impMethod;\n AGG_METHOD = fis.aggMethod;\n DEFUZZ_METHOD = fis.defuzzMethod; \n \n IN_MF_TYPE = [];\n for i = 1 : IN_N\n IN_MF_TYPE = [IN_MF_TYPE; {fis.input(i).mf.type}'];\n end \n OUT_MF_TYPE = [];\n for i = 1 : OUT_N\n OUT_MF_TYPE = [OUT_MF_TYPE; {fis.output(i).mf.type}'];\n end\n \n in_bound = reshape([fis.input.range], IN_N, 2);\n out_bound = reshape([fis.output.range], OUT_N, 2);\n BOUND = [in_bound; out_bound];\n\n RULE_WEIGHT = [fis.rule.weight]';\n AND_OR = [fis.rule.connection]';\n IN_RULE_LIST = {fis.rule.antecedent}';\n OUT_RULE_LIST = reshape([fis.rule.consequent], RULE_N, OUT_N);\n\n k = 1;\n totalInputMFs = sum(IN_MF_N);\n totalOutputMFs = sum(OUT_MF_N);\n IN_PARAM = zeros(totalInputMFs, 4);\n for i = 1 : IN_N\n for j = 1 : length(fis.input(i).mf)\n tmp = fis.input(i).mf(j).params;\n IN_PARAM(k, 1 : length(tmp)) = tmp;\n k = k + 1;\n end\n end\n k = 1;\n OUT_PARAM = zeros(totalOutputMFs, 4);\n for i = 1 : OUT_N\n for j = 1 : length(fis.output(i).mf)\n tmp = fis.output(i).mf(j).params;\n OUT_PARAM(k, 1 : length(tmp)) = tmp;\n k = k + 1;\n end\n end\n \n if strcmp(FIS_TYPE, 'sugeno')\n OUT_PARAM = OUT_PARAM(:, 1 : IN_N + 1);\n elseif strcmp(FIS_TYPE, 'mamdani')\n OUT_PARAM = OUT_PARAM(:, 1 : mf_para_n);\n else\n error('Unknown FIS type!');\n end\n \n if strcmp(FIS_TYPE, 'mamdani')\n % Compute OUT_TEMPLATE_MF\n OUT_TEMPLATE_MF = zeros(sum(OUT_MF_N), point_n);\n cum_mf = cumsum(OUT_MF_N);\n for i = 1 : sum(OUT_MF_N) \n % index for output\n output_index = find((cum_mf - i) >= 0, 1, 'first');\n tmp = linspace(BOUND(IN_N + output_index, 1), ...\n BOUND(IN_N + output_index, 2), point_n);\n OUT_TEMPLATE_MF(i, :) = ...\n evalmf(tmp, OUT_PARAM(i, :), OUT_MF_TYPE{i});\n end\n \n % Reorder to fill OUT_MF, an (RULE_N X point_n * OUT_N) matrix.\n OUT_MF = zeros(RULE_N, point_n * OUT_N);\n for i = 1 : RULE_N\n for j = 1 : OUT_N\n mf_index = OUT_RULE_LIST(i, j);\n index = sum(OUT_MF_N(1 : j - 1)) + abs(mf_index);\n tmp = (j - 1) * point_n + 1 : j * point_n;\n if mf_index > 0 % regular MF\n OUT_MF(i, tmp) = OUT_TEMPLATE_MF(index, :);\n elseif mf_index < 0 % Linguistic hedge \"NOT\"\n OUT_MF(i, tmp) = 1 - OUT_TEMPLATE_MF(index, :);\n else % Don't care (MF index == 0)\n OUT_MF(i, tmp) = ones(1, point_n);\n end\n end\n end\n \n % Allocate other matrices\n QUALIFIED_OUT_MF = zeros(RULE_N, point_n * OUT_N);\n OVERALL_OUT_MF = zeros(1, point_n * OUT_N);\n end\n % fprintf('Global variables for %s FIS are initialized\\n', FIS_NAME);\nend\n% End of initialization\n\n% Error checking for input stack\nm = size(input_stack, 1);\nn = size(input_stack, 2);\nif ~((n == IN_N) || ((n == 1) && (m == IN_N)))\n fprintf('The input stack is of size %dx%d,', m, n);\n fprintf('while expected input vector size is %d.\\n', IN_N);\n error('Exiting ...');\nend\nif (n == 1) && (m == IN_N)\n data_n = 1;\n input_stack = input_stack';\nelse\n data_n = m;\nend\n\n% Allocate output stack\noutput_stack = zeros(data_n, OUT_N);\n\n% Iteration through each row of input stack\nfor kkk = 1 : data_n\n input = input_stack(kkk, :);\n \n % Find in_template_mf_value\n in_template_mf_value = zeros(sum(IN_MF_N), 1);\n cum_mf = cumsum(IN_MF_N);\n for i = 1 : sum(IN_MF_N)\n input_index = find((cum_mf - i) >= 0, 1, 'first');\n in_template_mf_value(i) = ...\n evalmf(input(input_index), IN_PARAM(i, :), IN_MF_TYPE{i});\n end\n \n % Reordering to fill in_mf_value, which is an (RULE_N X 1) cell matrix.\n tmp = cumsum([0, IN_MF_N(1 : IN_N - 1)]);\n in_mf_value = cell(RULE_N, 1);\n for ind = 1 : RULE_N\n index = tmp(IN_RULE_LIST{ind}(1, :)) + abs(IN_RULE_LIST{ind}(2, :));\n in_mf_value{ind} = in_template_mf_value(index)';\n % Take care of linguistic hedge NOT (MF index is negative)\n neg_index = find(IN_RULE_LIST{ind}(2, :) < 0);\n in_mf_value{ind}(neg_index) = 1 - in_mf_value{ind}(neg_index);\n end \n \n % Find the firing strengths\n % AND_METHOD = 'min' or 'prod'; which is used as function name too\n % OR_METHOD = 'max' or 'probor'; which is used as function name too\n firing_strength = zeros(RULE_N, 1);\n and_index = find(AND_OR == 1);\n or_index = find(AND_OR == 2);\n if IN_N ~= 1 \n firing_strength(and_index) = ...\n cellfun(@(x) feval(AND_METHOD, x'), in_mf_value(and_index, :))';\n firing_strength(or_index) = ...\n cellfun(@(x) feval(OR_METHOD, x'), in_mf_value(or_index, :))';\n else\n firing_strength = [in_mf_value{:}]';\n end\n \n % Recalculate firing strengths scaled by rule weights\n firing_strength = firing_strength .* RULE_WEIGHT;\n \n % Find output\n if strcmp(FIS_TYPE, 'sugeno')\n template_output = OUT_PARAM * [input(:); 1]; % Output for template\n \n % Reordering according to the output part of RULE_LIST;\n % Negative MF index will becomes positive\n tmp = cumsum([0, OUT_MF_N(1 : OUT_N - 1)]);\n index = repmat(tmp, RULE_N, 1) + abs(OUT_RULE_LIST);\n index(index == 0) = 1; % temp. setting for easy indexing\n rule_output = template_output(index);\n rule_output(OUT_RULE_LIST == 0) = 0; % take care of zero index\n sum_firing_strength = sum(firing_strength); \n \n if sum_firing_strength == 0\n fprintf('input = [');\n for i = 1 : IN_N\n fprintf('%f ', input(i));\n end\n fprintf(']\\n');\n error('Total firing strength is zero!');\n end \n \n switch DEFUZZ_METHOD\n case 'wtaver'\n output_stack(kkk, :) = firing_strength' * rule_output / ...\n sum_firing_strength;\n case 'wtsum'\n output_stack(kkk, :) = firing_strength' * rule_output;\n otherwise\n error('Unknown defuzzification method!');\n end \n elseif strcmp(FIS_TYPE, 'mamdani')\n % Transform OUT_MF to QUALIFIED_OUT_MF\n % Duplicate firing_strength.\n tmp = firing_strength(:, ones(1, point_n * OUT_N));\n \n if strcmp(IMP_METHOD, 'prod') % IMP_METHOD == 'prod'\n QUALIFIED_OUT_MF = tmp .* OUT_MF;\n elseif strcmp(IMP_METHOD, 'min') % IMP_METHOD == 'min'\n QUALIFIED_OUT_MF = feval(IMP_METHOD, tmp, OUT_MF);\n else % IMP_METHOD is user-defined\n tmp1 = feval(IMP_METHOD, [tmp(:)'; OUT_MF(:)']);\n QUALIFIED_OUT_MF = reshape(tmp1, RULE_N, point_n * OUT_N);\n end\n \n % AGG_METHOD = 'sum' or 'max' or 'probor' or user-defined\n OVERALL_OUT_MF = feval(AGG_METHOD, QUALIFIED_OUT_MF);\n \n for i = 1 : OUT_N\n tmp = linspace(BOUND(IN_N + i, 1), BOUND(IN_N + i, 2), point_n);\n tmp1 = (i - 1) * point_n + 1 : i * point_n;\n output_stack(kkk, i) = ...\n defuzz(tmp, OVERALL_OUT_MF(1, tmp1), DEFUZZ_METHOD);\n end\n else\n fprintf('fis_type = %d\\n', FIS_TYPE);\n error('Unknown FIS type!');\n end\nend\n\nif nargout >= 2\n IRR = in_mf_value; \nend\n\nif strcmp(FIS_TYPE, 'sugeno')\n if nargout >= 3\n ORR = rule_output;\n end\n if nargout >= 4\n ARR = firing_strength(:, ones(1, OUT_N));\n end\nelse\n if nargout >= 3\n ORR = [];\n for iii = 1 : OUT_N\n tmp = (iii - 1) * point_n + 1 : iii * point_n;\n ORR = [ORR; QUALIFIED_OUT_MF(:, tmp)];\n end\n ORR = ORR';\n end\n if nargout >= 4\n ARR = reshape(OVERALL_OUT_MF, point_n, OUT_N);\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/28393-fuzzy-cart/fcart/evalfisx1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3697152464892773}} {"text": "function relaxMtFit(dataDir,outDir,voxRange)\n%\n% relaxMtFit(dataDir,outDir,voxRange)\n%\n% Calculates the k and f maps using the MT TOF sequence.\n%\n% See Yarnykh & Yuan (2004). Cross-relaxation imaging reveals\n% detailed anatomy of white matter fiber tracts in the human\n% brain. Neuroimage, 23(1):409-24. (PMID: 15325389)\n%\n% KEY DEPENDENCIES:\n% lorentzian.m, relaxMtFitFunc.m\n%\n% SEE ALSO:\n% relaxPreprocess.m to get raw DICOM data into the right format for\n% this function.\n%\n% HISTORY:\n% 2006.02.19 Nikola Stikov wrote it.\n% 2007.01.?? NS recoded it to use lsqnonlin\n% 2007.02.27 RFD rewrote the loop structure and data format.\n% 2007.03.02 RFD slight performance enhancements. Also renamed\n% several functions and added them all to the mrDiffusion\n% repository.\n%\n\nif(~exist('dataDir','var')|isempty(dataDir))\n dataDir = pwd;\nend\n\nif(~exist('outDir','var')|isempty(outDir))\n outDir = dataDir;\nend\n\nif(~exist('voxRange','var')|isempty(voxRange))\n voxRange = '';\nend\n\nif(~exist(outDir,'dir'))\n mkdir(outDir);\nend\n\ndisp(['Loading data from ' dataDir '...']);\n\nni = niftiRead(fullfile(dataDir,'T1.nii.gz'));\nT1 = ni.data;\nxform = ni.qto_xyz;\nclear ni;\nnz = T1>0;\n\nif(exist(fullfile(dataDir,'brainMask.nii.gz'),'file'))\n ni = niftiRead(fullfile(dataDir,'brainMask.nii.gz'));\n brainMask = ni.data==1;\n clear ni;\nelse\n brainMask = nz;\nend\n\n%ni = niftiRead(fullfile(dataDir,'PD.nii.gz'));\n%PD = ni.data;\n\nni = niftiRead(fullfile(dataDir,'S0.nii.gz'));\nS0 = ni.data;\nclear ni;\n\nd = dir(fullfile(dataDir,'MT_*.nii.gz'));\ndelta = zeros(1,length(d));\nfor(ii=1:length(d))\n ni = niftiRead(fullfile(dataDir,d(ii).name));\n MT(:,:,:,ii) = ni.data;\n clear ni;\n % TODO: fix this crude hack. Maybe store offset freqs in nifti header?\n delta(ii) = sscanf(d(ii).name,'MT_%dkHz.nii.gz') ;\nend\ndelta = delta'*1e3; % offset frequencies, in Hz\n\niterMax = 50; %maximum number of iterations allowed\n\nsz = size(brainMask);\n\n% Clip T1 and PD to reasonable values\n% Tissue T1 (s) T2 (ms) PD*\n% CSF 0.8 - 20 110 - 2000 70 - 230\n% White\t 0.76 - 1.08 61 - 100 \t 70 - 90\n% Gray 1.09 - 2.15 61 - 109 85 - 125\n% Meninges 0.5 - 2.2 50 - 165 5 - 44\n% Muscle 0.95 - 1.82 20 - 67 45 - 90\n% Adipose 0.2 - 0.75 53 - 94 50 - 100\n% (PD values are based on PD=111 for 12mM aqueous NiCl2)\n% (From http://www.cis.rit.edu/htbooks/mri/chap-8/chap-8.htm#8.7 )\n% Our PDs seem to be scaled by 50 or so???\nT1(T1<0.01) = 0.01;\nT1(T1>10) = 10;\n%PD(PD<0) = 0;\n%PD(PD>12000) = 12000;\n\nR1 = zeros(size(T1)); R1(nz) = 1./T1(nz);\n%if(~exist(fullfile(dataDir,'R1.nii.gz'),'file'))\n% dtiWriteNiftiWrapper(single(R1),xform,fullfile(dataDir,'R1.nii.gz'));\n%end\n\n% Tidy-up the brain mask a bit\n%brainMask(PD<1000|PD>10000|T1<0.2|T1>2|S0<20) = 0;\nbrainMask(T1<0.2|T1>2|any(MT==0,4)) = 0;\n\n% RFD: empirically, [1 .08] is the median for brain tissue\nx0 = [1 .08];\n%x0 = [2.4, .10]'; %this is our initial guess, bese [3.4, .15]'\n\nlb = [.1 .03]; % [k f]\nub = [5 .28];\n\nt_m = 8e-3; %bese 8e-3\nt_s = 5e-3; %bese 5e-3\nt_r = 19e-3; %bese 19e-3\nT2_B = 11e-6;\n% Where does this come from? Should we estimate it from the data?\nw1rms = 2400; % omega-1 RMS\n\nfor ii = 1:length(delta)\n W_B(ii) = pi*(w1rms^2)*lorentzian (delta(ii), T2_B);\nend;\n\noptions = optimset('LevenbergMarquardt','on', 'Display', 'off');\n\n% FOR DEBUGGING:\n%showMontage(brainMask);\n\nbrainInds = find(brainMask);\nnumVoxelsPerUpdate = 10000;\nnVoxAll = length(brainInds);\nfor(ii=1:size(MT,4))\n tmpVol = MT(:,:,:,ii);\n tmpMT(ii,:) = tmpVol(brainInds);\nend\nclear tmpVol;\nMT = tmpMT;\nclear tmpMT;\nR1 = R1(brainInds);\nS0 = S0(brainInds);\n\nf = zeros(1,nVoxAll); \nk = zeros(1,nVoxAll);\ngof = zeros(1,nVoxAll);\ntotalSecs = 0;\nif(~isempty(voxRange))\n if(any(voxRange<0))\n\tdoVox = [floor(nVoxAll*voxRange(1))+1:ceil(nVoxAll*voxRange(2))];\n else\n\tdoVox = [max(1,voxRange(1)):min(nVoxAll,voxRange(2))];\n end\n fprintf('Processing voxels %d - %d...\\n', doVox(1), doVox(end));\nelse\n doVox = [1:nVoxAll];\n fprintf('Processing all %d voxels...\\n',nVoxAll);\nend\n\n% What we compute here is actually W_F./R1_F. R1_F is computed in\n% the fit function, but we precompute the rest out here to save a\n% few cpu cycles in the loop below.\nW_F = (w1rms./(2*pi*delta)).^2/.055;\n\nwarning off;\nnVox = doVox(end)-doVox(1);\ntmp = zeros(size(brainMask));\ntmpName = tempname\ntic;\nfor(ii=doVox)\n if(mod(ii,numVoxelsPerUpdate)==0)\n prevSecs = toc;\n totalSecs = totalSecs+prevSecs;\n secsPerVox = totalSecs./(ii-doVox(1));\n estTime = secsPerVox*(doVox(end)-ii);\n if(estTime>5400) estTime=estTime./3600; estTimeUnits='hours';\n elseif(estTime>90) estTime=estTime./60; estTimeUnits='minutes';\n else estTimeUnits='seconds'; end\n fprintf('Processed %d of %d voxels- %0.1f %s remaining (%0.3f secs per vox)...\\n',ii-doVox(1),nVox,estTime,estTimeUnits,secsPerVox);\n\ttmp(brainInds) = f;\n m = makeMontage(tmp,[1:5:size(tmp,3)]);\n\tm = uint8(round(m./max(f).*255));\n\timwrite(m,['/home/bob/public_html/f.png']);\n\tsave(tmpName,'k','f','gof','voxRange','xform');\n tic;\n end\n \n % Some voxels produce a \"Input to EIG must not contain NaN\n % or Inf\" error in lsqnonl in. Tweaking the bounds or\n % starting estimate can fix it sometimes, but they are\n % probably junk voxels anyway, so we'll catch and skip them.\n try\n %[x, resnorm, residual, exitflag, output] = lsqnonlin(@(x) relaxMtFitFunc(x, MT(:,ii), W_B, W_F, T2_B, R1(ii), S0(ii), t_m, t_s, t_r), x0, lb, ub, options); %bese j-12;\n [x, resnorm, exitflag] = fminsearch(@(x) relaxMtFitFuncLs(x, MT(:,ii), W_B, W_F, T2_B, R1(ii), S0(ii), t_m, t_s, t_r), x0, options);\n if(exitflag>0)\n k(ii) = x(1);\n f(ii) = x(2);\n gof(ii) = resnorm;\n else\n gof(ii) = NaN;\n end\n catch\n % Leave the fit values at zero.\n end\nend\nwarning on;\n\nfprintf('Finished processing %d slices (%d voxels) in %0.1f seconds.\\n\\n',sz(3),nVox,totalSecs);\n\nif(isempty(voxRange))\n outName = '';\nelse\n outName = sprintf('%0.2f-%0.2f',voxRange(1),voxRange(2));\nend\nim=zeros(size(brainMask)); im(brainInds) = f; f = im;\nim=zeros(size(brainMask)); im(brainInds) = k; k = im;\nim=zeros(size(brainMask)); im(brainInds) = gof; gof = im;\ntry\n dtiWriteNiftiWrapper(single(f),xform,fullfile(outDir,[outName 'f.nii.gz']));\n dtiWriteNiftiWrapper(single(k),xform,fullfile(outDir,[outName 'k.nii.gz']));\n dtiWriteNiftiWrapper(single(gof),xform,fullfile(outDir,[outName 'gof.nii.gz']));\ncatch\n outName = tempname\n save(outName,'k','f','gof','voxRange','xform');\nend\n% FOR DEBUGGING:\nkeyboard;\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrQuant/relaxometry/relaxMtFit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3697152464892773}} {"text": "%kkhypot 'Output = sqrt[(Input 1)**2 + (Input 2 or Constant)**2]'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros khypot.pane file\n%\n% Parameters: \n% InputFile: i1 'Input 1', required: 'First input data object'\n% OutputFile: o 'Output', required: 'Resulting output data object'\n% InputFile: i2 'Input 2', optional: 'Second input data object'\n%\n% Example: o = kkhypot({i1, i2}, {'i1','';'o','';'i2',''})\n%\n% Khoros helpfile follows below:\n%\n% PROGRAM\n% khypot - Output = sqrt[(Input 1)**2 + (Input 2 or Constant)**2]\n%\n% DESCRIPTION\n% The \"Hypotenuse\" operator returns the square root of the result \n% produced by adding the square of each point in \\fBInput 1\" and the square\n% of either the corresponding point in \\fBInput 2\" or the \\fBConstant\\fP \n% value, which ever is specified by the user.\n% \n% Executing \"Hypotenuse\" runs the program \\fIkarith2\\fP with the -hypot flag.\n% \n% \"Data Type - Single Input\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/value_type_1input\n% \n% \"Data Type - Two Input Objects\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/value_type_2input\n% \n% \"Map Data - Single Input\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/map_1input\n% \n% \"Map Data - Two Input Objects\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/map_2input\n% \n% \"Validity Mask\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/mask_2input\n% \n% \"Input Objects of Different Sizes\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/resize_2input\n% The values used to pad the data when input files are not the same size are\n% (0.0, 0.0).\n% \n% \"Explicit Location and Time Data - Single Input\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_1input\n% \n% \"Explicit Location and Time Data - Two Input Objects\" 5\n% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_2input\n% \n% \"Failure Modes - Single Input\"\n% .cI $DATAMANIP/repos/shared/man/sections/fail_1input\n% \n% \"Failure Modes - Two Input Objects\"\n% .cI $DATAMANIP/repos/shared/man/sections/fail_2input\n%\n% \n%\n% EXAMPLES\n%\n% \"SEE ALSO\"\n% DATAMANIP::karith2, DATAMANIP::kcmplx2real, DATAMANIP::kmag\n%\n% RESTRICTIONS \n% Operations on complex data are not supported at this time. If the\n% input object is complex, only the real component of the data is\n% processed, and the output object is real. To calculate the hypotenuse,\n% or magnitude of a complex number, use DATAMANIP::kcmplx2real.\n%\n% REFERENCES \n%\n% COPYRIGHT\n% Copyright (C) 1993 - 1997, Khoral Research, Inc. (\"KRI\") All rights reserved.\n% \n\n\nfunction varargout = kkhypot(varargin)\nif nargin ==0\n Inputs={};arglist={'',''};\nelseif nargin ==1\n Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kkhypot(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i1', '__input';'o', '__output';'i2', '__input'};\nmaxval={0,0,1};\nminval={0,0,1};\nistoggle=[0,0,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','OutputFile','InputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=1; nextinput=1; nextoutput=1;\n for ii=1:size(arglist,1)\n wasmatched=0;\n for jj=1:size(narglist,1)\n if strcmp(arglist{ii,1},narglist{jj,1}) % a given argument was matched to the possible arguments\n wasmatched = 1;\n was_set(jj) = 1;\n if strcmp(narglist{jj,2}, '__input')\n if (nextinput > length(Inputs)) \n error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n end\n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n elseif strcmp(narglist{jj,2}, '__output')\n if (nextoutput > nargout) \n error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n end\n if (isempty(arglist{ii,2}))\n narglist{jj,2} = 'OK_out';\n else\n narglist{jj,2} = arglist{ii,2};\n end\n\n nextoutput = nextoutput + 1;\n if (minval{jj} == 0) \n NumReqOutputs = NumReqOutputs - 1;\n end\n elseif isstr(arglist{ii,2})\n narglist{jj,2} = arglist{ii,2};\n else\n if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n end\n if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n end\n end\n end\n if ~strcmp(narglist{jj,2},'OK_out') & ~strcmp(narglist{jj,2},'OK_in') \n narglist{jj,2} = arglist{ii,2};\n end\n end\n end\n if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n if strcmp(paramtype{jj}, 'Toggle')\n if (narglist{jj,2} ==0)\n narglist{jj,1} = ''; \n end;\n narglist{jj,2} = ''; \n end;\n if ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n narglist{jj,1} = ''; \n narglist{jj,2} = ''; \n end;\n if strcmp(narglist{jj,2}, '__input')\n if (minval{jj} == 0) % meaning this input is required\n if (nextinput > size(Inputs)) \n error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n else\n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n end\n else % this is an optional input\n if (nextinput <= length(Inputs)) \n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n else \n narglist{jj,1} = '';\n narglist{jj,2} = '';\n end;\n end;\n else \n if strcmp(narglist{jj,2}, '__output')\n if (minval{jj} == 0) % this is a required output\n if (nextoutput > nargout & nargout > 1) \n error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n else\n narglist{jj,2} = 'OK_out';\n nextoutput = nextoutput + 1;\n NumReqOutputs = NumReqOutputs-1;\n end\n else % this is an optional output\n if (nargout - nextoutput >= NumReqOutputs) \n narglist{jj,2} = 'OK_out';\n nextoutput = nextoutput + 1;\n else \n narglist{jj,1} = '';\n narglist{jj,2} = '';\n end;\n end\n end\n end\nend\nif nargout\n varargout = cell(1,nargout);\nelse\n varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'karith2\" -hypot'],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kkhypot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.36967456386455866}} {"text": "function [L_l,R_l] = lindemannInh(L,R,fs,c_inh,dim)\n%LINDEMANNINH Signal pre-processing for Lindemann's cross-correlation\n% \n% [L_L,R_L] = IOSR.AUDITORY.LINDEMANNINH(L,R,FS) pre-processes left L and\n% right R signals for the cross-correlation function based on Lindemann's\n% precedence model [1,2]. A crucial parameter for Lindemann's model is\n% the \"operating point\", which controls the amount of inhibition. The\n% parameter is actually a function of the input related to its RMS level.\n% After half-wave rectifying and filtering the input signals L and R\n% (sampled at FS Hz) along the first non-singleton dimension, this\n% function applies a gain related to the inhibition parameter C_INH\n% (default is 0.3). The gain is identical for all rows, columns, etc.\n% Lastly, values outside of the interval [0,1] are not permitted in\n% Lindemann's model and hence these values are clipped.\n% \n% [L_L,R_L] = IOSR.AUDITORY.LINDEMANNINH(L,R,FS,C_INH) uses the specified\n% inhibition parameter C_INH. The value must be in the interval [0,1].\n% \n% [L_L,R_L] = IOSR.AUDITORY.LINDEMANNINH(L,R,FS,C_INH,DIM) pre-processes\n% L and R along the dimension DIM.\n% \n% References\n% \n% [1] Lindemann, W. (1986), Extension of a binaural cross-correlation\n% model by contralateral inhibition. I. Simulation of lateralization\n% for stationary signals, The Journal of the Acoustical Society of\n% America 80, 6, 1608-1622.\n% \n% [2] Lindemann, W. (1986), Extension of a binaural cross-correlation\n% model by contralateral inhibition. II. The law of the first wave\n% front, The Journal of the Acoustical Society of America 80, 6,\n% 1623-1630.\n% \n% Further reading\n% \n% Hummersone, C., Mason, R., Brookes, T. (2013), A comparison of\n% computational precedence models for source separation in\n% reverberant environments, The Journal of the Audio Engineering\n% Society 61, 7/8, 508-520.\n% \n% See also IOSR.AUDITORY.XCORRLINDEMANN.\n\n% Copyright 2016 University of Surrey.\n\n %% check input\n \n assert(isequal(size(L),size(R)), 'iosr:lindemannInh:invalidInputs', 'L and R arrays must be the same size')\n assert(isscalar(fs), 'iosr:lindemannInh:invalidFs', 'FS must be a scalar')\n \n % default dim\n if nargin<5\n dim = find(size(L)>1,1,'first');\n end\n \n %% process\n \n % half-wave rectify\n L_l = hwr(L);\n R_l = hwr(R);\n\n % filter\n cutofffreq=800;\n [b,a] = butter(1,cutofffreq*2/fs);\n L_l = filter(b,a,L_l,[],dim);\n R_l = filter(b,a,R_l,[],dim);\n\n % inhibition parameter\n if nargin < 4\n c_inh = .3;\n else\n assert(isscalar(c_inh) & isnumeric(c_inh), 'iosr:lindemannInh:invalidCinh', 'c_inh must be a scalar');\n assert(c_inh>=0 || c_inh<=1, 'iosr:lindemannInh:invalidX', 'c_inh must be in the interval (0,1].')\n end\n\n % gain\n c_gamma_L = calc_gamma(L,dim);\n c_gamma_R = calc_gamma(R,dim);\n c_gamma = max([c_gamma_L(:); c_gamma_R(:)]);\n\n % apply parameters\n L_l = apply_gamma(L_l,c_inh,c_gamma);\n R_l = apply_gamma(R_l,c_inh,c_gamma);\n\n % restrict range\n L_l = clip(L_l);\n R_l = clip(R_l);\n\nend\n\nfunction y = hwr(x)\n%HWR half-wave rectify\n\n y = max(x,0);\n \nend\n\nfunction gamma = calc_gamma(x,dim)\n%CALC_GAMMA calculate the gamma\n\n gamma = sqrt(2).*iosr.dsp.rms(x,dim);\n \nend\n\nfunction y = apply_gamma(x,c_inh,c_gamma)\n%APPLY_GAMMA apply gamma to achieve inhibition parameter\n\n y = (c_inh/c_gamma).*x;\n \nend\n\nfunction y = clip(x)\n%CLIP clip input data to [0,1] interval\n\n y = x;\n y(y<0) = 0;\n y(y>1) = 1;\n\nend\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/+auditory/lindemannInh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3695780252928127}} {"text": "classdef m_47_IHM19_16p_4s < MARRMoT_model\n% Class for hydrologic conceptual model: Forellenbach model\n \n% Copyright (C) 2021 Clara Brandes, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n%\n% Model reference\n% Brandes, C. (2020). Erstellung eines Konzeptionellen\n% Hochwasserabfluss-modells für das Einzugsgebiet des Forellenbachs, NP\n% Bayerischer Wald. MSc Thesis. Technische Univerisität Dresden, Germany.\n\n properties\n % model-specific attributes\n end\n methods\n \n % creator method\n function obj = m_47_IHM19_16p_4s() \n obj.numStores = 4; % number of model stores\n obj.numFluxes = 18; % number of model fluxes\n obj.numParams = 16;\n \n obj.JacobPattern = [1,0,0,0;\n 1,1,0,0;\n 1,1,1,0;\n 0,1,1,1]; % Jacobian matrix of model store ODEs\n \n obj.parRanges = [ 2, 5; % 01 SIMAX, maximum interception storage [mm]\n 0.9, 1; % 02 A, splitting coeffcient for excess precipitation [-]\n 0.4, 0.95; % 03 FF, forest fraction [-]\n 0.05, 5; % 04 SMPMAX, maximum storage macropores [mm]\n 0, 1; % 05 CQMP, runoff time parameter (fast/slow runnoff) first soil layer [1/d]\n 1, 5; % 06 XQMP, runoff scale parameter first soil layer [-] \n 400, 600; % 07 SS1MAX, maximum soil moisture storage first soil layer [mm]\n 0.3, 0.7; % 08 FCCS1, field capacity as fraction of maximum storage first soil layer [-]\n 0, 1000; % 09 CFS1, maximum infiltration rate first soil layer [mm/d]\n 0, 15; % 10 XFS1, infiltration loss exponent first soil layer [-]\n 0, 1; % 11 CQS1, runoff time parameter for (fast/slow runnoff) first soil layer [1/d]\n 1, 5; % 12 XQS1, runoff scale parameter first soil layer [-]\n 300, 500; % 13 SS2MAX, maximum soil moisture storage second soil layer [mm]\n 0, 1; % 14 CQS2, runoff time parameter for (fast/slow runnoff) second soil layer [1/d]\n 1, 5; % 15 XQS2, runoff scale parameter second soil layer [-]\n 0.01, 5]; % 16 D, Flow delay before surface runoff [d]\n \n obj.StoreNames = {\"S1\", \"S2\" \"S3\" \"S4\"}; % Names for the stores\n obj.FluxNames = {\"ei\", \"pex\", \"pexmp\", \"pexs1\", \"fmp\",...\n \"qexmp\", \"qmp\", \"pqexsl\", \"fs1\", \"etas1\",...\n \"qs1\", \"q0\", \"q0r\", \"qmps1\", \"pc\",...\n \"qh\", \"qs2\", \"qgw\"}; % Names for the fluxes\n \n obj.FluxGroups.Ea = [1 10]; % Index or indices of fluxes to add to Actual ET\n obj.FluxGroups.Q = [13 16 17 18]; % Index or indices of fluxes to add to Streamflow\n obj.FluxGroups.GW = -18; % Index of GW runoff flow.\n \n end\n \n % INITialisation function\n function obj = init(obj)\n % parameters\n theta = obj.theta;\n delta_t = obj.delta_t;\n SIMAX = theta(1); % maximum interception storage [mm]\n SMPMAX = theta(4); % maximum storage macropores [mm]\n SS1MAX = theta(7); % maximum soil moisture storage first soil layer [mm]\n SS2MAX = theta(13); % maximum soil moisture storage second soil layer [mm]\n D = theta(16); % Flow delay before surface runoff [d]\n \n % initial store values\n obj.S0 = 0.8 * [SIMAX; % Initial interception storage\n SMPMAX; % Initial macropore storage \n SS1MAX; % Initial soil moisture storage 1 \n SS2MAX]; % Initial soil moisture storage 2\n \n % initialise the unit hydrographs and still-to-flow vectors \n uh_q0r = uh_4_full(D,delta_t);\n \n obj.uhs = {uh_q0r};\n end\n \n % MODEL_FUN are the model governing equations in state-space formulation\n function [dS, fluxes] = model_fun(obj, S)\n % parameters\n theta = obj.theta;\n SIMAX = theta(1); % maximum interception storage [mm]\n A = theta(2); % splitting coeffcient for excess precipitation [-]\n FF = theta(3); % forest fraction [-]\n SMPMAX = theta(4); % maximum storage macropores [mm]\n CQMP = theta(5); % runoff time parameter (fast/slow runnoff) first soil layer [1/d]\n XQMP = theta(6); % runoff scale parameter first soil layer [-]\n SS1MAX = theta(7); % maximum soil moisture storage first soil layer [mm]\n FCCS1 = theta(8); % field capacity coefficient fist soil layer [-]\n CFS1 = theta(9); % maximum infiltration rate first soil layer [-]\n XFS1 = theta(10); % infiltration loss exponent first soil layer [-]\n CQS1 = theta(11); % runoff time parameter for (fast/slow runnoff) first soil layer [1/d]\n XQS1 = theta(12); % runoff scale parameter first soil layer [-]\n SS2MAX = theta(13); % maximum soil moisture storage second soil layer [mm]\n CQS2 = theta(14); % runoff time parameter for (fast/slow runnoff) second soil layer [1/d]\n XQS2 = theta(15); % runoff scale parameter second soil layer [-]\n \n \n % delta_t\n delta_t = obj.delta_t;\n \n % unit hydrographs and still-to-flow vectors\n uhs = obj.uhs;\n uh_q0r = uhs{1};\n \n % stores\n S1 = S(1);\n S2 = S(2);\n S3 = S(3);\n S4 = S(4);\n \n % climate input\n t = obj.t; % this time step\n climate_in = obj.input_climate(t,:); % climate at this step\n P = climate_in(1);\n Ep = climate_in(2);\n T = climate_in(3);\n \n % fluxes functions\n flux_ei = evap_1(S1,Ep,delta_t);\n flux_pex = interception_1(P,S1,SIMAX);\n flux_pexmp = split_1(A,flux_pex);\n flux_pexs1 = split_2(A,flux_pex);\n flux_fmp = infiltration_3(flux_pexmp,S2,SMPMAX);\n flux_qexmp = flux_pexmp - flux_fmp;\n flux_qmp = interflow_3(CQMP,XQMP,S2,delta_t);\n flux_pqexs1 = flux_pexs1 + flux_qexmp;\n flux_fs1 = infiltration_7(CFS1,XFS1,S3,SS1MAX,flux_pqexs1);\n flux_etas1 = evap_23(FF,FCCS1,S3,SS1MAX,Ep,delta_t); \n flux_qs1 = interflow_9(S3,CQS1,FCCS1*SS1MAX,XQS1,delta_t);\n flux_q0 = flux_pqexs1 - flux_fs1;\n flux_q0r = route(flux_q0, uh_q0r);\n flux_qmps1 = flux_qmp + flux_qs1;\n flux_pc = infiltration_3(flux_qmps1,S4,SS2MAX);\n flux_qh = flux_qmps1 - flux_pc;\n flux_qs2 = interflow_3(CQS2,XQS2,S4,delta_t);\n flux_qgw = 0.0195;\n\n % stores ODEs\n dS1 = P - flux_ei - flux_pex;\n dS2 = flux_fmp - flux_qmp;\n dS3 = flux_fs1 - flux_etas1 - flux_qs1;\n dS4 = flux_pc - flux_qs2;\n \n % outputs\n dS = [dS1 dS2 dS3 dS4];\n fluxes = [flux_ei, flux_pex, flux_pexmp, flux_pexs1,...\n flux_fmp, flux_qexmp, flux_qmp, flux_pqexs1,...\n flux_fs1, flux_etas1, flux_qs1, flux_q0,...\n flux_q0r, flux_qmps1, flux_pc , flux_qh,...\n flux_qs2, flux_qgw];\n end\n \n % STEP runs at the end of every timestep.\n function obj = step(obj)\n % unit hydrographs and still-to-flow vectors\n uhs = obj.uhs;\n uh_q0r = uhs{1};\n \n % input fluxes to the unit hydrographs\n fluxes = obj.fluxes(obj.t,:);\n flux_q0 = fluxes(12);\n \n % update still-to-flow vectors using fluxes at current step and\n % unit hydrographs\n uh_q0r = update_uh(uh_q0r, flux_q0);\n obj.uhs = {uh_q0r};\n end\n end\nend", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Model files/m_47_IHM19_16p_4s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.36915067398517715}} {"text": "% NMFLAB for Signal Processing written by A. Cichocki and R. Zdunek \n% in cooperation with other members of Laboratory for Advanced Brain Signal\n% Processing, BSI, RIKEN, Saitama, JAPAN\n\nfunction [A,X,Distance_output]=nmf_smart_alg(Y,r,Index_norm,A_true,S, mc_on, NoAlts,restart_mc_on,AL,Y_true,type_alg_A,type_alg_X, max_restart,no_iter, alpha, alpha_BE, omegaX, omegaA, alphaS)\n%\n%\n% Non-negative Matrix Factorization (NMF) with Extended SMART algorithms \n%\n% [A,X]=nmf_smart_alg(Y, r, Index_norm, A_true, S, mc_on, NoAlts, restart_mc_on, AL, Y_true, type_alg_A, type_alg_X, max_restart, no_iter, \n% alpha, alpha_BE, omegaX, omegaA, alphaS)\n% returns mixing matrix A of dimension [m by r],\n% and source matrix X of dimension [r by T], for the linear mixing model: AX = Y, \n% where Y is an observation matrix [m by T]. \n% Note: > m: number of sensors,\n% > r: number of sources,\n% > T: number of samples,\n% \n% INPUTS:\n% > Index_norm: vector of 13 binary entries indicating which number\n% divergence measures are turned on in the View Options,\n%\n% > A_true: true mixing matrix (only for synthetic data),\n% > S: true source matrix (only for synthetic data), \n% > mc_on: 1 - Monte Carlo analysis enabled, 0 - otherwise, \n% > NoAlts: number of alternating steps (only for Monte Carlo\n% analysis and the option \"Fixed Alternatings\" is selected)\n% > restart_mc_on: 1 - restarts in Monte Carlo analysis are enabled,\n% 0 - otherwise, \n% > AL: mixing matrix estimaed from the preceeding layer, \n% > Y_true: the first layer mixed signals (mixtures),\n% > type_alg_A: indicates the selected algorithm for computation\n% of the mixing matrix,\n% > type_alg_X: indicates the selected algorithm for computation of the sources, \n% > no_iter: number of inner iterations, \n% > alpha: parameter \"alpha\" in the Amari alpha-divergence\n% > alpha_BE: parameter \"alpha\" in the Bose-Einstein divergence\n% > omegaX: relaxation parameter (omega) in computation of the sources, \n% > omegaA: relaxation parameter (omega) in computation of\n% the mixing matrix,\n% > alphaS: parameter of non-linear projection in computation\n% of the sources, \n% \n% OUTPUTS:\n% > A: estimated mixing matrix,\n% > X: estimated source matrix,\n% > Distance_output: structures of different divergences measured between \"Y\" and estimated \"AX\" versus iterations,\n%\n% #########################################################################\nA = [];\nX = [];\nif (nargin < 19) | isempty(alphaS) | max(size(alphaS) > 1)\n disp('Incorrect parameter alphaS');\n return\nend\nif (nargin < 18) | isempty(omegaA) | max(size(omegaA) > 1)\n disp('Incorrect parameter alpha');\n return\nend\nif (nargin < 17) | isempty(omegaX) | max(size(omegaX) > 1)\n disp('Incorrect parameter omegaX');\n return\nend\nif (nargin < 16) | isempty(alpha_BE) | max(size(alpha_BE) > 1)\n disp('Incorrect parameter alpha in the Bose_Einstein divergence');\n return\nend\nif (nargin < 15) | isempty(alpha) | max(size(alpha) > 1)\n disp('Incorrect parameter alpha');\n return\nend\nif (nargin < 14) | isempty(no_iter) | (no_iter < 1) | max(size(no_iter) > 1)\n disp('Incorrect number of inner iterations');\n return\nend\nif (nargin < 13) | isempty(max_restart) | (max_restart < 0) | max(size(max_restart) > 1)\n disp('Number of restarts must be given correctly');\n return\nend\nif (nargin < 12) | isempty(type_alg_X) | (type_alg_X < 1) | max(size(type_alg_X) > 1)\n disp('Incorrect algorithm for X');\n return\nend\nif (nargin < 11) | isempty(type_alg_A) | (type_alg_A < 1) | max(size(type_alg_A) > 1)\n disp('Incorrect algorithm for A');\n return\nend\nif (nargin < 10) | isempty(Y_true) \n disp('The first layer mixed signals are unknown');\n Y_true = zeros(size(Y_true));\nend\nif (nargin < 9) | isempty(AL) \n disp('Mixing matrix from the preceeding layer unknown');\n AL = eye(size(Y,1));\nend\nif (nargin < 8) | isempty(restart_mc_on) | max(size(restart_mc_on) > 1)\n disp('Index od restarts in MC analysis unknown');\n restart_mc_on = 0;\nend\nif (nargin < 7) | isempty(NoAlts) | max(size(NoAlts) > 1)\n disp('Adjustable number of alternatings');\n NoAlts = [];\nend\nif (nargin < 6) | isempty(mc_on) | max(size(mc_on) > 1)\n disp('No Monte Carlo Analysis');\n mc_on = 0;\nend\nif (nargin < 5) | isempty(S) \n disp('X_true not given');\nend\nif (nargin < 4) | isempty(A_true) \n disp('A_true not given');\n index_fixed_A = 1;\nelse\n index_fixed_A = 0; \nend\nif (nargin < 3) | isempty(Index_norm)\n '\"Index_norm\" must be specified'\n return\nend\nif (nargin < 2) | isempty(r)\n 'Rank of factorization must be given'\n return\nend\nif isempty(Y) | isnan(Y)\n error('No data');\n return\nend\n% test for negative values in Y\nif min(min(Y)) < 0\n disp('Some matrix entries are changed from negative to small positive');\n Y(Y< 0) = eps;\nend\nif min(sum(Y,2)) == 0\n disp('Not all entries in a row can be zero');\n return\nend\n\nif (alpha == 0) \n if (type_alg_X == 1) \n type_alg_X = 2; \n end\n if (type_alg_A == 1)\n type_alg_A = 2; \n end\nend\n\nif (type_alg_A == 12) & (size(A_true,1) ~= size(Y,1))\n disp('Multilayer technique cannot be used with A fixed');\n Distance_output = [];\n return\nend\n\n\nY = Y + eps;\n\n[m,T]=size(Y);\nniter_selected = 2000; % maximum number of iterations for the selected sample (can be adjusted)\nniter_sample = 30; % maximum number of iterations for each random sample\nepsil_normA = 1E-4; % tolerance for alternating\n\n% Monte Carlo and alternatings adjustment\nif mc_on & ~restart_mc_on\n max_restart = 0;\nend\nif ~isempty(NoAlts)\n niter_selected = NoAlts;\nend\n\n% Declaration for A and X\nA=zeros(m,r);\nAp = A;\nX=zeros(r,T);\nAinit = A;\nXinit = X;\nnr_best = -1;\nZ = zeros(m,T);\nKL_outer_temp = 0;\nnr = 0; restart_on = 0; norm_A = 10;\nm_sx = 1:m; r_sx = 1:r; T_sx = 1:T; s_dist = 0;\n\n\nwhile (nr <= max_restart)\n \n % Initialize random A and X\n if ~nr & (~mc_on | restart_mc_on) \n Ainit(m_sx',r_sx) = abs(repmat(.1*sin(2*pi*.1*m_sx'),1,r) + repmat(.1*cos(2*pi*.1*r_sx),m,1) + repmat(cos(2*pi*.471*m_sx'),1,r) + repmat(sin(2*pi*.471*r_sx),m,1));\n Ainit = Ainit/max(max(Ainit));\n \n Xinit(r_sx',T_sx) = abs(repmat(.1*sin(2*pi*.1*r_sx'),1,T) + repmat(.1*cos(2*pi*.1*T_sx),r,1) + repmat(cos(2*pi*.471*r_sx'),1,T) + repmat(sin(2*pi*.471*T_sx),r,1));\n Xinit = Xinit/max(max(Xinit));\n else\n Ainit=rand(m,r);\n Xinit=rand(r,T);\n end\n \n % Normalization of initial guess\n Ainit = Ainit*diag(1./sum(Ainit,1));\n \n if (nr == max_restart)&(max_restart > 0)\n A = A_best;\n X = X_best;\n else\n A = Ainit;\n X = Xinit;\n end % initial guess assignment\n \n Yx = zeros(m,T);\n n = 0; k = 0;\n \n \nwhile ((k <= niter_sample)&(nr < max_restart)) | ((k <= niter_selected)&(nr == max_restart)&(norm_A > epsil_normA)& isempty(NoAlts)) | ((k <= niter_selected)&(nr == max_restart)& (NoAlts > 0)) \n \nk = k + 1;\n \nif no_iter == 1\n \n switch type_alg_X\n \n case 1 % Asymmetric alpha-divergence\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = (1/alpha)*((Y./Z).^alpha - 1);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 2 % EG-DKL\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(Y./Z + eps);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 3 % EG-RAG\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(2*Y./(Z + Y) + eps);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 4 % EG-SAG\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(2*sqrt(Y.*Z)./(Z + Y) + eps) + (Y - Z)./Z ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 5 % EG-DJ\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = .5*log(Y./Z + eps) + .5*(Y - Z)./Z ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 6 % EG-RJS\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = (Y - Z)./(Y + Z) ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 7 % EG-DRJS\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = 2*log(.5*(Y + Z)./Z) + (Z - Y)./(Y + Z);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 8 % EG-SJS\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(.5*(Y + Z)./Z + eps) ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n \n case 9 % EG-Tri\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = (2*Y./(Y + Z)).^2 - 1;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 10 % EG-BE\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = alpha_BE*log((Y + alpha_BE*Z)./((1 + alpha_BE)*Z) + eps);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1 + alphaS); \n \n case 11 % Pinv\n \n X = max(1E6*eps,pinv(A)*Y); \n \n case 12 % Fixed X\n \n X = S + eps; \n niter_selected = 1000; % maximum number of iterations for the selected sample (can be adjusted) \n X = diag(sum(X,2))*X;\n \n end % switch for X\n \n switch type_alg_A\n \n case 1 % Asymmetric alpha-divergence\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = (1/alpha)*((Y./Z).^alpha - 1);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 2 % EG-DKL\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(Y./Z + eps);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 3 % EG-RAG\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(2*Y./(Z + Y) + eps);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 4 % EG-SAG\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(2*sqrt(Y.*Z)./(Z + Y) + eps) + (Y - Z)./Z ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 5 % EG-DJ\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = .5*log(Y./Z + eps) + .5*(Y - Z)./Z ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 6 % EG-RJS\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = (Y - Z)./(Y + Z) ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 7 % EG-DRJS\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = 2*log(.5*(Y + Z)./Z) + (Z - Y)./(Y + Z);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 8 % EG-SJS\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(.5*(Y + Z)./Z + eps) ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n \n case 9 % EG-Tri\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = (2*Y./(Y + Z)).^2 - 1;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 10 % EG-BE\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = alpha_BE*log((Y + alpha_BE*Z)./((1 + alpha_BE)*Z) + eps);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 11 % Pinv\n \n Ap = A; \n A = max(1E6*eps,Y*pinv(X')'); \n A = A*diag(1./sum(A,1)); \n \n case 12 % Fixed A\n \n niter_selected = 1000; % maximum number of iterations for the selected sample (can be adjusted)\n A = A_true + eps; \n A = A*diag(1./(sum(A,1) + eps));\n \n end % switch for A\n \n \nelse % no_iter\n \n\n for t = 1:no_iter\n \n switch type_alg_X\n \n case 1 % Asymmetric alpha-divergence\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = (1/alpha)*((Y./Z).^alpha - 1);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 2 % EG-DKL\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(Y./Z + eps);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 3 % EG-RAG\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(2*Y./(Z + Y) + eps);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 4 % EG-SAG\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(2*sqrt(Y.*Z)./(Z + Y) + eps) + (Y - Z)./Z ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 5 % EG-DJ\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = .5*log(Y./Z + eps) + .5*(Y - Z)./Z ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 6 % EG-RJS\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = (Y - Z)./(Y + Z) ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 7 % EG-DRJS\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = 2*log(.5*(Y + Z)./Z) + (Z - Y)./(Y + Z);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 8 % EG-SJS\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = log(.5*(Y + Z)./Z + eps) ;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 9 % EG-Tri\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = (2*Y./(Y + Z)).^2 - 1;\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 10 % EG-BE\n \n gamma_m = sum(A,1);\n Z = A*X + eps;\n Q = alpha_BE*log((Y + alpha_BE*Z)./((1 + alpha_BE)*Z) + eps);\n X = (X.*exp(diag(omegaX./gamma_m)*(A'*Q))).^(1+alphaS); \n \n case 11 % Pinv\n \n X = max(1E6*eps,pinv(A)*Y); \n \n case 12 % Fixed X\n \n X = S + eps; \n niter_selected = 1000; % maximum number of iterations for the selected sample (can be adjusted) \n X = diag(sum(X,2))*X;\n \n end % switch for X\n \n end % for t in X\n\n for t = 1:no_iter\n \n switch type_alg_A\n \n case 1 % Asymmetric alpha-divergence\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = (1/alpha)*((Y./Z).^alpha - 1);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 2 % EG-DKL\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(Y./Z + eps);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 3 % EG-RAG\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(2*Y./(Z + Y) + eps);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 4 % EG-SAG\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(2*sqrt(Y.*Z)./(Z + Y) + eps) + (Y - Z)./Z ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 5 % EG-DJ\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = .5*log(Y./Z + eps) + .5*(Y - Z)./Z ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 6 % EG-RJS\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = (Y - Z)./(Y + Z) ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 7 % EG-DRJS\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = 2*log(.5*(Y + Z)./Z) + (Z - Y)./(Y + Z);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 8 % EG-SJS\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = log(.5*(Y + Z)./Z + eps) ;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n \n case 9 % EG-Tri\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = (2*Y./(Y + Z)).^2 - 1;\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 10 % EG-BE\n \n Ap = A; \n gamma_T = (sum(X,2))';\n Z = A*X + eps;\n Q = alpha_BE*log((Y + alpha_BE*Z)./((1 + alpha_BE)*Z) + eps);\n A = A.*exp(Q*X'*diag(omegaA./gamma_T));\n A = A*diag(1./(sum(A,1) + eps)); \n \n case 11 % Pinv\n \n Ap = A; \n A = max(1E6*eps,Y*pinv(X')'); \n A = A*diag(1./sum(A,1)); \n \n case 12 % Fixed A\n \n niter_selected = 1000; % maximum number of iterations for the selected sample (can be adjusted)\n A = A_true + eps; \n A = A*diag(1./(sum(A,1) + eps)); \n \n end % switch for A \n \n end % for t in A\n \n \nend % if no_iter\n \n if (nr == max_restart)&(mod(k,50)==0)& (~mc_on | restart_mc_on)\n norm_A = norm(abs(A - Ap),'fro');\n fprintf(1, 'Restart %d, %d-th alternating step\\n',nr_best+1,k);\n end\n \n if sum(Index_norm)\n if (nr == max_restart) & (((k < 50) & (mod(k,5)==0)) | ((k>49) & ((mod(k,50)==0)))) \n \n s_dist = s_dist + 1;\n k_select(s_dist) = k;\n Z = A*X + eps;\n Z = diag(1./sqrt(var(Z')))*Z;\n \n dist_Fro(s_dist) = norm(Y - Z,'fro'); \n dist_KL(s_dist) = sum(sum(Y.*log(Y./Z + eps) - Y + Z)); \n dist_KL2(s_dist) = sum(sum(Z.*log(Z./Y + eps) + Y - Z)); \n dist_Pearson(s_dist) = sum(sum( ((Y - Z).^2)./Z ));\n dist_Hellinger(s_dist) = sum(sum( (sqrt(Z) - sqrt(Y)).^2 )); \n dist_JS_rel(s_dist) = sum(sum(2*Y.*log(2*Y./(Y + Z) + eps) + Z - Y)); \n dist_JS_rel2(s_dist) = sum(sum(2*Z.*log(2*Z./(Y + Z) + eps) - Z + Y)); \n Zy = Y + Z; \n dist_JS(s_dist) = sum(sum(Y.*log(2*Y./Zy + eps) + Z.*log(2*Z./Zy + eps) )); \n dist_AG_rel(s_dist) = sum(sum(Zy.*log(.5*Zy./Y + eps) + Y - Z)); \n dist_AG(s_dist) = sum(sum(.5*Zy.*log(.5*Zy./sqrt(Y.*Z) + eps))); \n dist_J(s_dist) = sum(sum( .5*(Y - Z).*log(Y./Z + eps) )); \n dist_Chi(s_dist) = sum(sum( ((Y + Z).*(Y - Z).^2)./(Y.*Z) )); \n dist_Tria(s_dist) = sum(sum( ((Y - Z).^2)./(Y + Z) )); \n end % if multiple\n end % if sum\n \nend % while (k)\n\n% Outer KL divergence\nZ = AL*A*X; \nZ_outer = norm(Z,'fro') + eps;\nKL_outer = sum(sum(Y_true.*log((Y_true + eps)./(Z + eps)) - Y_true + Z))/Z_outer;\n \n if (nr == 0) | (KL_outer < KL_outer_temp)\n A_best = A; X_best = X; KL_outer_temp = KL_outer; nr_best = nr;\n end % multi-conditions\n \n nr = nr + 1;\n \n if nr <=max_restart\n fprintf(1, 'Restart %d, Kullback-Leibler divergence = %e\\n',\tnr, KL_outer);\n end\n \nend % while (restarts)\n\nX(X <= 0) = eps;\n\nDistance_output = cell(length(s_dist),1);\nDistance_output(1) = {[]};\nDistance_output(2) = {[]};\nDistance_output(3) = {[]};\nDistance_output(4) = {[]};\nDistance_output(5) = {[]};\nDistance_output(6) = {[]};\nDistance_output(7) = {[]};\nDistance_output(8) = {[]};\nDistance_output(9) = {[]};\nDistance_output(10) = {[]};\nDistance_output(11) = {[]};\nDistance_output(12) = {[]};\nDistance_output(13) = {[]};\nDistance_output(14) = {[]};\n\nif sum(Index_norm)\n Distance_output(1) = {k_select}; \n Distance_output(2) = {dist_Fro};\n Distance_output(3) = {dist_KL};\n Distance_output(4) = {dist_KL2};\n Distance_output(5) = {dist_Pearson};\n Distance_output(6) = {dist_Hellinger};\n Distance_output(7) = {dist_JS_rel};\n Distance_output(8) = {dist_JS_rel2};\n Distance_output(9) = {dist_JS};\n Distance_output(10) = {dist_AG_rel};\n Distance_output(11) = {dist_AG};\n Distance_output(12) = {dist_J};\n Distance_output(13) = {dist_Chi};\n Distance_output(14) = {dist_Tria};\nend\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/nmf_smart_alg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3688463592159916}} {"text": "% -------------------------------------------------------------------------\n% Author: Jai Juneja\n% Date: 12/02/2013\n% -------------------------------------------------------------------------\nfunction World = ekfSLAM(handles, AxisDim, Lmks, Wpts, Obstacles)\n\n %%%%%%%%%%%%%%%%%%%%%%%%% INITIALISATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n cla; % Clear axes\n rob = Robot; % Create new robot object\n sen = Sensor;\n sen_rf = Sensor;\n sen_rf.noise = [0.1; 3 * pi/180];\n sen_rf.range = 10;\n sen.range = 30;\n sen.fov = 270 * pi/180;\n rob.q = [0.1;2*pi/180];\n \n [World, rob] = configuration(rob, sen_rf, Lmks, Wpts, AxisDim);\n \n Graphics = initGraphics(World, Obstacles, handles);\n \n % Determine which obstacles are moving\n numObstacles = length(Obstacles);\n numSegments = 0;\n movingObstacles = zeros(1, numObstacles);\n for i = 1:numObstacles\n if ~isequal([0; 0], Obstacles(i).velocity)\n movingObstacles(i) = 1;\n end\n numSegments = numSegments + size(Obstacles(i).vertices, 2) - 1;\n end\n movingObstacles = find(movingObstacles);\n\n %%%%%%%%%%%%%%%%%%%%%%%% TEMPORAL LOOP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % Initialise some loop variables\n pose_this_scan = [];\n this_scan_good = 0;\n big_turn = 0;\n r = World.r; % Location of robot pose in mapspace\n\n for t = 1:World.tend\n\n World.t = t;\n \n %%%%%%%%%%%%%%%%%%%%%%%%% SIMULATE WORLD %%%%%%%%%%%%%%%%%%%%%%%%%%\n R_old = rob.R;\n if ~isempty(World.Wpts)\n rob.steer(World.Wpts);\n end\n for i = movingObstacles\n Obstacles(i).move(AxisDim);\n end\n % n = rob.q .* randn(2,1); % Control noise in real world\n rob.R = rob.move(zeros(2,1), 'true'); % Move with noise\n for lid = 1:size(World.W,2)\n v = sen_rf.noise .* randn(2,1);\n World.y(:,lid) = scanPoint(rob.R, World.W(:,lid)) + v;\n end\n lmks_all = World.y;\n % Determine landmarks that are within the sensor range\n [World.y, lmks_visible] = sen_rf.constrainMeasurement(World.y);\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%% START EKF %%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n %%%%%%%%%%%%%%%%%%%%%%% EKF PREDICTION STEP %%%%%%%%%%%%%%%%%%%%%%%\n \n % 1. POSE PREDICTION USING SCAN MATCHING %%%%%%%%%%%%%%%%%%%%%%%%%%\n % TODO: if scan_matching, then do this step. Scan match only if\n % ~isempty(Obstacles)\n enough_correlations = 0;\n \n % Current stored scan is now the last scan\n last_scan_good = this_scan_good;\n pose_last_scan = pose_this_scan;\n this_scan_good = 0; % Initialise this_scan_good for this iteration\n\n % Put the previous scan's data in scan_ref\n scan_ref = World.scan_data;\n % Initialise scan data vector at maximum possible size it can take\n World.scan_data = -ones(3, numSegments * (round(sen.fov/sen.angular_res) + 1));\n scan_ndx = 1;\n for i = 1:length(Obstacles)\n scan_data = Obstacles(i).getMeasured(sen, rob);\n % Build scan_data vector\n if ~isempty(scan_data)\n World.scan_data(:, scan_ndx:scan_ndx+size(scan_data, 2)-1) = scan_data;\n scan_ndx = scan_ndx + size(scan_data, 2);\n end\n end\n % Reduce scan to only those appended in above for loop\n World.scan_data = World.scan_data(:, World.scan_data(2, :) ~= -1);\n \n % Reduce scan so that each laser angle only has one associated\n % measurement\n World.scan_data = removeDuplicateLasers(World.scan_data);\n World.scan_data = World.scan_data(2:3, :); % Remove index row\n\n % First add Gaussian white noise to scan\n v = repmat(sen.noise, 1, size(World.scan_data, 2)) .* randn(2,size(World.scan_data, 2));\n World.scan_data = World.scan_data + v;\n\n if ~isempty(World.scan_data)\n obstaclesDetected = 1;\n\n % Convert to Cartesian co-ordinates for scan matching\n World.scan_data = getInvMeasurement(World.scan_data);\n\n % If the number of point scanned exceeds the specified\n % tolerance, it is suitable for scan matching\n if size(World.scan_data, 2) > World.scan_corr_tolerance\n this_scan_good = 1;\n end\n \n % Convert to global co-ordinates for graphical display\n % World.scan_global = transToGlobal(rob.R, World.scan_data);\n else\n obstaclesDetected = 0;\n World.scan_global = [];\n end\n % If both last and current scans are good for scan matching,\n % proceed to match scans:\n if last_scan_good && this_scan_good\n n = rob.q .* randn(2,1); % Noise in odometry measurement\n \n % Do ICP scan matching using odometry input as initial guess\n [R, T, correl, icp_var] = doICP(scan_ref, World.scan_data, 1, rob.u + n);\n % If there are enough points correlated between the two\n % scans:\n if length(correl) > World.scan_corr_tolerance\n enough_correlations = 1;\n % Determine estimated pose from scan match\n r_scan = zeros(3, 1);\n da = getPiToPi(asin(R(2,1)));\n r_scan(1:2) = transToGlobal(pose_last_scan, T);\n r_scan(3) = pose_last_scan(3) + da;\n \n % Transform scan data to global co-ordinates\n scan_data_corr = World.scan_data;\n scan_data_corr = transToGlobal(r_scan, scan_data_corr);\n % Grab data points that were successfully corellated\n scan_data_corr = scan_data_corr(:, correl(:, 2)');\n\n [r_odo, R_r, R_n] = rob.move(n);\n\n % Compute covariance matrix of scan match\n C = getICPCovariance(icp_var, scan_data_corr);\n J_u = [R zeros(2, 1); 0 0 1];\n cov_scan = J_u * C * J_u';\n cov_scan_norm = trace(cov_scan);\n end\n end\n \n % 2. POSE PREDICTION USING ODOMETRY MEASUREMENTS %%%%%%%%%%%%%%%%%%\n \n % If there isn't a useful scan, just use odometry data\n if ~enough_correlations\n n = rob.q .* randn(2,1);\n [r_odo, R_r, R_n] = rob.move(n);\n cov_scan = zeros(3, 3);\n dr_scan = zeros(3, 1);\n else\n dr_scan = r_scan - rob.r;\n dr_scan(3) = getPiToPi(dr_scan(3));\n end \n\n % 3. WEIGHTAGE OF ODOMETRY AND SCAN MATCH PREDICTIONS %%%%%%%%%%%%%\n \n cov_odo = R_n * World.Q * R_n';\n cov_odo_norm = trace(cov_odo);\n \n dr_odo = r_odo - rob.r;\n dr_odo(3) = getPiToPi(dr_odo(3));\n \n dr_true = rob.R - R_old;\n\n % Check if the robot is making a large turn\n if abs(dr_scan(2)) > pi/6 || abs(dr_odo(2)) > pi/6\n big_turn = 1;\n elseif abs(dr_odo(2)) < pi/18\n big_turn = 0;\n end\n \n % Determine weights:\n % If not enough correlations, or turning is large, use odometry\n if ~enough_correlations % || big_turn\n weight_odo = 1;\n weight_scan = 0;\n else\n weight_odo = cov_scan_norm / (cov_scan_norm + cov_odo_norm);\n weight_scan = 1 - weight_odo;\n weight_scan = 1;\n weight_odo = 0;\n end\n \n % Determine robot pose using weights:\n rob.r = weight_odo * dr_odo + weight_scan * dr_scan + rob.r;\n World.x(r) = rob.r;\n\n % Covariance update\n % Caution: this method of update is suboptimal for CPU processing.\n % Alternative is to have a single equation that updates both\n % the pose and landmark covariances in a single step, but this\n % equation is rather complicated.\n P_rr = World.P(r,r);\n World.P(r,:) = R_r * World.P(r,:);\n World.P(:,r) = World.P(r,:)';\n World.P(r,r) = R_r * P_rr * R_r' + ...\n weight_scan * cov_scan + ...\n weight_odo * cov_odo;\n \n %%%%%%%%%%%%%%%%%%%%%% EKF UPDATE STEP %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % 1. CORRECT KNOWN VISIBLE LANDMARKS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % Find the visible landmarks. The below code circumvents the data\n % association problem:\n r_old = rob.r;\n \n lmks_visible_known = find(World.l(1,lmks_visible));\n lids = lmks_visible(lmks_visible_known);\n \n for lid = lids \n % Measurement prediction\n [e, E_r, E_l] = scanPoint(rob.r, World.x(World.l(:,lid)));\n\n E_rl = [E_r E_l];\n rl = [r World.l(:,lid)'];\n E = E_rl * World.P(rl,rl) * E_rl';\n\n % Actual Measurement\n yi = World.y(:,lid);\n\n % Innovation\n z = yi - e;\n z(2) = getPiToPi(z(2));\n Z = World.M + E;\n\n % Kalman gain\n K = World.P(:, rl) * E_rl' * Z^-1;\n\n % Update state and covariance\n World.x = World.x + K * z;\n World.P = World.P - K * Z * K'; % The complexity of this line is \n % very high (subtraction of two\n % large matrices)\n rob.r = World.x(r);\n end\n\n % 2. INITIALISE NEW LANDMARKS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % Check landmark availabiliy.\n % Again data association is avoided. A new landmark is initialised\n % in the storage space reserved specifically for that landmark:\n lmks_visible_unknown = find(World.l(1,lmks_visible)==0);\n lids = lmks_visible(lmks_visible_unknown);\n \n if ~isempty(lids)\n for lid = lids\n s = find(World.mapspace, 2);\n if ~isempty(s)\n World.mapspace(s) = 0;\n World.l(:,lid) = s';\n % Measurement\n yi = World.y(:,lid);\n\n [World.x(World.l(:,lid)), L_r, L_y] = invScanPoint(rob.r, yi);\n World.P(s,:) = L_r * World.P(r,:);\n World.P(:,s) = World.P(s,:)'; % Cross variance of lmk with all other lmks\n World.P(s,s) = L_r * World.P(r,r) * L_r' + L_y * World.M * L_y';\n end\n end\n end\n pose_this_scan = rob.r; % The corrected pose at which the scan was taken\n \n %%%%%%%%%%%%%%%%%%%%%%%%%% MAPPING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Determine pose correction during update step\n update = rob.r - r_old;\n\n if enough_correlations && ~isequal(rob.r, r_old)\n % Adjust latest correlated scan points to account for pose correction\n World.scan_data = transformPoints(World.scan_data, update);\n \n World = doMapping(World, sen, rob.r, World.scan_data, handles);\n elseif ~obstaclesDetected && isequal(mod(World.t, 5), 0)\n % If no obstacles have been detected, only compute map every 5\n % iterations\n World = doMapping(World, sen, rob.r, World.scan_data, handles);\n end\n \n if ~isempty(World.scan_data)\n World.scan_global = transToGlobal(rob.r, World.scan_data);\n end\n \n %%%%%%%%%%%%%%%%%%%%%%% HISTORICAL DATA COLECTION %%%%%%%%%%%%%%%%%\n World.R_hist(:, t) = rob.R(1:2);\t% True position history\n World.r_hist(:, t) = rob.r(1:2); % Estimated position history\n pose_error2 = (rob.R(1:2) - rob.r(1:2)).^2;\n World.error_hist(t) = sqrt(pose_error2(1) + pose_error2(2));\n World.Pr_hist(:, t) = [World.P(r(1),r(1)); World.P(r(2),r(2))];\n \n if enough_correlations\n scan_error = abs(dr_scan-dr_true); scan_error(3) = abs(getPiToPi(scan_error(3)));\n scan_error(1) = pdist([0 0; scan_error(1) scan_error(2)]); scan_error(2) = [];\n else\n scan_error = [0; 0];\n end\n \n odo_error = abs(dr_odo-dr_true); odo_error(3) = abs(getPiToPi(odo_error(3)));\n odo_error(1) = pdist([0 0; odo_error(1) odo_error(2)]); odo_error(2) = [];\n \n World.scan_error_hist(:, t) = scan_error;\n World.odo_error_hist(:, t) = odo_error;\n World.turning_hist(t) = rob.u(2);\n World.weight_scan_hist(t) = weight_scan;\n World.weight_odo_hist(t) = weight_odo;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%% GRAPHICS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n Graphics.lmks_all = lmks_all; Graphics.lmks_visible = lmks_visible;\n doGraphics(rob, World, Graphics, Obstacles(movingObstacles), AxisDim);\n\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%% PLOT HISTORICAL DATA %%%%%%%%%%%%%%%%%%%%%%%%%\n % Plot trajectories;\n set(Graphics.R_hist, 'xdata', World.R_hist(1,:), 'ydata', World.R_hist(2, :))\n set(Graphics.r_hist, 'xdata', World.r_hist(1,:), 'ydata', World.r_hist(2, :))\n \n % Plot position uncertainties\n figure('color', 'white')\n subplot(2, 1, 1)\n plot(1:World.tend, World.error_hist)\n title('EKF SLAM: position error over time')\n xlabel('Time (s)'), ylabel('Position Error (m)')\n subplot(2, 1, 2)\n plot(1:World.tend, sqrt(World.Pr_hist(1, :)), 'r', ...\n 1:World.tend, sqrt(World.Pr_hist(2, :)), 'b')\n title('EKF SLAM: position uncertainty over time')\n xlabel('Time (s)'), ylabel('Standard Deviation (m)')\n legend('St. Dev. in x', 'St. Dev. in y')\n \n figure('color', 'white')\n subplot(4, 1, 1)\n AX = plotyy(1:World.tend, World.scan_error_hist(1,:), ...\n 1:World.tend, World.scan_error_hist(2,:), 'plot');\n set(get(AX(1),'Ylabel'),'String',['Position' char(10) 'Error (m)'])\n set(get(AX(2),'Ylabel'),'String',['Angular' char(10) 'Error (rad)'])\n title('Scan errors over time')\n xlabel('Time (s)')\n \n subplot(4, 1, 2)\n AX2 = plotyy(1:World.tend, World.odo_error_hist(1,:), ...\n 1:World.tend, World.odo_error_hist(2,:), 'plot');\n set(get(AX2(1),'Ylabel'),'String',['Position' char(10) 'Error (m)']) \n set(get(AX2(2),'Ylabel'),'String',['Angular' char(10) 'Error (rad)'])\n title('Odometry error over time')\n \n subplot(4, 1, 3)\n plot(1:World.tend, World.weight_scan_hist, 'r', ...\n 1:World.tend, World.weight_odo_hist, 'b')\n title('Scan and odometry weights over time')\n xlabel('Time (s)'), ylabel('Weight')\n legend('Scan', 'Odometry')\n axis tight\n \n subplot(4, 1, 4)\n plot(1:World.tend, World.turning_hist)\n title('Turning control over time')\n xlabel('Time (s)'), ylabel('Angle (rad)')\n axis tight\nend", "meta": {"author": "jaijuneja", "repo": "ekf-slam-matlab", "sha": "d0746d0396aa2c24eee6633f3dfc5e1b9f1d7f87", "save_path": "github-repos/MATLAB/jaijuneja-ekf-slam-matlab", "path": "github-repos/MATLAB/jaijuneja-ekf-slam-matlab/ekf-slam-matlab-d0746d0396aa2c24eee6633f3dfc5e1b9f1d7f87/ekfSLAM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3687011784951851}} {"text": "%% This script simulates the LODCO-based epsilon-Greedy algorithm.\n% author: Hailiang Zhao\nclc, clear\nopt = optimset('Display', 'none');\n\n%% basic parameter settings (had better not change those paras)\nk = 1e-28; % effective switched capacitance (a constant decided by the chip architecture)\ntau = 0.002; % the length of time slot (in second)\nphi = 0.002; % the cost of task dropping (in second)\nomega = 1e6; % the bandwidth of MEC server (in Hz)\nsigma = 1e-13; % the noise power of the receiver (in W)\np_tx_max = 1; % the maximum transmit power of mobile device (in W)\nf_max = 1.5e9; % the maximum CPU-cycle frequency of mobile device (in Hz)\nE_max = 0.002; % the maximum amout of battery output energy (in J)\nL = 1000; % the input size of the computation task (in bit)\nX = 737.5; % the number of CPU cycles needed on processing one bit of task\nW = L * X; % the number of CPU cycles needed on processing one task\nE_H_max = 48e-6; % the upper bound of the energy arrive at the mobile device (in J)\np_H = E_H_max / (2*tau); % the average Energy Harvesting (EH) power (in W)\ng0 = power(10, -4); % the path-loss constant\nd0 = 1; % the relative distance between each mobile device and each MEC server\n\n%% parameter control\nN = 10; % the number of mobile devices\nM = 8; % the number of MEC servers\nT = 2000; % the number of time slot (a.k.a. the size of the time horizon)\ntau_d = 0.002; % execution deadline (in second)\nd = 50; % the distance between the mobile device and the MEC server (in meter)\nE_min = 0.02e-3; % the minimum amout of battery output energy (in J)\nV = 1e-5; % the weight of penalty (the control parameter introduced by Lyapunov Optimization)\nrho = 0.6; % the probability that the computation task is requested\nmax_connects = 4; % the maximum number of processible mobile devices for each MEC server ($ \\frac{f_s^{max} \\tau}{L X} $)\nmin_distance = 10; % the minimum distance from mobile device to MEC server\nmax_distance = 50; % the maximum distance from mobile device to MEC server\neps = 0.8; % if rand() <= eps, for the best i-j pair, we always choose MEC server execution mode (except no MEC server to choose)\n\n% the lower bound of perturbation parameter\nE_max_hat = min(max(k * W * (f_max)^2, p_tx_max * tau), E_max);\ntheta = E_max_hat + V * phi / E_min;\n\n%% allocate storage for valuable results\nB = zeros(T, N); % the battery energy level (in J)\nB_hat = zeros(T, N); % the virtual battery energy level ($B_hat = B - theta$)\ne = zeros(T, N); % the amout of the harvested and stored energy (in J)\nchosen_mode = zeros(T, N); % {1: local, 2: remote, 3: drop, 4: no task request}\nchosen_server = zeros(T, N); % record the index of chosen server for each mobile device if its choice is MEC server execution\nf = zeros(T, N); % the CPU-cycle frequency of local execution (in Hz)\np = zeros(T, N); % the transmit power of computation offloading (in W)\n\nmobile_exe_cost = zeros(T, N); % the mobile execution cost (delay) (in second)\nserver_exe_cost = zeros(T, N); % the MEC server execution cost (delay) (in second)\nfinal_chosen_cost = zeros(T, N); % the final execution delay under currently chosen modes (in second)\n\nmobile_exe_E = zeros(T, N); % the energy consumption for mobile execution (in J)\nserver_exe_E = zeros(T, N); % the energy consumption for MEC server execution (in J)\nfinal_chosen_E = zeros(T, N); % the energy consumption of the final chosen modes (in J)\n\n%% simulation begin\nt = 1;\nwhile t <= T\n disp(['===> Time slot #', num2str(t), ' <==='])\n \n %% allocate storage for mode-chosen\n device_server_pairs = []; % each column represents i, j, J_s^{\\star}(i, j), respectively\n remained_connects = max_connects * ones(M, 1); % the available connections of MEC servers\n J_m = zeros(N, 1); J_s = zeros(N, M); % the matrices for J_m and J_s values\n p_mat = zeros(N, M); % the matrix for transmit power\n server_cost_mat = zeros(N, M); % the matrix for MEC server execution cost\n server_E_mat = zeros(N, M); % the matrix for energy consumption of MEC server\n \n %% initialization\n % generate the virtual battery energy level\n B_hat(t, :) = B(t, :) - theta;\n % generate the channel power gain (from each mobile device to each MEC sever)\n distances = unifrnd(min_distance, max_distance, N, M);\n gamma = exprnd(1, N, M);\n h_mat = g0 * gamma .* power(d0 ./ distances, 4);\n \n %% step 1: for each mobile device, choose the initial mode\n for i = 1: N\n disp(['Mobile device #', num2str(i)])\n \n %% step 1.1: get the optimal energy harvesting no matter whether task is requested\n E_H_t = unifrnd(0, E_H_max);\n if B_hat(t, i) <= 0\n e(t, i) = E_H_t;\n end\n \n %% step 1.2: get the (initial) optimal computation offloading strategy (I_m(i), I_s(i, :), I_d(i), f(t, i), p(t, i))\n % generate the task request\n zeta = binornd(1, rho);\n if zeta == 0\n % chosen mode has to be 4\n disp('no task request generated!')\n chosen_mode(t, i) = 4;\n else\n % chosen_mode is chosen from {1, 2, 3}\n disp('task request generated!')\n \n %% step 1.2.1: solve the optimization problem $\\mathcal{P}_{ME}$ (f(t, i) > 0)\n % calculate f_L and f_U\n f_L = max(sqrt(E_min / (k * W)), W / tau_d);\n f_U = min(sqrt(E_max / (k * W)), f_max);\n if f_L <= f_U\n % the sub-problem is feasible\n disp('mobile execution ($\\mathcal{P}_{ME}$) is feasible!')\n \n if B_hat(t, i) < 0\n f_0 = (V / (-2 * B_hat(t, i) * k))^(1/3);\n else\n % complex number may exist, which may lead to error\n f_0 = -(V / (2 * B_hat(t, i) * k))^(1/3);\n end\n \n if (f_0 > f_U && B_hat(t, i) < 0) || (B_hat(t, i) >= 0)\n f(t, i) = f_U;\n elseif f_0 >= f_L && f_0 <= f_U && B_hat(t, i) < 0\n f(t, i) = f_0;\n elseif f_0 < f_L && B_hat(t, i) < 0\n f(t, i) = f_L;\n end\n % check whether f(t, i) is zero\n if f(t, i) == 0\n disp('Something wrong! f is 0!')\n end\n \n % calculate the delay of mobile execution\n mobile_exe_cost(t, i) = W / f(t, i);\n % calculate the energy consumption of mobile execution\n mobile_exe_E(t, i) = k * W * (f(t, i)^2);\n % calculate the value of optimization goal\n J_m(i) = -B_hat(t, i) * k * W * (f(t, i)^2 + V * W / f(t, i));\n else\n % the sub-problem is not fasible because (i) the limited \n % computation capacity or (ii) time cosumed out of deadline \n % or (iii) the energy consumed out of battery energy level\n % If it is not feasible, it just means that we cannot choose \n % 'I_m(i)=1'. It dosen't mean that the task has to be dropped.\n disp('mobile execution ($\\mathcal{P}_{ME}$) is not feasible!')\n f(t, i) = 0;\n mobile_exe_cost(t, i) = 0;\n mobile_exe_E(t, i) = 0;\n % 'I_m(i)=1' can never be chosen if mobile execution goal is inf\n J_m(i) = inf;\n end\n \n %% step 1.2.2: solve the optimization problem $\\mathcal{P}_{SE}$ (p(t, i) > 0)\n % calculate J_s(i, j) from mobile device i to each MEC server j\n for j = 1: M\n disp(['MEC server #', num2str(j)])\n h = h_mat(i, j);\n \n E_tmp = sigma * L * log(2) / (omega * h);\n p_L_taud = (power(2, L / (omega * tau_d)) - 1) * sigma / h;\n % calculate p_L\n if E_tmp >= E_min\n p_L = p_L_taud;\n else\n % calculate p_E_min (use inline function and fsolve)\n y = @(x) x * L - omega * log2(1 + h*x/sigma) * E_min;\n % accroding to the function figure, p_L_taud is a positive \n % number around 0.2\n p_E_min = fsolve(y, 0.2, opt);\n p_L = max(p_L_taud, p_E_min);\n end\n % calculate p_U\n if E_tmp >= E_max\n p_U = 0;\n else\n % caculate p_E_max (use inline function and fsolve)\n y = @(x) x * L - omega * log2(1 + h*x/sigma) * E_max;\n % accroding to the function figure, p_E_max is a large positive\n % number around 20\n p_E_max = fsolve(y, 100, opt);\n p_U = min(p_tx_max, p_E_max);\n end\n \n if p_L <= p_U\n % the sub-problem is feasible\n disp('MEC server execution ($\\mathcal{P}_{SE}$) is feasible!')\n % calculate p_0\n virtual_battery = B_hat(t, i);\n y = @(x) virtual_battery * log2(1 + h*x/sigma) + ...\n h * (V - virtual_battery*x) / log(2) / (sigma + h*x);\n p_0 = fsolve(y, 0.5, opt);\n \n if (p_U < p_0 && B_hat(t, i) < 0) || B_hat(t, i) >= 0\n p_mat(i, j) = p_U;\n elseif p_0 < p_L && B_hat(t) < 0\n p_mat(i, j) = p_L;\n elseif p_0 >= p_L && p_0 <= p_U && B_hat(t, i) < 0\n p_mat(i, j) = p_0;\n end\n % check whether p_mat(i, j) is zero\n if p_mat(i, j) == 0\n disp('Something wrong! p is 0!')\n end\n \n % calculate the delay of MEC server execution\n server_cost_mat(i, j) = L / (omega * log2(1 + h*p_mat(i, j)/sigma));\n % calculate the energy consumption of MEC server execution\n server_E_mat(i, j) = p_mat(i, j) * server_cost_mat(i, j);\n % calculate the value of optimization goal\n J_s(i, j) = (-B_hat(t, i) * p_mat(i, j) + V) * server_cost_mat(i, j);\n \n % (we can not set server_exe_cost(t, i) and server_exe_E(t, i) for now)\n else\n % the sub-problem is not feasible because (i) the limited transmit \n % power or (ii) time cosumed out of deadline or (iii) the energy \n % consumed out of battery energy level\n % If it is not feasible, it just means that we cannot choose \n % 'I_s(i,j)=1'. It dosen't mean that the task has to be dropped.\n disp('MEC server execution ($\\mathcal{P}_{SE}$) is not feasible!')\n p_mat(i, j) = 0;\n server_cost_mat(i, j) = 0;\n server_E_mat(i, j) = 0;\n % 'I_s(i,j)=1' can never be chosen if MEC server execution goal is inf\n J_s(i, j) = inf;\n \n % (we can not set server_exe_cost(t, i) and server_exe_E(t, i) for now)\n % Similarly, we do not check whether the energy cunsumed is larger than\n % battery energy level because the problem $\\mathcal{J}_{CO}$ does\n % not have constraint (8).\n end\n end\n \n %% step 1.2.3: choose the (initial) optimal execution mode\n J_d = V * phi;\n disp(['J_m(i):', num2str(J_m(i))])\n disp(['J_s(i,:):', num2str(J_s(i, :))])\n [~, mode] = min([J_m(i), J_s(i, :), J_d]);\n if mode == 1\n % mobile execution\n chosen_mode(t, i) = 1;\n final_chosen_cost(t, i) = mobile_exe_cost(t, i);\n final_chosen_E(t, i) = mobile_exe_E(t, i);\n elseif mode == (M+2)\n % drop\n chosen_mode(t, i) = 3;\n final_chosen_cost(t, i) = phi;\n final_chosen_E(t, i) = 0;\n else\n % MEC servre execution\n chosen_mode(t, i) = 2;\n % add i, the chosen j, and their J_s(i, j) value into the pairs\n device_server_pairs = [device_server_pairs; [i, mode-1, J_s(i, mode-1)]];\n end\n end\n end\n \n %% step 2: allocate connection right for each mobile device who chooses MEC server execution\n while ~isempty(device_server_pairs)\n if rand() <= eps\n % find the {i, j, J_s(i, j)} with the minimum J_s(i, j) in the device_server_pairs, choose MEC server execution mode, \n % except no MEC server to choose\n [min_Js, idx] = min(device_server_pairs(:, 3));\n i = device_server_pairs(idx, 1); j = device_server_pairs(idx, 2); % find the i and its j\n if remained_connects(j) >= 1\n % the chosen i can be allocated to the j-th MEC server\n % set its final modes as 2 and record the final cost and energy consumption for it\n chosen_mode(t, i) = 2; % this is not necessary\n p(t, i) = p_mat(i, j);\n server_exe_cost(t, i) = server_cost_mat(i, j);\n server_exe_E(t, i) = server_E_mat(i, j);\n chosen_server(t, i) = j;\n final_chosen_cost(t, i) = server_exe_cost(t, i);\n final_chosen_E(t, i) = server_exe_E(t, i);\n \n % update remained_connects for j\n remained_connects(j) = remained_connects(j) - 1;\n % finally, remove it from global pairs, it is done\n device_server_pairs(device_server_pairs(:, 1) == i, :) = [];\n else\n % the chosen i can not be allocated to the j-th MEC server\n % set the mobile device's J_s(i, j) as inf\n % (which means no matter what happens, the MEC server j can never be chosen)\n J_s(i, j) = inf;\n % remove it from global pairs\n device_server_pairs(device_server_pairs(:, 1) == i, :) = [];\n % if there still exists j' where J_s(i, j') is not inf, we choose the best j', \n % otherwise we can only choose from mobile execution and drop\n if min(J_s(i, :)) ~= inf\n [second_min_Js, second_min_j] = min(J_s(i, :));\n % add the new pair into global pairs\n device_server_pairs = [device_server_pairs; [i, second_min_j, second_min_Js]];\n else\n % choose from mobile execution and drop for i\n [~, mode] = min([J_m(i), inf, J_d]);\n chosen_mode(t, i) = mode;\n if mode == 1\n final_chosen_cost(t, i) = mobile_exe_cost(t, i);\n final_chosen_E(t, i) = mobile_exe_E(t, i);\n else\n final_chosen_cost(t, i) = phi;\n final_chosen_E(t, i) = 0;\n end\n end\n end\n else\n % do as LODCO-based Greedy algorithm do\n for j = 1: M\n % find every pair who chooses the MEC server j\n device_j_pairs = device_server_pairs(device_server_pairs(:, 2) == j, :);\n % find those devices is\n is = device_j_pairs(:, 1);\n if isempty(is)\n disp(['For current MEC server #', num2str(j), ', no mobile device choose it!'])\n % go to handle next MEC server\n continue;\n end\n if remained_connects(j) >= length(is)\n % every mobile device who chooses j can be connected,\n % set their final modes as 2 and record the final cost and energy consumption for them\n chosen_mode(t, is) = 2; % this is not necessary\n p(t, is) = transp(p_mat(is, j));\n server_exe_cost(t, is) = transp(server_cost_mat(is, j));\n server_exe_E(t, is) = transp(server_E_mat(is, j));\n chosen_server(t, is) = repmat(j, 1, length(is));\n final_chosen_cost(t, is) = server_exe_cost(t, is);\n final_chosen_E(t, is) = server_exe_E(t, is);\n\n % update remained_connects for j\n remained_connects(j) = remained_connects(j) - length(is);\n % finally, remove them from global pairs, they are done\n device_server_pairs(device_server_pairs(:, 2) == j, :) = [];\n else\n if remained_connects(j) == 0\n % no mobile device can be connected, remove all mobile devices who chooses j from global pairs\n device_server_pairs(device_server_pairs(:, 2) == j, :) = [];\n % set those mobile devices' J_s(i, j) as inf\n % (which means no matter what happens, the MEC server j can never be chosen)\n J_s(is, j) = inf;\n % choose mode again for those i and insert new potential pairs into global pairs\n for idx = 1: numel(is)\n i = is(idx);\n [~, mode] = min([J_m(i), J_s(i, :), J_d]);\n if mode == 1\n chosen_mode(t, i) = 1;\n final_chosen_cost(t, i) = mobile_exe_cost(t, i);\n final_chosen_E(t, i) = mobile_exe_E(t, i);\n elseif mode == (M+2)\n chosen_mode(t, i) = 3;\n final_chosen_cost(t, i) = phi;\n final_chosen_E(t, i) = 0;\n else\n chosen_mode(t, i) = 2;\n device_server_pairs = [device_server_pairs; [i, mode-1, J_s(i, mode-1)]];\n end\n end\n else\n % some mobile devices can be connected, set their final modes as 2 and remove them from global pairs\n % besides, record the final cost and energy consumption for them\n % for the left i', remove them from global pairs and set J_s(i', j) as inf, \n % choose mode again for those i' and insert new potential pairs into global pairs\n\n % sort the J_s(is, j) and return those lucky idxs\n [~, idxs] = sort(device_j_pairs(:, 3));\n for idx = 1: remained_connects(j)\n i = idxs(idx);\n chosen_mode(t, i) = 2;\n p(t, i) = p_mat(i, j);\n server_exe_cost(t, i) = server_cost_mat(i, j);\n server_exe_E(t, i) = server_E_mat(i, j);\n chosen_server(t, i) = j;\n final_chosen_cost(t, i) = server_exe_cost(t, i);\n final_chosen_E(t, i) = server_exe_E(t, i);\n\n % remove i from global pairs\n device_server_pairs(device_server_pairs(:, 1) == i, :) = [];\n end\n\n % update remained_connects for j\n remained_connects(j) = 0;\n\n % for those unlucky mobile devices i', set J_s(i', j) as inf (i' are in currently device_server_pairs(: , j) now)\n residual_is = device_server_pairs(device_server_pairs(:, 2) == j, 1);\n J_s(residual_is, j) = inf;\n for idx = 1: numel(residual_is)\n residual_i = residual_is(idx);\n [~, mode] = min([J_m(residual_i), J_s(residual_i, :), J_d]);\n if mode == 1\n chosen_mode(t, residual_i) = 1;\n final_chosen_cost(t, residual_i) = mobile_exe_cost(t, residual_i);\n final_chosen_E(t, residual_i) = mobile_exe_E(t, residual_i);\n elseif mode == (M+2)\n chosen_mode(t, residual_i) = 3;\n final_chosen_cost(t, residual_i) = phi;\n final_chosen_E(t, residual_i) = 0;\n else\n chosen_mode(t, residual_i) = 2;\n device_server_pairs = [device_server_pairs; [residual_i, mode-1, J_s(residual_i, mode-1)]];\n end\n end\n end\n end\n end\n end\n end\n \n %% step 3: update the battery energy level and go to the next time slot\n B(t + 1, :) = B(t, :) - final_chosen_E(t, :) + e(t, :);\n t = t + 1;\n \nend\n\n%% step 4: evaluate the simulation results\n% 1. the battery energy level vs. time slot\nfigure\nplot(1:T, B(1:T, :))\nhold on\nplot(1:T, repmat(theta + E_H_max, [T, 1]), '-')\ntitle('Envolution of battery energy level')\nxlabel('time slot')\nylabel('battery energy level $B_t$ of each mobile device', 'Interpreter','latex')\n\n% 2. the average execution cost vs. time slot\naccumulated = 0;\naverage_cost = zeros(T, N);\nfigure\nfor i = 1: N\n % draw for each mobile device\n request_num = 0;\n for t = 1: T\n accumulated = accumulated + final_chosen_cost(t, i);\n if chosen_mode(t, i) ~= 4\n % there exists task request\n request_num = request_num + 1;\n end\n average_cost(t, i) = accumulated / request_num;\n end\n plot(1:T, average_cost(:, i));\n hold on\nend\ntitle('Envolution of average execution cost')\nxlabel('time slot')\nylabel('average execution cost $\\frac{1}{T} \\sum_{t=0}^{T-1} cost^t$ of each mobile device', 'Interpreter','latex')\n\n% 3. the average ratio of each chosen mode of the ith mobile device vs. time slot\naverage_ratio = zeros(T, 3);\nmobile_exe = 0; server_exe = 0; drop = 0;\nrequest_num = 0;\ni = 1; % we simply choose the first mobile device\nfor t = 1: T\n if final_chosen_cost(t, i) == 0\n continue\n else\n request_num = request_num + 1;\n if chosen_mode(t, i) == 1\n mobile_exe = mobile_exe + 1;\n elseif chosen_mode(t, i) == 2\n server_exe = server_exe + 1;\n else\n drop = drop + 1;\n end\n end\n average_ratio(t, :) = [mobile_exe, server_exe, drop] / request_num;\nend\nfigure\nplot(1:T, average_ratio(:, 1));\nhold on\nplot(1:T, average_ratio(:, 2));\nhold on\nplot(1:T, average_ratio(:, 3));\nlegend('mobile execution', 'MEC server execution', 'drop')\ntitle('Envolution of average ratio of chosen modes')\nxlabel('time slot')\nylabel('average ratio of chosen modes $\\frac{1}{T} \\sum_{t=0}^{T-1} \\{I_m^t, I_s^t, I_d^t\\}$ of the i-th mobile device', 'Interpreter','latex')\n", "meta": {"author": "hliangzhao", "repo": "Edge-Computing-Codes", "sha": "dc6dc2b59e6dcc7bb20355cf198cb240e10e338b", "save_path": "github-repos/MATLAB/hliangzhao-Edge-Computing-Codes", "path": "github-repos/MATLAB/hliangzhao-Edge-Computing-Codes/Edge-Computing-Codes-dc6dc2b59e6dcc7bb20355cf198cb240e10e338b/UIC18/eps_greedy_LODCO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3685790755399626}} {"text": "%%***********************************************************************\n%% Read in a problem in SDPA sparse format.\n%%\n%% [blk,At,C,b] = read_sdpa(fname)\n%%\n%% Input: fname = name of the file containing SDP data in\n%% SDPA foramt. \n%% Important: the data is assumed to contain only \n%% semidefinite and linear blocks. \n%%\n%%***********************************************************************\n%% SDPNAL+ \n%% Copyright (c) 2014 by\n%% Liuqin Yang, Defeng Sun, and Kim-Chuan Toh\n%%***********************************************************************\n function [blk,At,C,b] = read_sdpa(fname)\n\n%%\n%% Open the file for input\n%%\n compressed = 0; \n if exist(fname)\n fid = fopen(fname,'r');\n elseif exist([fname,'.Z']); \n compressed = 1; \n unix(['uncompress ',fname,'.Z']);\n fid = fopen(fname,'r');\n elseif exist([fname,'.gz']); \n compressed = 2;\n unix(['gunzip ',fname,'.gz']);\n fid = fopen(fname,'r');\n else\n fprintf(['*** Problem \"',fname,'\" not found, please specify the correct path or problem name. \\n']);\n blk = []; At = []; C = []; b = [];\n return;\n end\n%%\n%% Clean up special characters and comments from the file \n%%\n [datavec,count] = fscanf(fid,'%c');\n linefeeds = findstr(datavec,char(10));\n comment_chars = '*\"=';\n cumidx = [];\n for i=1:length(comment_chars)\n idx = findstr(datavec,comment_chars(i));\n cumidx = [cumidx,idx];\n end\n for j=length(cumidx):-1:1\n if (cumidx(j)==1) || (strcmp(datavec(cumidx(j)-1),char(10)))\n datavec(cumidx(j):linefeeds(min(find(cumidx(j) size(blksize,2); blksize = blksize'; end\n%%\n%% Get input b.\n%%\n idxstrt = 2+numblk; \n b = datavec(idxstrt+[1:m]); \n idxstrt = idxstrt+m; \n b = -b;\n%%\n%% Construct blk\n%%\n deblksize = 80; \n spblkidxtmp = find( (blksize>1) & (blksize < deblksize) ); \n spblkidxtmp = sort(spblkidxtmp);\n deblkidx = find( (blksize<=1) | (blksize >= deblksize) ); \n denumblk = length(deblkidx); \n linblkidx = zeros(1,denumblk); \n for p = 1:denumblk\n n = blksize(deblkidx(p)); \n if (n > 1); \n blk{p,1} = 's'; blk{p,2} = n;\n n2 = n*(n+1)/2; \n At{p,1} = sparse(n2,m);\n C{p,1} = sparse(n,n); \n else\n linblkidx(p) = p; \n blk{p,1} = 'l'; blk{p,2} = abs(n); \n At{p,1} = sparse(abs(n),m); \n C{p,1} = sparse(abs(n),1); \n end \n end\n if ~isempty(spblkidxtmp) \n maxnumblk = 200; \n spnumblk = ceil(length(spblkidxtmp)/maxnumblk);\n for q = 1:spnumblk\n if (q < spnumblk) \n spblkidxall{q} = spblkidxtmp([(q-1)*maxnumblk+1: q*maxnumblk]); \n else\n spblkidxall{q} = spblkidxtmp([(q-1)*maxnumblk+1: length(spblkidxtmp)]); \n end\n tmp = blksize(spblkidxall{q}); \n blk{denumblk+q,1} = 's'; \n blk{denumblk+q,2} = tmp; \n n2 = sum(tmp.*(tmp+1))/2; \n At{denumblk+q,1} = sparse(n2,m);\n C{denumblk+q,1} = sparse(sum(tmp),sum(tmp)); \n end\n else\n spnumblk = 0; \n end\n linblkidx(denumblk+[1:spnumblk]) = zeros(1,spnumblk); \n%%\n%% Construct single blocks of A,C\n%%\n len = length(datavec); \n Y = reshape(datavec(idxstrt+1:len),5,(len-idxstrt)/5)'; \n clear datavec; \n Y = sortrows(Y,[1 2]); \n matidx = [0; find(diff(Y(:,1)) ~= 0); size(Y,1)];\n%%\n for k = 1:length(matidx)-1\n idx = [matidx(k)+1 : matidx(k+1)]; \n Ytmp = Y(idx,1:5); \n matno = Ytmp(1,1); \n Ytmp2 = Ytmp(:,2); \n for p = 1:denumblk \n n = blksize(deblkidx(p)); \n idx = find(Ytmp2 == deblkidx(p)); \n ii = Ytmp(idx,3); jj = Ytmp(idx,4); vv =Ytmp(idx,5); \n len = length(idx); \n if (n > 1)\n idxtmp = find(ii > jj); \n if ~isempty(idxtmp); \n tmp = jj(idxtmp); \n jj(idxtmp) = ii(idxtmp); ii(idxtmp) = tmp; \n end\n tmp = -sparse(ii,jj,vv,n,n); \n tmp = tmp + triu(tmp,1)'; \n else\n tmp = -sparse(ii,ones(len,1),vv,abs(n),1); \n end\n if (matno == 0) \n C{p,1} = tmp; \n else\n if (n > 1)\n At{p,1}(:,matno) = svec(blk(p,:),tmp,1); \n else\n At{p,1}(:,matno) = tmp; \n end\n end\n end\n end \n%%\n%% Construct big sparse block of A,C \n%%\nif (spnumblk > 0)\n Y1 = Y(:,1); \n diffY1 = find(diff([-1; Y1; inf])); \n for kk = 1:length(diffY1)-1\n idx = [diffY1(kk) : diffY1(kk+1)-1];\n matno = Y1(diffY1(kk)); \n Ytmp = Y(idx,1:5);\n Ytmp2 = Ytmp(:,2); \n maxYtmp2 = Ytmp2(length(Ytmp2)); \n minYtmp2 = Ytmp2(1);\n diffYtmp2 = Ytmp2(find(diff([-1; Ytmp2]))); \n for q = 1:spnumblk\n spblkidx = spblkidxall{q};\n maxspblkidx = spblkidx(length(spblkidx));\n minspblkidx = spblkidx(1); \n count = 0; \n if (minYtmp2 <= maxspblkidx) & (maxYtmp2 >= minspblkidx)\n tmpblksize = blksize(spblkidx);\n n = sum(tmpblksize); \n cumspblksize = [0 cumsum(tmpblksize)]; \n n2 = sum(tmpblksize.*(tmpblksize+1))/2; \n idx = zeros(n2,1); offset = zeros(n2,1); \n for t = [1:length(diffYtmp2)] \n \t p = find(spblkidx == diffYtmp2(t)); \n if ~isempty(p)\n\t idxtmp = find(Ytmp2 == spblkidx(p));\n len = length(idxtmp); \n \t idx(count+[1:len]) = idxtmp; \n offset(count+[1:len]) = cumspblksize(p); \n count = count + len; \n end\n end \n idx = idx(1:count); offset = offset(1:count); \n ii = Ytmp(idx,3)+offset; jj = Ytmp(idx,4)+offset; vv = Ytmp(idx,5);\n idxtmp = find(ii > jj); \n if ~isempty(idxtmp); \n tmp = jj(idxtmp); \n jj(idxtmp) = ii(idxtmp); ii(idxtmp) = tmp; \n end\n\t idxeq = find(ii==jj); \n tmp = spconvert([ii jj -vv; jj ii -vv; n n 0]) ...\n + spconvert([ii(idxeq) jj(idxeq) vv(idxeq); n n 0]);\n if (matno == 0) \n C{denumblk+q,1} = tmp;\n else\n At{denumblk+q,1}(:,matno) = svec(blk(denumblk+q,:),tmp,1); \n end\n end\n end\n end\nend\n%%\n%% put all linear blocks together as a single linear block\n%% \n idx = find(linblkidx); \n if (length(idx) > 1)\n sdpidx = find(linblkidx==0); \n blktmp = 0; Atmp = []; Ctmp = [];\n for k = 1:length(idx)\n tmp = linblkidx(idx(k)); \n blktmp = blktmp+blk{tmp,2}; \n Atmp = [Atmp; At{tmp}];\n Ctmp = [Ctmp; C{tmp}]; \n end\n At = At(sdpidx); C = C(sdpidx); blk = blk(sdpidx,:); \n len = length(sdpidx); \n blk(2:len+1,:) = blk; \n blk{1,1} = 'l'; blk{1,2} = blktmp; \n At(2:len+1,1) = At; C(2:len+1,1) = C; \n At{1,1} = Atmp; C{1,1} = Ctmp; \n end\n%%******************************************************************\n\n", "meta": {"author": "intellhave", "repo": "SDRSAC", "sha": "b081721e9dfd7843d75aa12f30025b2bd7c8f024", "save_path": "github-repos/MATLAB/intellhave-SDRSAC", "path": "github-repos/MATLAB/intellhave-SDRSAC/SDRSAC-b081721e9dfd7843d75aa12f30025b2bd7c8f024/solvers/SDPNAL+v1.0/util/read_sdpa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.36848184968020903}} {"text": "% DeJong_f3.m\n% De Jong's f3 function, ND, also called STEP\n% from: http://www.cs.rpi.edu/~hornda/pres/node4.html\n%\n% f(x) = sum( floor(x) )\n%\n% x = N element row vector containing [ x0, x1,..., xN ]\n% each row is processed independently,\n% you can feed in matrices of timeXN no prob\n%\n% example: cost = DeJong_f3([1,2;3,4;5,6])\n% note minimum @ x= -Inf or whatever lower bound you've chosen\n\n% Brian Birge\n% Rev 1.0\n% 9/12/04\n\nfunction [out]=DeJong_f3(in)\n out = sum( floor(in) , 2);", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/MATLAB智能算法30个案例分析/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/DeJong_f3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.36788233527255954}} {"text": "function [stat, cfg] = ft_statistics_montecarlo(cfg, dat, design, varargin)\n\n% FT_STATISTICS_MONTECARLO performs a nonparametric statistical test by calculating\n% Monte-Carlo estimates of the significance probabilities and/or critical values from\n% the permutation distribution. This function should not be called directly, instead\n% you should call the function that is associated with the type of data on which you\n% want to perform the test.\n%\n% Use as\n% stat = ft_timelockstatistics(cfg, data1, data2, data3, ...)\n% stat = ft_freqstatistics (cfg, data1, data2, data3, ...)\n% stat = ft_sourcestatistics (cfg, data1, data2, data3, ...)\n%\n% where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS or\n% FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE,\n% FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively \n% and with cfg.method = 'montecarlo'\n%\n% The configuration options that can be specified are:\n% cfg.numrandomization = number of randomizations, can be 'all'\n% cfg.correctm = string, apply multiple-comparison correction, 'no', 'max', cluster', 'tfce', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')\n% cfg.alpha = number, critical value for rejecting the null-hypothesis per tail (default = 0.05)\n% cfg.tail = number, -1, 1 or 0 (default = 0)\n% cfg.correcttail = string, correct p-values or alpha-values when doing a two-sided test, 'alpha','prob' or 'no' (default = 'no')\n% cfg.ivar = number or list with indices, independent variable(s)\n% cfg.uvar = number or list with indices, unit variable(s)\n% cfg.wvar = number or list with indices, within-cell variable(s)\n% cfg.cvar = number or list with indices, control variable(s)\n% cfg.feedback = string, 'gui', 'text', 'textbar' or 'no' (default = 'text')\n% cfg.randomseed = string, 'yes', 'no' or a number (default = 'yes')\n%\n% If you use a cluster-based statistic, you can specify the following options that\n% determine how the single-sample or single-voxel statistics will be thresholded and\n% combined into one statistical value per cluster.\n% cfg.clusterstatistic = how to combine the single samples that belong to a cluster, 'maxsum', 'maxsize', 'wcm' (default = 'maxsum')\n% the option 'wcm' refers to 'weighted cluster mass', a statistic that combines cluster size and intensity; \n% see Hayasaka & Nichols (2004) NeuroImage for details\n% cfg.clusterthreshold = method for single-sample threshold, 'parametric', 'nonparametric_individual', 'nonparametric_common' (default = 'parametric')\n% cfg.clusteralpha = for either parametric or nonparametric thresholding per tail (default = 0.05)\n% cfg.clustercritval = for parametric thresholding (default is determined by the statfun)\n% cfg.clustertail = -1, 1 or 0 (default = 0)\n%\n% To include the channel dimension for clustering of channel level data, you should specify\n% cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS\n% If you specify an empty neighbourhood structure, clustering will only be done\n% over frequency and/or time and not over neighbouring channels.\n%\n% The statistic that is computed for each sample in each random reshuffling\n% of the data is specified as\n% cfg.statistic = 'indepsamplesT' independent samples T-statistic,\n% 'indepsamplesF' independent samples F-statistic,\n% 'indepsamplesregrT' independent samples regression coefficient T-statistic,\n% 'indepsamplesZcoh' independent samples Z-statistic for coherence,\n% 'depsamplesT' dependent samples T-statistic,\n% 'depsamplesFmultivariate' dependent samples F-statistic MANOVA,\n% 'depsamplesregrT' dependent samples regression coefficient T-statistic,\n% 'actvsblT' activation versus baseline T-statistic.\n% or you can specify your own low-level statistical function.\n%\n% You can also use a custom statistic of your choice that is sensitive to the\n% expected effect in the data. You can implement the statistic in a \"statfun\" that\n% will be called for each randomization. The requirements on a custom statistical\n% function is that the function is called ft_statfun_xxx, and that the function returns\n% a structure with a \"stat\" field containing the single sample statistical values.\n% Have a look at the functions in the fieldtrip/statfun directory (e.g. \n% FT_STATFUN_INDEPSAMPLEST) for the correct format of the input and output.\n%\n% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS,\n% FT_STATISTICS_ANALYTIC, FT_STATISTICS_STATS, FT_STATISTICS_MVPA,\n% FT_STATISTICS_CROSSVALIDATE\n\n% Undocumented local options:\n% cfg.resampling permutation, bootstrap\n% cfg.computecritval yes|no, for the statfun\n% cfg.computestat yes|no, for the statfun\n% cfg.computeprob yes|no, for the statfun\n% cfg.voxelstatistic deprecated\n% cfg.voxelthreshold deprecated\n% cfg.precondition before|after|[], for the statfun\n\n% Copyright (C) 2005-2015, 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% do a sanity check on the input data\nassert(isnumeric(dat), 'this function requires numeric data as input, you probably want to use FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS instead');\nassert(isnumeric(design), 'this function requires numeric data as input, you probably want to use FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS instead');\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'renamed', {'factor', 'ivar'});\ncfg = ft_checkconfig(cfg, 'renamed', {'unitfactor', 'uvar'});\ncfg = ft_checkconfig(cfg, 'renamed', {'repeatedmeasures', 'uvar'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'clusterthreshold', 'nonparametric', 'nonparametric_individual'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'correctm', 'yes', 'max'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'correctm', 'none', 'no'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'correctm', 'bonferoni', 'bonferroni'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'correctm', 'holms', 'holm'});\ncfg = ft_checkconfig(cfg, 'required', {'statistic'});\ncfg = ft_checkconfig(cfg, 'forbidden', {'ztransform', 'removemarginalmeans', 'randomfactor', 'voxelthreshold', 'voxelstatistic'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'statfun', 'depsamplesF', 'ft_statfun_depsamplesFmultivariate'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'statfun', 'ft_statfun_depsamplesF', 'ft_statfun_depsamplesFmultivariate'});\n\n% set the defaults for the main function\ncfg.alpha = ft_getopt(cfg, 'alpha', 0.05);\ncfg.tail = ft_getopt(cfg, 'tail', 0);\ncfg.correctm = ft_getopt(cfg, 'correctm', 'no');\ncfg.resampling = ft_getopt(cfg, 'resampling', 'permutation');\ncfg.feedback = ft_getopt(cfg, 'feedback', 'text');\ncfg.ivar = ft_getopt(cfg, 'ivar', 'all');\ncfg.uvar = ft_getopt(cfg, 'uvar', []);\ncfg.cvar = ft_getopt(cfg, 'cvar', []);\ncfg.wvar = ft_getopt(cfg, 'wvar', []);\ncfg.correcttail = ft_getopt(cfg, 'correcttail', 'no');\ncfg.precondition = ft_getopt(cfg, 'precondition', []);\n\n% explicit check for option 'yes' in cfg.correctail.\nif strcmp(cfg.correcttail, 'yes')\n ft_error('cfg.correcttail = ''yes'' is not allowed, use either ''prob'', ''alpha'' or ''no''')\nend\n\nif strcmp(cfg.correctm, 'tfce')\n % TODO this could require some better defaults\n cfg.connectivity = ft_getopt(cfg, 'connectivity', []);\n cfg.tfce_h0 = ft_getopt(cfg, 'tfce_h0', 0);\n cfg.tfce_H = ft_getopt(cfg, 'tfce_H', 2);\n cfg.tfce_E = ft_getopt(cfg, 'tfce_E', 0.5);\n cfg.tfce_nsteps = ft_getopt(cfg, 'tfce_nsteps', 100);\nelse\n % these options only apply to tfce, to ensure appropriate configs they are forbidden when _not_ clustering\n cfg = ft_checkconfig(cfg, 'unused', {'tfce_h0', 'tfce_H', 'tfce_E', 'tfce_nsteps'});\nend\n\nif strcmp(cfg.correctm, 'cluster')\n % set the defaults for clustering\n cfg.clusterstatistic = ft_getopt(cfg, 'clusterstatistic', 'maxsum');\n cfg.clusterthreshold = ft_getopt(cfg, 'clusterthreshold', 'parametric');\n cfg.clusteralpha = ft_getopt(cfg, 'clusteralpha', 0.05);\n cfg.clustercritval = ft_getopt(cfg, 'clustercritval', []);\n cfg.clustertail = ft_getopt(cfg, 'clustertail', cfg.tail);\n cfg.connectivity = ft_getopt(cfg, 'connectivity', []); % the default is dealt with below\nelse\n % these options only apply to clustering, to ensure appropriate configs they are forbidden when _not_ clustering\n cfg = ft_checkconfig(cfg, 'unused', {'clusterstatistic', 'clusteralpha', 'clustercritval', 'clusterthreshold', 'clustertail'});\nend\n\nif any(strcmp(cfg.correctm, {'cluster' 'tfce'}))\n % these options might require a spatial neighbourhood matrix\n \n % deal with the neighbourhood of the channels/triangulation/voxels\n if isempty(cfg.connectivity)\n if isfield(cfg, 'dim') && ~isfield(cfg, 'channel') && ~isfield(cfg, 'tri')\n % input data can be reshaped into a 3D volume, use bwlabeln/spm_bwlabel rather than clusterstat\n ft_info('using connectivity of voxels in 3-D volume\\n');\n cfg.connectivity = nan;\n elseif isfield(cfg, 'tri')\n % input data describes a surface along which neighbours can be defined\n ft_info('using connectivity of vertices along triangulated surface\\n');\n cfg.connectivity = triangle2connectivity(cfg.tri);\n if isfield(cfg, 'insideorig')\n cfg.connectivity = cfg.connectivity(cfg.insideorig, cfg.insideorig);\n end\n elseif isfield(cfg, 'avgoverchan') && istrue(cfg.avgoverchan)\n % channel dimension has been averaged across, no sense in clustering across space\n cfg.connectivity = true(1);\n elseif isfield(cfg, 'channel')\n cfg.neighbours = ft_getopt(cfg, 'neighbours', []);\n cfg.connectivity = channelconnectivity(cfg);\n else\n % there is no connectivity in the spatial dimension\n cfg.connectivity = false(size(dat,1));\n end\n else\n % use the specified connectivity: this is not fully robust because\n % there is no guarantee that the order of the spatial elements in the\n % data is the same as the order of the spatial elements in the\n % adjacency matrix\n end\nend\n\n% for backward compatibility and other warnings relating correcttail\nif isfield(cfg,'correctp') && strcmp(cfg.correctp,'yes')\n ft_warning('cfg.correctp has been renamed to cfg.correcttail and the options have been changed')\n disp('setting cfg.correcttail to ''prob''')\n cfg.correcttail = 'prob';\n cfg = rmfield(cfg,'correctp');\nelseif isfield(cfg,'correctp') && strcmp(cfg.correctp,'no')\n cfg = ft_checkconfig(cfg, 'renamed', {'correctp', 'correcttail'});\nend\nif strcmp(cfg.correcttail,'no') && cfg.tail==0 && cfg.alpha==0.05\n ft_warning('Doing a two-sided test without correcting p-values or alpha-level, p-values and alpha-level will reflect one-sided tests per tail. See http://bit.ly/2YQ1Hm8')\nend\n\n% for backward compatibility\nif size(design,2)~=size(dat,2)\n design = transpose(design);\nend\n\nif ischar(cfg.ivar) && strcmp(cfg.ivar, 'all')\n cfg.ivar = 1:size(design,1);\nend\n\n% fetch function handle to the low-level statistics function\nstatfun = ft_getuserfun(cfg.statistic, 'statfun');\nif isempty(statfun)\n ft_error('could not locate the appropriate statistics function');\nelse\n ft_info('using \"%s\" for the single-sample statistics\\n', func2str(statfun));\nend\n\n% construct the resampled design matrix or data-shuffling matrix\nft_info('constructing randomized design\\n');\nresample = resampledesign(cfg, design);\nNrand = size(resample,1);\n\n% most of the statfuns result in this warning, which is not interesting\nws = ft_warning('off', 'MATLAB:warn_r14_stucture_assignment');\n\nif strcmp(cfg.correctm, 'cluster')\n % determine the critical value for cluster thresholding\n if strcmp(cfg.clusterthreshold, 'nonparametric_individual') || strcmp(cfg.clusterthreshold, 'nonparametric_common')\n ft_info('using a nonparametric threshold for clustering\\n');\n cfg.clustercritval = []; % this will be determined later\n elseif strcmp(cfg.clusterthreshold, 'parametric') && isempty(cfg.clustercritval)\n ft_info('computing a parametric threshold for clustering\\n');\n tmpcfg = cfg; % the next line does not pass on non-standard options that a statfun might use\n % tmpcfg = keepfields(cfg, {'dim' 'dimord' 'clusteralpha' 'clustertail' 'ivar' 'uvar' 'cvar' 'wvar' 'contrastcoefs'});\n tmpcfg.computecritval = 'yes'; % explicitly request the computation of the crtitical value\n tmpcfg.computestat = 'no'; % skip the computation of the statistic\n tmpcfg.alpha = cfg.clusteralpha; % the statfun uses cfg.alpha most likely \n try\n cfg.clustercritval = getfield(statfun(tmpcfg, dat, design), 'critval');\n catch\n disp(lasterr);\n ft_error('could not determine the parametric critical value for clustering');\n end\n elseif strcmp(cfg.clusterthreshold, 'parametric') && ~isempty(cfg.clustercritval)\n ft_info('using the specified parametric threshold for clustering\\n');\n cfg.clusteralpha = [];\n end\nend\n\n% compute the statistic for the observed data\nft_progress('init', cfg.feedback, 'computing statistic');\n% get an estimate of the time required per evaluation of the statfun\ntime_pre = cputime;\n\ntry\n % the nargout function in MATLAB 6.5 and older does not work on function handles\n num = nargout(statfun);\ncatch\n num = 1;\nend\n\nif num==1\n % only the statistic is returned\n [statobs] = statfun(cfg, dat, design);\nelseif num==2\n % both the statistic and the (updated) configuration are returned\n [statobs, cfg] = statfun(cfg, dat, design);\nelseif num==3\n % both the statistic and the (updated) configuration and the (updated) data are returned\n tmpcfg = cfg;\n if strcmp(cfg. precondition, 'before'), tmpcfg.preconditionflag = 1; end\n [statobs, tmpcfg, dat] = statfun(tmpcfg, dat, design);\n tmpcfg.preconditionflag = 0;\n cfg = tmpcfg;\nend\n\nif isstruct(statobs)\n % remember all details for later reference, continue to work with the statistic\n statfull = statobs;\n statobs = statobs.stat;\nend\n\n% remember the statistic for later reference, continue to work with the statistic\nstatfull.stat = statobs;\n\ntime_eval = cputime - time_pre;\nft_info('estimated time per randomization is %.2f seconds\\n', time_eval);\n\n% pre-allocate some memory\nif strcmp(cfg.correctm, 'cluster')\n statrand = zeros(size(statobs,1), size(resample,1), class(dat)); % this reduces the memory footprint, requires the user to use ft_struct2single on the input data\nelse\n prb_pos = zeros(size(statobs));\n prb_neg = zeros(size(statobs));\nend\n\nif strcmp(cfg.precondition, 'after')\n tmpcfg = cfg;\n tmpcfg.preconditionflag = 1;\n [tmpstat, tmpcfg, dat] = statfun(tmpcfg, dat, design);\nend\n\nif any(strcmp(cfg.correctm, {'tfce' 'max'}))\n % pre-allocate the memory to hold the distribution of most extreme positive (right) and negative (left) statistical values\n posdistribution = nan(1,Nrand);\n negdistribution = nan(1,Nrand);\nend\n\n% compute the statistic for the randomized data and count the outliers\nfor i = 1:Nrand\n ft_progress(i/Nrand, 'computing statistic %d from %d\\n', i, Nrand);\n if strcmp(cfg.resampling, 'permutation')\n tmpdesign = design(:,resample(i,:)); % the columns in the design matrix are reshufled by means of permutation\n tmpdat = dat; % the data itself is not shuffled\n if size(tmpdesign,1)==size(tmpdat,2)\n tmpdesign = transpose(tmpdesign);\n end\n elseif strcmp(cfg.resampling, 'bootstrap')\n tmpdesign = design; % the design matrix is not shuffled\n tmpdat = dat(:,resample(i,:)); % the columns of the data are resampled by means of bootstrapping\n end\n if any(strcmp(cfg.correctm, {'cluster' 'tfce'}))\n % keep each randomization in memory for cluster postprocessing\n dum = statfun(cfg, tmpdat, tmpdesign);\n if isstruct(dum)\n statrand(:,i) = dum.stat;\n else\n statrand(:,i) = dum;\n end\n else\n % do not keep each randomization in memory, but process them on the fly\n statrand = statfun(cfg, tmpdat, tmpdesign);\n if isstruct(statrand)\n statrand = statrand.stat;\n end\n \n % the following line is for debugging\n % stat.statkeep(:,i) = statrand;\n if strcmp(cfg.correctm, 'max')\n % compare each data element with the maximum statistic\n prb_pos = prb_pos + (statobsmin(statrand(:)));\n posdistribution(i) = max(statrand(:));\n negdistribution(i) = min(statrand(:));\n else\n % compare each data element with its own statistic\n prb_pos = prb_pos + (statobsstatrand);\n end\n end\nend\nft_progress('close');\n\nif strcmp(cfg.correctm, 'cluster')\n % do the cluster postprocessing\n [stat, cfg] = clusterstat(cfg, statrand, statobs);\nelseif strcmp(cfg.correctm, 'tfce')\n [stat, cfg] = tfcestat(cfg, statrand, statobs);\nelse\n if ~isequal(cfg.numrandomization, 'all')\n % in case of random permutations (i.e., montecarlo sample, and NOT full\n % permutation), the minimum p-value should not be 0, but 1/N\n prb_pos = prb_pos + 1;\n prb_neg = prb_neg + 1;\n Nrand = Nrand + 1;\n end\n switch cfg.tail\n case 1\n clear prb_neg % not needed any more, free some memory\n stat.prob = prb_pos./Nrand;\n case -1\n clear prb_pos % not needed any more, free some memory\n stat.prob = prb_neg./Nrand;\n case 0\n % for each observation select the tail that corresponds with the lowest probability\n prb_neg = prb_neg./Nrand;\n prb_pos = prb_pos./Nrand;\n stat.prob = min(prb_neg, prb_pos); % this is the probability for the most unlikely tail\n end\nend\n\n% In case of a two tailed test, the type-I error rate (alpha) refers to\n% both tails of the distribution, whereas the stat.prob value computed sofar\n% corresponds with one tail, i.e. the probability, under the assumption of\n% no effect or no difference (the null hypothesis), of obtaining a result\n% equal to or more extreme than what was actually observed. The decision\n% rule whether the null-hopothesis should be rejected given the observed\n% probability therefore should consider alpha divided by two, to correspond\n% with the probability in one of the tails (the most extreme tail). This\n% is conceptually equivalent to performing a Bonferroni correction for the\n% two tails.\n%\n% An alternative solution to distribute the alpha level over both tails is\n% achieved by multiplying the probability with a factor of two, prior to\n% thresholding it wich cfg.alpha. The advantage of this solution is that\n% it results in a p-value that corresponds with a parametric probability.\n% Below both options are realized\nif strcmp(cfg.correcttail, 'prob') && cfg.tail==0\n stat.prob = stat.prob .* 2;\n stat.prob(stat.prob>1) = 1; % clip at p=1\n % also correct the probabilities in the pos/negcluster fields\n if isfield(stat, 'posclusters')\n for i=1:length(stat.posclusters)\n stat.posclusters(i).prob = stat.posclusters(i).prob*2;\n if stat.posclusters(i).prob>1; stat.posclusters(i).prob = 1; end\n end\n end\n if isfield(stat, 'negclusters')\n for i=1:length(stat.negclusters)\n stat.negclusters(i).prob = stat.negclusters(i).prob*2;\n if stat.negclusters(i).prob>1; stat.negclusters(i).prob = 1; end\n end\n end\nelseif strcmp(cfg.correcttail, 'alpha') && cfg.tail==0\n cfg.alpha = cfg.alpha / 2;\nend\n\n% compute range of confidence interval p ? 1.96(sqrt(var(p))), with var(p) = var(x/n) = p*(1-p)/N\nstddev = sqrt(stat.prob.*(1-stat.prob)/Nrand);\nstat.cirange = 1.96*stddev;\n\nif isfield(stat, 'posclusters')\n for i=1:length(stat.posclusters)\n stat.posclusters(i).stddev = sqrt(stat.posclusters(i).prob.*(1-stat.posclusters(i).prob)/Nrand);\n stat.posclusters(i).cirange = 1.96*stat.posclusters(i).stddev;\n if i==1 && stat.posclusters(i).prob=cfg.alpha\n ft_warning('FieldTrip:posCluster_exceeds_alpha', sprintf('The p-value confidence interval of positive cluster #%i includes %.3f - consider increasing the number of permutations!', i, cfg.alpha));\n end\n end\nend\nif isfield(stat, 'negclusters')\n for i=1:length(stat.negclusters)\n stat.negclusters(i).stddev = sqrt(stat.negclusters(i).prob.*(1-stat.negclusters(i).prob)/Nrand);\n stat.negclusters(i).cirange = 1.96*stat.negclusters(i).stddev;\n if i==1 && stat.negclusters(i).prob=cfg.alpha\n ft_warning('FieldTrip:negCluster_exceeds_alpha', sprintf('The p-value confidence interval of negative cluster #%i includes %.3f - consider increasing the number of permutations!', i, cfg.alpha));\n end\n end\nend\n\nif ~isfield(stat, 'prob')\n ft_warning('probability was not computed');\nelse\n switch lower(cfg.correctm)\n case 'max'\n % the correction is implicit in the method\n ft_notice('using a maximum-statistic based method for multiple comparison correction\\n');\n ft_notice('the returned probabilities and the thresholded mask are corrected for multiple comparisons\\n');\n stat.mask = stat.prob<=cfg.alpha;\n stat.posdistribution = posdistribution;\n stat.negdistribution = negdistribution;\n case 'tfce'\n ft_notice('using a threshold free cluster enhancement based method for multiple comparison correction\\n');\n ft_notice('the returned probabilities and the thresholded mask are corrected for multiple comparisons\\n');\n stat.mask = stat.prob<=cfg.alpha;\n case 'cluster'\n % the correction is implicit in the method\n ft_notice('using a cluster-based method for multiple comparison correction\\n');\n ft_notice('the returned probabilities and the thresholded mask are corrected for multiple comparisons\\n');\n stat.mask = stat.prob<=cfg.alpha;\n case 'bonferroni'\n ft_notice('performing Bonferroni correction for multiple comparisons\\n');\n ft_notice('the returned probabilities are uncorrected, the thresholded mask is corrected\\n');\n stat.mask = stat.prob<=(cfg.alpha ./ numel(stat.prob));\n case 'holm'\n % test the most significatt significance probability against alpha/N, the second largest against alpha/(N-1), etc.\n ft_notice('performing Holm-Bonferroni correction for multiple comparisons\\n');\n ft_notice('the returned probabilities are uncorrected, the thresholded mask is corrected\\n');\n [pvals, indx] = sort(stat.prob(:)); % this sorts the significance probabilities from smallest to largest\n k = find(pvals > (cfg.alpha ./ ((length(pvals):-1:1)')), 1, 'first'); % compare each significance probability against its individual threshold\n mask = (1:length(pvals))'1\n fola=storeOverlap(f,Lb);\n else\n storeOverlap(f,Lb);\n end\n % Return first half\n fhat = f(1:Lb,:);\n elseif strcmp(F.blockalg,'segola')\n if ~isfield(F,'winLen') \n error('%s: Frame does not have FIR windows.',upper(mfilename));\n end\n Lw = F.winLen;\n switch(F.type)\n case 'fwt'\n % The SegDWT algorithm\n J = F.J;\n w = F.g;\n m = numel(w.g{1}.h);\n a = w.a(1);\n blocksize = a^J;\n r = (a^J-1)/(a-1)*(m-1);\n Lbrec = (floor(nextSb/blocksize) - floor(Sb/blocksize))*blocksize;\n rSb = (a^J-1)/(a-1)*(m-a) + mod(Sb,a^J);\n over = r - rSb;\n f = block_ifwt(c,w,J,Lbrec);\n ol = loadOverlap(r-mod(Sb, a^J),size(c,2),fola);\n olLen = size(ol,1);\n f(1:olLen-over,:) = f(1:olLen-over,:) + ol(1+over:end,:);\n f = [ol(1:over,:);f];\n if nargout>1\n fola=storeOverlap(f,r-mod(nextSb, a^J));\n else\n storeOverlap(f,r-mod(nextSb, a^J));\n end\n fhat = f(1:Lb,:);\n case {'dgt','dgtreal','dwilt','wmdct'}\n % Time step \n a = F.a; \n % Length of the left half of the window\n Lwl = floor(Lw/2);\n\n Sbonelmax = ceil((Lw-1)/a)*a + a-1;\n Sbolen = ceil((Lw-1)/a)*a + mod(Sb,a);\n % Next block overlap length\n nextSbolen = ceil((Lw-1)/a)*a + mod(nextSb,a);\n Lext = Sbolen + Lb - mod(nextSb,a);\n Lextc = Sbolen + Lb - nextSbolen + Lwl;\n \n startc = ceil(Lwl/a)+1;\n endc = ceil((Lextc)/a);\n \n cc = F.coef2native(c,size(c));\n chat = zeros(size(cc,1),ceil(F.L/a),size(cc,3),class(cc));\n chat(:,startc:endc,:) = cc;\n chat = F.native2coef(chat); \n f = F.frsyn(chat);\n f = f(1:Lext,:);\n over = Sbonelmax - Sbolen;\n \n ol = loadOverlap(Sbonelmax-mod(Sb,a),size(c,2),fola);\n olLen = size(ol,1);\n f(1:olLen-over,:) = f(1:olLen-over,:) + ol(1+over:end,:);\n f = [ol(1:over,:);f];\n if nargout>1\n fola=storeOverlap(f,Sbonelmax-mod(nextSb,a));\n else\n storeOverlap(f,Sbonelmax-mod(nextSb,a));\n end\n fhat = f(1:Lb,:);\n case {'filterbank','filterbankreal'} \n lcma = F.lcma;\n % Time step \n a = F.a(:,1); \n % Length of the left half of the window\n Lwl = max(-F.g_info.offset);\n \n if Lw-1 < a\n Sbonelmax = lcma-1;\n Sbolen = mod(Sb,lcma);\n nextSbolen = mod(nextSb,lcma);\n else\n Sbonelmax = ceil((Lw-1)/lcma)*lcma + lcma-1;\n Sbolen = ceil((Lw-1)/lcma)*lcma + mod(Sb,lcma);\n nextSbolen = ceil((Lw-1)/lcma)*lcma + mod(nextSb,lcma);\n end\n\n\n Lext = Sbolen + Lb - mod(nextSb,lcma);\n Lextc = Sbolen + Lb - nextSbolen + Lwl;\n \n startc = ceil(Lwl./a)+1;\n endc = ceil((Lextc)./a);\n \n cc = F.coef2native(c,size(c));\n \n chat = cell(numel(cc),1);\n for ii=1:numel(cc)\n chat{ii} = zeros(ceil(F.L./a(ii)),size(cc{ii},2));\n chat{ii}(startc(ii):endc(ii),:) = cc{ii};\n end\n \n chat = F.native2coef(chat); \n f = F.frsyn(chat);\n f = f(1:Lext,:);\n over = Sbonelmax - Sbolen;\n \n \n ol = loadOverlap(Sbonelmax-mod(Sb,lcma),size(c,2),fola);\n olLen = size(ol,1);\n f(1:olLen-over,:) = f(1:olLen-over,:) + ol(1+over:end,:);\n f = [ol(1:over,:);f];\n if nargout>1\n fola=storeOverlap(f,Sbonelmax-mod(nextSb,lcma));\n else\n storeOverlap(f,Sbonelmax-mod(nextSb,lcma));\n end\n fhat = f(1:Lb,:); \n otherwise\n error('%s: Unsupported frame.',upper(mfilename));\n end\n\n else\n error('%s: Frame was not created with blockaccel.',upper(mfilename));\n end\n\nend\n\nfunction overlap = loadOverlap(L,chan,overlap)\n%LOADOVERLAP Loads overlap\n%\n%\n if isempty(overlap)\n overlap = block_interface('getSynOverlap');\n end\n \n if isempty(overlap)\n overlap = zeros(L,chan,block_interface('getClassId'));\n end\n Lo = size(overlap,1);\n if nargin<1\n L = Lo;\n end\n if L>Lo\n % Required more samples than stored\n if 0\n error('%s: Required more samples than stored.',upper(mfilename));\n else\n % pad with zeros\n overlapTmp = zeros(L,chan,block_interface('getClassId')); \n overlapTmp(end-Lo+1:end,:) = overlap;\n overlap = overlapTmp;\n end\n end\n overlap = overlap(end-L+1:end,:);\nend\n\nfunction overlap = storeOverlap(fext,L)\n%STOREOVERLAP Stores overlap\n%\n%\n if L>size(fext,1)\n error('%s: Storing more samples than passed.',upper(mfilename));\n end\n overlap = fext(end-L+1:end,:);\n \n if nargout<1\n block_interface('setSynOverlap',overlap); \n end\nend % STOREOVERLAP\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/blockproc/blocksyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.36771852778005404}} {"text": "function RoPSs = RoPSFunc(mesh,neighborSize,binSize, rotaSize, LocalFrames)\n\n% Author: Yulan Guo {yulan.guo@nudt.edu.cn}\n% NUDT, China & CSSE, UWA, Australia\n%\n% This function takes a mesh and local reference frames (LRFs) for a set of\n% keypoints as an input, and generate RoPS feature descriptors for the\n% keypoints as an output. An illustration is shown in Fig4 in Ref.[1].\n%\n% Arguments : mesh - with vertices and faces \n% neighborSize - the size of neighborhood to define a\n% local surface for a selected keypoint\n% binSize - number of bins for 2D plane partition\n% rotaSize - number of rotations around each coordinate axis\n% LocalFrames - local reference frames corresponding to all\n% keypoints of the input mesh\n\n% Return : RoPS - RoPS feature descriptors corresponding to all\n% keypoints\n%\n% Copyright : This code is written by Yulan Guo {yulan.guo@nudt.edu.cn}, NUDT. \n% The code may be used, modified and distributed for research purposes with\n% acknowledgement of the author and inclusion this copyright information.\n%References:\n% [1] Yulan Guo, Ferdous Sohel, Mohammed Bennamoun, Min Lu, Jianwei Wan. \n% Rotational Projection Statistics for 3D Local Surface Description and Object Recognition. \n% Internation Journal of Computer Vision. 2013, 105 (1), 63-86\n% [2] Yulan Guo, Mohammed Bennamoun, Ferdous A Sohel, Min Lu, Jianwei Wan. \n% 3D Object Recognition in Cluttered Scenes with Local Surface Features: A Survey. \n% IEEE Transactions on Pattern Analysis and Machine Intelligence,2014\n%\n% Disclaimer: This code is provided as is without any warranty.\n\n%%%%%%%%%%%% parallel computing to accelerate.\np = gcp('nocreate'); % If no pool, do not create new one.\nif isempty(p) % if exists no parallel computing handle, create one.\n poolsize = parpool;\n % disp('Create a Parallel Computing Pool to accelarate process' );\nelse\n poolsize = p.NumWorkers;\n % disp(sprintf( 'Parpool has %d workers', poolsize) );\nend\n\nkeypntIdx = mesh.keypntIdx;\n% BucketSize = floor(length(mesh.vertices)/100);\n% kdtreeVertices = KDTreeSearcher(mesh.vertices,'Distance','euclidean','BucketSize',BucketSize);\n% BucketSize = floor(length(mesh.vertices)/100);\nkdtreeVertices = KDTreeSearcher(mesh.vertices,'Distance','euclidean');\n\ninterval = pi/2/rotaSize;\nparfor i = 1:length(keypntIdx)\n %obtain the neighboring point of a keypoint\n keypnt = mesh.vertices(keypntIdx(i),:);\n [neighborIdx2,neighborDis]= rangesearch(kdtreeVertices,keypnt,neighborSize); \n neighborIdx2 = cell2mat(neighborIdx2);\n neighborIdx = neighborIdx2(2:end);\n neighbNum = length(neighborIdx);\n if neighbNum<=1\n RoPSs{i,1} = ones(rotaSize*45,1)/sum(ones(rotaSize*45,1));\n continue;\n end\n\n %transfom the neighboring point to the local reference frame (LRF) \n rotation = LocalFrames{i};\n neighbor = [];\n for j=1:neighbNum\n neighbor(j,:) = (mesh.vertices(neighborIdx(j),:)-mesh.vertices(keypntIdx(i),:))*inv(rotation);\n end\n \n RoPS = [];\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %calculate the sub-feature of the keypoint along the Z axis\n for rotaIdx = 1:rotaSize\n rotaAngle = (rotaIdx-1)*interval + interval/2;\n R = [cos(rotaAngle) sin(rotaAngle) 0; -sin(rotaAngle) cos(rotaAngle) 0; 0 0 1]';\n rotaNeighbor = neighbor*R;\n %projection on the XY plane \n projNeighborXY = [rotaNeighbor(:,1),rotaNeighbor(:,2)];\n histTemp = subRoPSFunc(projNeighborXY,binSize);\n RoPS = [RoPS,histTemp]; \n %projection on the XZ plane \n projNeighborXZ = [rotaNeighbor(:,1),rotaNeighbor(:,3)];\n histTemp = subRoPSFunc(projNeighborXZ,binSize);\n RoPS = [RoPS,histTemp];\n %projection on the YZ plane \n projNeighborYZ = [rotaNeighbor(:,2),rotaNeighbor(:,3)];\n histTemp = subRoPSFunc(projNeighborYZ,binSize);\n RoPS = [RoPS,histTemp];\n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %calculate the sub-feature of the keypoint along the Y axis\n for rotaIdx = 1:rotaSize\n rotaAngle = (rotaIdx-1)*interval + interval/2;\n R = [cos(rotaAngle) 0 sin(rotaAngle); 0 1 0 ;-sin(rotaAngle) 0 cos(rotaAngle)]'; \n rotaNeighbor = neighbor*R; \n %projection on the XY plane \n projNeighborXY = [rotaNeighbor(:,1),rotaNeighbor(:,2)];\n histTemp = subRoPSFunc(projNeighborXY,binSize);\n RoPS = [RoPS,histTemp]; \n %projection on the XZ plane \n projNeighborXZ = [rotaNeighbor(:,1),rotaNeighbor(:,3)];\n histTemp = subRoPSFunc(projNeighborXZ,binSize);\n RoPS = [RoPS,histTemp];\n %projection on the YZ plane \n projNeighborYZ = [rotaNeighbor(:,2),rotaNeighbor(:,3)];\n histTemp = subRoPSFunc(projNeighborYZ,binSize);\n RoPS = [RoPS,histTemp];\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %calculate the sub-feature of the keypoint along the X axis\n for rotaIdx = 1:rotaSize\n rotaAngle = (rotaIdx-1)*interval + interval/2;\n R = [1,0,0; 0,cos(rotaAngle),sin(rotaAngle); 0, -sin(rotaAngle), cos(rotaAngle)]';\n rotaNeighbor = neighbor*R;\n %projection on the XY plane \n projNeighborXY = [rotaNeighbor(:,1),rotaNeighbor(:,2)];\n histTemp = subRoPSFunc(projNeighborXY,binSize);\n RoPS = [RoPS,histTemp]; \n %projection on the XZ plane \n projNeighborXZ = [rotaNeighbor(:,1),rotaNeighbor(:,3)];\n histTemp = subRoPSFunc(projNeighborXZ,binSize);\n RoPS = [RoPS,histTemp];\n %projection on the YZ plane \n projNeighborYZ = [rotaNeighbor(:,2),rotaNeighbor(:,3)];\n histTemp = subRoPSFunc(projNeighborYZ,binSize);\n RoPS = [RoPS,histTemp];\n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n RoPSs{i,1} = (RoPS)'/sum(RoPS);\nend\n\n\n\n\n\n", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/RoPSMatcher/RoPS Toolbox2/RoPSFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3677166888935524}} {"text": "function segment_length = p14_boundary_segment_length ( segment_index, h )\n\n%*****************************************************************************80\n%\n%% P14_BOUNDARY_SEGMENT_LENGTH returns boundary segment lengths in problem 14.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer SEGMENT_INDEX, the index of one of the boundary segments.\n%\n% Input, real H, the suggested spacing between points.\n%\n% Output, integer SEGMENT_LENGTH, the number of points in the segment.\n%\n n1 = 90;\n n2 = 11;\n \n v1 = [ ...\n 316.43027, 404.47559; ...\n 291.04946, 400.70917; ...\n 265.16504, 409.77890; ...\n 241.46794, 402.40310; ...\n 216.55145, 396.52064; ...\n 163.28492, 411.37102; ...\n 142.81752, 391.16355; ...\n 111.95404, 346.70264; ...\n 100.03538, 325.72710; ...\n 103.98723, 302.51587; ...\n 128.72978, 285.72802; ...\n 147.49111, 266.23345; ...\n 196.65261, 242.24055; ...\n 213.56835, 221.67192; ...\n 226.49969, 198.09326; ...\n 248.37126, 183.50473; ...\n 262.21952, 165.39102; ...\n 278.42330, 149.91715; ...\n 300.71846, 145.82601; ...\n 311.12698, 166.71094; ...\n 326.66315, 184.58335; ...\n 359.78574, 225.48049; ...\n 357.08892, 252.88958; ...\n 358.76685, 285.34403; ...\n 361.50834, 303.71287; ...\n 371.68926, 314.92452; ...\n 380.49890, 324.58632; ...\n 396.37634, 328.88990; ...\n 412.59116, 327.25238; ...\n 425.48394, 315.28623; ...\n 435.84305, 302.44664; ...\n 458.34025, 297.55121; ...\n 479.66439, 288.99238; ...\n 493.09812, 270.20636; ...\n 518.87309, 264.56427; ...\n 547.18014, 268.18846; ...\n 600.49708, 240.62570; ...\n 625.96183, 238.40347; ...\n 633.90530, 260.70629; ...\n 621.50451, 285.88914; ...\n 576.87224, 322.14121; ...\n 570.51915, 348.85423; ...\n 567.16400, 378.24075; ...\n 558.00668, 406.86552; ...\n 565.19008, 435.75599; ...\n 567.56437, 465.33407; ...\n 550.87626, 490.96358; ...\n 532.98174, 515.84491; ...\n 500.66817, 551.89078; ...\n 478.75120, 562.17222; ...\n 430.03371, 583.94286; ...\n 401.20454, 587.69910; ...\n 368.32214, 581.10110; ...\n 354.26303, 585.86085; ...\n 346.75200, 601.10367; ...\n 332.85137, 628.74602; ...\n 308.02188, 645.84180; ...\n 295.52344, 647.18525; ...\n 286.51519, 651.60328; ...\n 285.98846, 662.07339; ...\n 298.93455, 665.66316; ...\n 301.70226, 682.79570; ...\n 278.65857, 689.63850; ...\n 266.25737, 712.11005; ...\n 287.28701, 732.77147; ...\n 318.19548, 736.85151; ...\n 343.83067, 753.60957; ...\n 375.53164, 758.35231; ...\n 405.73444, 768.98687; ...\n 406.33873, 785.59001; ...\n 378.35436, 789.44240; ...\n 350.02151, 795.02238; ...\n 338.68030, 788.87325; ...\n 325.67930, 786.10177; ...\n 319.05995, 798.04657; ...\n 301.78158, 795.34254; ...\n 280.69272, 773.86634; ...\n 254.55844, 758.02898; ...\n 234.07759, 737.42090; ...\n 218.38337, 711.41500; ...\n 220.99086, 682.17833; ...\n 224.50640, 651.96297; ...\n 240.25971, 631.36117; ...\n 259.86174, 612.60253; ...\n 291.85381, 556.70385; ...\n 315.52139, 537.56387; ...\n 341.63663, 520.12519; ...\n 351.37130, 458.75372; ...\n 349.33183, 431.31454; ...\n 328.80465, 412.43055 ]';\n v2 = [ ...\n 238.64853, 266.58978; ...\n 235.14026, 287.95183; ...\n 238.20736, 303.46785; ...\n 250.13902, 303.71290; ...\n 258.51675, 297.46973; ...\n 274.55300, 291.27357; ...\n 284.66230, 280.72063; ...\n 279.73288, 267.83455; ...\n 270.68478, 255.55440; ...\n 255.73801, 249.16872; ...\n 241.72690, 256.73448 ]';\n\n if ( h <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P14_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n fprintf ( 1, ' Nonpositive H = %f\\n', h );\n error ( 'P14_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n end\n\n if ( segment_index == 1 )\n\n length = polyloop_length_nd ( 2, n1, v1 ) ;\n\n elseif ( segment_index == 2 )\n\n length = polyloop_length_nd ( 2, n2, v2 );\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P14_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n fprintf ( 1, ' Illegal SEGMENT_INDEX = %d\\n', segment_index );\n error ( 'P14_BOUNDARY_SEGMENT_LENGTH - Fatal error!' );\n\n end\n\n n = round ( length / h );\n\n segment_length = n;\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/test_triangulation/p14_boundary_segment_length.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3675893907299582}} {"text": "function [A, W] = fpica(X, whiteningMatrix, dewhiteningMatrix, approach, ...\n numOfIC, g, finetune, a1, a2, myy, stabilization, ...\n epsilon, maxNumIterations, maxFinetune, initState, ...\n guess, sampleSize, displayMode, displayInterval, ...\n s_verbose);\n%FPICA - Fixed point ICA. Main algorithm of FASTICA.\n%\n% [A, W] = fpica(whitesig, whiteningMatrix, dewhiteningMatrix, approach,\n% numOfIC, g, finetune, a1, a2, mu, stabilization, epsilon,\n% maxNumIterations, maxFinetune, initState, guess, sampleSize,\n% displayMode, displayInterval, verbose);\n%\n% Perform independent component analysis using Hyvarinen's fixed point\n% algorithm. Outputs an estimate of the mixing matrix A and its inverse W.\n%\n% whitesig :the whitened data as row vectors\n% whiteningMatrix :can be obtained with function whitenv\n% dewhiteningMatrix :can be obtained with function whitenv\n% approach [ 'symm' | 'defl' ] :the approach used (deflation or symmetric)\n% numOfIC [ 0 - Dim of whitesig ] :number of independent components estimated\n% g [ 'pow3' | 'tanh' | :the nonlinearity used\n% 'gaus' | 'skew' ]\n% finetune [same as g + 'off'] :the nonlinearity used in finetuning.\n% a1 :parameter for tuning 'tanh'\n% a2 :parameter for tuning 'gaus'\n% mu :step size in stabilized algorithm\n% stabilization [ 'on' | 'off' ] :if mu < 1 then automatically on\n% epsilon :stopping criterion\n% maxNumIterations :maximum number of iterations\n% maxFinetune :maximum number of iteretions for finetuning\n% initState [ 'rand' | 'guess' ] :initial guess or random initial state. See below\n% guess :initial guess for A. Ignored if initState = 'rand'\n% sampleSize [ 0 - 1 ] :percentage of the samples used in one iteration\n% displayMode [ 'signals' | 'basis' | :plot running estimate\n% 'filters' | 'off' ]\n% displayInterval :number of iterations we take between plots\n% verbose [ 'on' | 'off' ] :report progress in text format\n%\n% EXAMPLE\n% [E, D] = pcamat(vectors);\n% [nv, wm, dwm] = whitenv(vectors, E, D);\n% [A, W] = fpica(nv, wm, dwm);\n%\n%\n% This function is needed by FASTICA and FASTICAG\n%\n% See also FASTICA, FASTICAG, WHITENV, PCAMAT\n\n% @(#)$Id: fpica.m,v 1.7 2005/06/16 12:52:55 jarmo Exp $\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Global variable for stopping the ICA calculations from the GUI\nglobal g_FastICA_interrupt;\nif isempty(g_FastICA_interrupt)\n clear global g_FastICA_interrupt;\n interruptible = 0;\nelse\n interruptible = 1;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Default values\n\nif nargin < 3, error('Not enough arguments!'); end\n[vectorSize, numSamples] = size(X);\nif nargin < 20, s_verbose = 'on'; end\nif nargin < 19, displayInterval = 1; end\nif nargin < 18, displayMode = 'on'; end\nif nargin < 17, sampleSize = 1; end\nif nargin < 16, guess = 1; end\nif nargin < 15, initState = 'rand'; end\nif nargin < 14, maxFinetune = 100; end\nif nargin < 13, maxNumIterations = 1000; end\nif nargin < 12, epsilon = 0.0001; end\nif nargin < 11, stabilization = 'on'; end\nif nargin < 10, myy = 1; end\nif nargin < 9, a2 = 1; end\nif nargin < 8, a1 = 1; end\nif nargin < 7, finetune = 'off'; end\nif nargin < 6, g = 'pow3'; end\nif nargin < 5, numOfIC = vectorSize; end % vectorSize = Dim\nif nargin < 4, approach = 'defl'; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the data\n\nif ~isreal(X)\n error('Input has an imaginary part.');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the value for verbose\n\nswitch lower(s_verbose)\n case 'on'\n b_verbose = 1;\n case 'off'\n b_verbose = 0;\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\\n', s_verbose));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the value for approach\n\nswitch lower(approach)\n case 'symm'\n approachMode = 1;\n case 'defl'\n approachMode = 2;\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''approach''\\n', approach));\nend\nif b_verbose, fprintf('Used approach [ %s ].\\n', approach); end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the value for numOfIC\n\nif vectorSize < numOfIC\n error('Must have numOfIC <= Dimension!');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the sampleSize\nif sampleSize > 1\n sampleSize = 1;\n if b_verbose\n fprintf('Warning: Setting ''sampleSize'' to 1.\\n');\n end\nelseif sampleSize < 1\n if (sampleSize * numSamples) < 1000\n sampleSize = min(1000/numSamples, 1);\n if b_verbose\n fprintf('Warning: Setting ''sampleSize'' to %0.3f (%d samples).\\n', ...\n sampleSize, floor(sampleSize * numSamples));\n end\n end\nend\nif b_verbose\n if b_verbose & (sampleSize < 1)\n fprintf('Using about %0.0f%% of the samples in random order in every step.\\n',sampleSize*100);\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the value for nonlinearity.\n\nswitch lower(g)\n case 'pow3'\n gOrig = 10;\n case 'tanh'\n gOrig = 20;\n case {'gaus', 'gauss'}\n gOrig = 30;\n case 'skew'\n gOrig = 40;\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''g''\\n', g));\nend\nif sampleSize ~= 1\n gOrig = gOrig + 2;\nend\nif myy ~= 1\n gOrig = gOrig + 1;\nend\n\nif b_verbose,\n fprintf('Used nonlinearity [ %s ].\\n', g);\nend\n\nfinetuningEnabled = 1;\nswitch lower(finetune)\n case 'pow3'\n gFine = 10 + 1;\n case 'tanh'\n gFine = 20 + 1;\n case {'gaus', 'gauss'}\n gFine = 30 + 1;\n case 'skew'\n gFine = 40 + 1;\n case 'off'\n if myy ~= 1\n gFine = gOrig;\n else\n gFine = gOrig + 1;\n end\n finetuningEnabled = 0;\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''finetune''\\n', ...\n finetune));\nend\n\nif b_verbose & finetuningEnabled\n fprintf('Finetuning enabled (nonlinearity: [ %s ]).\\n', finetune);\nend\n\nswitch lower(stabilization)\n case 'on'\n stabilizationEnabled = 1;\n case 'off'\n if myy ~= 1\n stabilizationEnabled = 1;\n else\n stabilizationEnabled = 0;\n end\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''stabilization''\\n', ...\n stabilization));\nend\n\nif b_verbose & stabilizationEnabled\n fprintf('Using stabilized algorithm.\\n');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Some other parameters\nmyyOrig = myy;\n% When we start fine-tuning we'll set myy = myyK * myy\nmyyK = 0.01;\n% How many times do we try for convergence until we give up.\nfailureLimit = 5;\n\n\nusedNlinearity = gOrig;\nstroke = 0;\nnotFine = 1;\nlong = 0;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the value for initial state.\n\nswitch lower(initState)\n case 'rand'\n initialStateMode = 0;\n case 'guess'\n if size(guess,1) ~= size(whiteningMatrix,2)\n initialStateMode = 0;\n if b_verbose\n fprintf('Warning: size of initial guess is incorrect. Using random initial guess.\\n');\n end\n else\n initialStateMode = 1;\n if size(guess,2) < numOfIC\n if b_verbose\n fprintf('Warning: initial guess only for first %d components. Using random initial guess for others.\\n', size(guess,2));\n end\n guess(:, size(guess, 2) + 1:numOfIC) = ...\n rand(vectorSize,numOfIC-size(guess,2))-.5;\n elseif size(guess,2)>numOfIC\n guess=guess(:,1:numOfIC);\n fprintf('Warning: Initial guess too large. The excess column are dropped.\\n');\n end\n if b_verbose, fprintf('Using initial guess.\\n'); end\n end\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''initState''\\n', initState));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Checking the value for display mode.\n\nswitch lower(displayMode)\n case {'off', 'none'}\n usedDisplay = 0;\n case {'on', 'signals'}\n usedDisplay = 1;\n if (b_verbose & (numSamples > 10000))\n fprintf('Warning: Data vectors are very long. Plotting may take long time.\\n');\n end\n if (b_verbose & (numOfIC > 25))\n fprintf('Warning: There are too many signals to plot. Plot may not look good.\\n');\n end\n case 'basis'\n usedDisplay = 2;\n if (b_verbose & (numOfIC > 25))\n fprintf('Warning: There are too many signals to plot. Plot may not look good.\\n');\n end\n case 'filters'\n usedDisplay = 3;\n if (b_verbose & (vectorSize > 25))\n fprintf('Warning: There are too many signals to plot. Plot may not look good.\\n');\n end\n otherwise\n error(sprintf('Illegal value [ %s ] for parameter: ''displayMode''\\n', displayMode));\nend\n\n% The displayInterval can't be less than 1...\nif displayInterval < 1\n displayInterval = 1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif b_verbose, fprintf('Starting ICA calculation...\\n'); end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SYMMETRIC APPROACH\nif approachMode == 1,\n \n % set some parameters more...\n usedNlinearity = gOrig;\n stroke = 0;\n notFine = 1;\n long = 0;\n \n A = zeros(vectorSize, numOfIC); % Dewhitened basis vectors.\n if initialStateMode == 0\n % Take random orthonormal initial vectors.\n B = orth (randn (vectorSize, numOfIC));\n elseif initialStateMode == 1\n % Use the given initial vector as the initial state\n B = whiteningMatrix * guess;\n end\n \n BOld = zeros(size(B));\n BOld2 = zeros(size(B));\n \n % This is the actual fixed-point iteration loop.\n for round = 1:maxNumIterations + 1,\n if round == maxNumIterations + 1,\n fprintf('No convergence after %d steps\\n', maxNumIterations);\n fprintf('Note that the plots are probably wrong.\\n');\n if ~isempty(B)\n % Symmetric orthogonalization.\n B = B * real(inv(B' * B)^(1/2));\n \n W = B' * whiteningMatrix;\n A = dewhiteningMatrix * B;\n else\n W = [];\n A = [];\n end\n return;\n end\n \n if (interruptible & g_FastICA_interrupt)\n if b_verbose\n fprintf('\\n\\nCalculation interrupted by the user\\n');\n end\n if ~isempty(B)\n W = B' * whiteningMatrix;\n A = dewhiteningMatrix * B;\n else\n W = [];\n A = [];\n end\n return;\n end\n \n \n % Symmetric orthogonalization.\n B = B * real(inv(B' * B)^(1/2));\n \n % Test for termination condition. Note that we consider opposite\n % directions here as well.\n minAbsCos = min(abs(diag(B' * BOld)));\n minAbsCos2 = min(abs(diag(B' * BOld2)));\n \n if (1 - minAbsCos < epsilon)\n if finetuningEnabled & notFine\n if b_verbose, fprintf('Initial convergence, fine-tuning: \\n'); end;\n notFine = 0;\n usedNlinearity = gFine;\n myy = myyK * myyOrig;\n BOld = zeros(size(B));\n BOld2 = zeros(size(B));\n \n else\n if b_verbose, fprintf('Convergence after %d steps\\n', round); end\n \n % Calculate the de-whitened vectors.\n A = dewhiteningMatrix * B;\n break;\n end\n elseif stabilizationEnabled\n if (~stroke) & (1 - minAbsCos2 < epsilon)\n if b_verbose, fprintf('Stroke!\\n'); end;\n stroke = myy;\n myy = .5*myy;\n if mod(usedNlinearity,2) == 0\n usedNlinearity = usedNlinearity + 1;\n end\n elseif stroke\n myy = stroke;\n stroke = 0;\n if (myy == 1) & (mod(usedNlinearity,2) ~= 0)\n usedNlinearity = usedNlinearity - 1;\n end\n elseif (~long) & (round>maxNumIterations/2)\n if b_verbose, fprintf('Taking long (reducing step size)\\n'); end;\n long = 1;\n myy = .5*myy;\n if mod(usedNlinearity,2) == 0\n usedNlinearity = usedNlinearity + 1;\n end\n end\n end\n \n BOld2 = BOld;\n BOld = B;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Show the progress...\n if b_verbose\n if round == 1\n fprintf('Step no. %d\\n', round);\n else\n fprintf('Step no. %d, change in value of estimate: %.3g \\n', round, 1 - minAbsCos);\n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Also plot the current state...\n switch usedDisplay\n case 1\n if rem(round, displayInterval) == 0,\n % There was and may still be other displaymodes...\n % 1D signals\n icaplot('dispsig',(X'*B)');\n drawnow;\n end\n case 2\n if rem(round, displayInterval) == 0,\n % ... and now there are :-)\n % 1D basis\n A = dewhiteningMatrix * B;\n icaplot('dispsig',A');\n drawnow;\n end\n case 3\n if rem(round, displayInterval) == 0,\n % ... and now there are :-)\n % 1D filters\n W = B' * whiteningMatrix;\n icaplot('dispsig',W);\n drawnow;\n end\n otherwise\n end\n \n switch usedNlinearity\n % pow3\n case 10\n B = (X * (( X' * B) .^ 3)) / numSamples - 3 * B;\n case 11\n % optimoitu - epsilonin kokoisia eroja\n % t�m� on optimoitu koodi, katso vanha koodi esim.\n % aikaisemmista versioista kuten 2.0 beta3\n Y = X' * B;\n Gpow3 = Y .^ 3;\n Beta = sum(Y .* Gpow3);\n D = diag(1 ./ (Beta - 3 * numSamples));\n B = B + myy * B * (Y' * Gpow3 - diag(Beta)) * D;\n case 12\n Xsub=X(:, getSamples(numSamples, sampleSize));\n B = (Xsub * (( Xsub' * B) .^ 3)) / size(Xsub,2) - 3 * B;\n case 13\n % Optimoitu\n Ysub=X(:, getSamples(numSamples, sampleSize))' * B;\n Gpow3 = Ysub .^ 3;\n Beta = sum(Ysub .* Gpow3);\n D = diag(1 ./ (Beta - 3 * size(Ysub', 2)));\n B = B + myy * B * (Ysub' * Gpow3 - diag(Beta)) * D;\n \n % tanh\n case 20\n hypTan = tanh(a1 * X' * B);\n B = X * hypTan / numSamples - ...\n ones(size(B,1),1) * sum(1 - hypTan .^ 2) .* B / numSamples * ...\n a1;\n case 21\n % optimoitu - epsilonin kokoisia\n Y = X' * B;\n hypTan = tanh(a1 * Y);\n Beta = sum(Y .* hypTan);\n D = diag(1 ./ (Beta - a1 * sum(1 - hypTan .^ 2)));\n B = B + myy * B * (Y' * hypTan - diag(Beta)) * D;\n case 22\n Xsub=X(:, getSamples(numSamples, sampleSize));\n hypTan = tanh(a1 * Xsub' * B);\n B = Xsub * hypTan / size(Xsub, 2) - ...\n ones(size(B,1),1) * sum(1 - hypTan .^ 2) .* B / size(Xsub, 2) * a1;\n case 23\n % Optimoitu\n Y = X(:, getSamples(numSamples, sampleSize))' * B;\n hypTan = tanh(a1 * Y);\n Beta = sum(Y .* hypTan);\n D = diag(1 ./ (Beta - a1 * sum(1 - hypTan .^ 2)));\n B = B + myy * B * (Y' * hypTan - diag(Beta)) * D;\n \n % gauss\n case 30\n U = X' * B;\n Usquared=U .^ 2;\n ex = exp(-a2 * Usquared / 2);\n gauss = U .* ex;\n dGauss = (1 - a2 * Usquared) .*ex;\n B = X * gauss / numSamples - ...\n ones(size(B,1),1) * sum(dGauss)...\n .* B / numSamples ;\n case 31\n % optimoitu\n Y = X' * B;\n ex = exp(-a2 * (Y .^ 2) / 2);\n gauss = Y .* ex;\n Beta = sum(Y .* gauss);\n D = diag(1 ./ (Beta - sum((1 - a2 * (Y .^ 2)) .* ex)));\n B = B + myy * B * (Y' * gauss - diag(Beta)) * D;\n case 32\n Xsub=X(:, getSamples(numSamples, sampleSize));\n U = Xsub' * B;\n Usquared=U .^ 2;\n ex = exp(-a2 * Usquared / 2);\n gauss = U .* ex;\n dGauss = (1 - a2 * Usquared) .*ex;\n B = Xsub * gauss / size(Xsub,2) - ...\n ones(size(B,1),1) * sum(dGauss)...\n .* B / size(Xsub,2) ;\n case 33\n % Optimoitu\n Y = X(:, getSamples(numSamples, sampleSize))' * B;\n ex = exp(-a2 * (Y .^ 2) / 2);\n gauss = Y .* ex;\n Beta = sum(Y .* gauss);\n D = diag(1 ./ (Beta - sum((1 - a2 * (Y .^ 2)) .* ex)));\n B = B + myy * B * (Y' * gauss - diag(Beta)) * D;\n \n % skew\n case 40\n B = (X * ((X' * B) .^ 2)) / numSamples;\n case 41\n % Optimoitu\n Y = X' * B;\n Gskew = Y .^ 2;\n Beta = sum(Y .* Gskew);\n D = diag(1 ./ (Beta));\n B = B + myy * B * (Y' * Gskew - diag(Beta)) * D;\n case 42\n Xsub=X(:, getSamples(numSamples, sampleSize));\n B = (Xsub * ((Xsub' * B) .^ 2)) / size(Xsub,2);\n case 43\n % Uusi optimoitu\n Y = X(:, getSamples(numSamples, sampleSize))' * B;\n Gskew = Y .^ 2;\n Beta = sum(Y .* Gskew);\n D = diag(1 ./ (Beta));\n B = B + myy * B * (Y' * Gskew - diag(Beta)) * D;\n \n otherwise\n error('Code for desired nonlinearity not found!');\n end\n end\n \n \n % Calculate ICA filters.\n W = B' * whiteningMatrix;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Also plot the last one...\n switch usedDisplay\n case 1\n % There was and may still be other displaymodes...\n % 1D signals\n icaplot('dispsig',(X'*B)');\n drawnow;\n case 2\n % ... and now there are :-)\n % 1D basis\n icaplot('dispsig',A');\n drawnow;\n case 3\n % ... and now there are :-)\n % 1D filters\n icaplot('dispsig',W);\n drawnow;\n otherwise\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DEFLATION APPROACH\nif approachMode == 2\n \n B = zeros(vectorSize);\n \n % The search for a basis vector is repeated numOfIC times.\n round = 1;\n \n numFailures = 0;\n \n while round <= numOfIC,\n myy = myyOrig;\n usedNlinearity = gOrig;\n stroke = 0;\n notFine = 1;\n long = 0;\n endFinetuning = 0;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Show the progress...\n if b_verbose, fprintf('IC %d ', round); end\n \n % Take a random initial vector of lenght 1 and orthogonalize it\n % with respect to the other vectors.\n if initialStateMode == 0\n w = randn (vectorSize, 1);\n elseif initialStateMode == 1\n w=whiteningMatrix*guess(:,round);\n end\n w = w - B * B' * w; %orthogonalization - B is the previous w\n w = w / norm(w);\n \n wOld = zeros(size(w));\n wOld2 = zeros(size(w));\n \n % This is the actual fixed-point iteration loop.\n % for i = 1 : maxNumIterations + 1\n i = 1;\n gabba = 1;\n while i <= maxNumIterations + gabba\n if (usedDisplay > 0)\n drawnow;\n end\n if (interruptible & g_FastICA_interrupt)\n if b_verbose\n fprintf('\\n\\nCalculation interrupted by the user\\n');\n end\n return;\n end\n \n % Project the vector into the space orthogonal to the space\n % spanned by the earlier found basis vectors. Note that we can do\n % the projection with matrix B, since the zero entries do not\n % contribute to the projection.\n w = w - B * B' * w;\n w = w / norm(w);\n \n if notFine\n if i == maxNumIterations + 1\n if b_verbose\n fprintf('\\nComponent number %d did not converge in %d iterations.\\n', round, maxNumIterations);\n end\n round = round - 1;\n numFailures = numFailures + 1;\n if numFailures > failureLimit\n if b_verbose\n fprintf('Too many failures to converge (%d). Giving up.\\n', numFailures);\n end\n if round == 0\n A=[];\n W=[];\n end\n return;\n end\n % numFailures > failurelimit\n break;\n end\n % i == maxNumIterations + 1\n else\n % if notFine\n if i >= endFinetuning\n wOld = w; % So the algorithm will stop on the next test...\n end\n end\n % if notFine\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Show the progress...\n if b_verbose, fprintf('.'); end;\n \n \n % Test for termination condition. Note that the algorithm has\n % converged if the direction of w and wOld is the same, this\n % is why we test the two cases.\n if norm(w - wOld) < epsilon | norm(w + wOld) < epsilon\n if finetuningEnabled & notFine\n if b_verbose, fprintf('Initial convergence, fine-tuning: '); end;\n notFine = 0;\n gabba = maxFinetune;\n wOld = zeros(size(w));\n wOld2 = zeros(size(w));\n usedNlinearity = gFine;\n myy = myyK * myyOrig;\n \n endFinetuning = maxFinetune + i;\n \n else\n numFailures = 0;\n % Save the vector\n B(:, round) = w;\n \n % Calculate the de-whitened vector.\n A(:,round) = dewhiteningMatrix * w;\n % Calculate ICA filter.\n W(round,:) = w' * whiteningMatrix;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Show the progress...\n if b_verbose, fprintf('computed ( %d steps ) \\n', i); end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Also plot the current state...\n switch usedDisplay\n case 1\n if rem(round, displayInterval) == 0,\n % There was and may still be other displaymodes...\n % 1D signals\n temp = X'*B;\n icaplot('dispsig',temp(:,1:numOfIC)');\n drawnow;\n end\n case 2\n if rem(round, displayInterval) == 0,\n % ... and now there are :-)\n % 1D basis\n icaplot('dispsig',A');\n drawnow;\n end\n case 3\n if rem(round, displayInterval) == 0,\n % ... and now there are :-)\n % 1D filters\n icaplot('dispsig',W);\n drawnow;\n end\n end\n % switch usedDisplay\n break; % IC ready - next...\n end\n %if finetuningEnabled & notFine\n elseif stabilizationEnabled\n if (~stroke) & (norm(w - wOld2) < epsilon | norm(w + wOld2) < ...\n epsilon)\n stroke = myy;\n if b_verbose, fprintf('Stroke!'); end;\n myy = .5*myy;\n if mod(usedNlinearity,2) == 0\n usedNlinearity = usedNlinearity + 1;\n end\n elseif stroke\n myy = stroke;\n stroke = 0;\n if (myy == 1) & (mod(usedNlinearity,2) ~= 0)\n usedNlinearity = usedNlinearity - 1;\n end\n elseif (notFine) & (~long) & (i > maxNumIterations / 2)\n if b_verbose, fprintf('Taking long (reducing step size) '); end;\n long = 1;\n myy = .5*myy;\n if mod(usedNlinearity,2) == 0\n usedNlinearity = usedNlinearity + 1;\n end\n end\n end\n \n wOld2 = wOld;\n wOld = w;\n \n switch usedNlinearity\n % pow3\n case 10\n w = (X * ((X' * w) .^ 3)) / numSamples - 3 * w;\n case 11\n EXGpow3 = (X * ((X' * w) .^ 3)) / numSamples;\n Beta = w' * EXGpow3;\n w = w - myy * (EXGpow3 - Beta * w) / (3 - Beta);\n case 12\n Xsub=X(:,getSamples(numSamples, sampleSize));\n w = (Xsub * ((Xsub' * w) .^ 3)) / size(Xsub, 2) - 3 * w;\n case 13\n Xsub=X(:,getSamples(numSamples, sampleSize));\n EXGpow3 = (Xsub * ((Xsub' * w) .^ 3)) / size(Xsub, 2);\n Beta = w' * EXGpow3;\n w = w - myy * (EXGpow3 - Beta * w) / (3 - Beta);\n % tanh\n case 20\n hypTan = tanh(a1 * X' * w);\n w = (X * hypTan - a1 * sum(1 - hypTan .^ 2)' * w) / numSamples;\n case 21\n hypTan = tanh(a1 * X' * w);\n Beta = w' * X * hypTan;\n w = w - myy * ((X * hypTan - Beta * w) / ...\n (a1 * sum((1-hypTan .^2)') - Beta));\n case 22\n Xsub=X(:,getSamples(numSamples, sampleSize));\n hypTan = tanh(a1 * Xsub' * w);\n w = (Xsub * hypTan - a1 * sum(1 - hypTan .^ 2)' * w) / size(Xsub, 2);\n case 23\n Xsub=X(:,getSamples(numSamples, sampleSize));\n hypTan = tanh(a1 * Xsub' * w);\n Beta = w' * Xsub * hypTan;\n w = w - myy * ((Xsub * hypTan - Beta * w) / ...\n (a1 * sum((1-hypTan .^2)') - Beta));\n % gauss\n case 30\n % This has been split for performance reasons.\n u = X' * w;\n u2=u.^2;\n ex=exp(-a2 * u2/2);\n gauss = u.*ex;\n dGauss = (1 - a2 * u2) .*ex;\n w = (X * gauss - sum(dGauss)' * w) / numSamples;\n case 31\n u = X' * w;\n u2=u.^2;\n ex=exp(-a2 * u2/2);\n gauss = u.*ex;\n dGauss = (1 - a2 * u2) .*ex;\n Beta = w' * X * gauss;\n w = w - myy * ((X * gauss - Beta * w) / ...\n (sum(dGauss)' - Beta));\n case 32\n Xsub=X(:,getSamples(numSamples, sampleSize));\n u = Xsub' * w;\n u2=u.^2;\n ex=exp(-a2 * u2/2);\n gauss = u.*ex;\n dGauss = (1 - a2 * u2) .*ex;\n w = (Xsub * gauss - sum(dGauss)' * w) / size(Xsub, 2);\n case 33\n Xsub=X(:,getSamples(numSamples, sampleSize));\n u = Xsub' * w;\n u2=u.^2;\n ex=exp(-a2 * u2/2);\n gauss = u.*ex;\n dGauss = (1 - a2 * u2) .*ex;\n Beta = w' * Xsub * gauss;\n w = w - myy * ((Xsub * gauss - Beta * w) / ...\n (sum(dGauss)' - Beta));\n % skew\n case 40\n w = (X * ((X' * w) .^ 2)) / numSamples;\n case 41\n EXGskew = (X * ((X' * w) .^ 2)) / numSamples;\n Beta = w' * EXGskew;\n w = w - myy * (EXGskew - Beta*w)/(-Beta);\n case 42\n Xsub=X(:,getSamples(numSamples, sampleSize));\n w = (Xsub * ((Xsub' * w) .^ 2)) / size(Xsub, 2);\n case 43\n Xsub=X(:,getSamples(numSamples, sampleSize));\n EXGskew = (Xsub * ((Xsub' * w) .^ 2)) / size(Xsub, 2);\n Beta = w' * EXGskew;\n w = w - myy * (EXGskew - Beta*w)/(-Beta);\n \n otherwise\n error('Code for desired nonlinearity not found!');\n end\n \n \n% TEST % % % % % % % % % % % % % % % % % % % % % % % % %\ninterval = 1;\nif mod(i,interval)==0\n modifyA =1; %for now...\n nx = 20;\n ny = 20;\n sigfix = 3.7/4; % sig of PSF...\n \n if exist ('modifyA','var')\n if modifyA == 1\n % fprintf ('Modifying matrix conevrgence of w...')\n Atemp = dewhiteningMatrix * w;\n% signum = 1;\n% if abs(min(Atemp))>max(Atemp) %or sum(Atemp)<0...?\n% signum = -1;\n% end\n% if abs(min(Atemp))>max(Atemp) %or sum(Atemp)<0...?\n% Atemp = -Atemp;\n% end\n absA = abs(Atemp);\n maxA = max(absA);\n \n gf = (gauss2d([nx ny],[nx/2,ny/2],sigfix,maxA));\n Aconv = (conv2(gf, reshape (Atemp, nx, ny),'same')).^5;\n Atemp = reshape(Aconv,ny*ny,1);\n \n% [x_mu, y_mu, sig] = fitgauss2d(reshape(absA, nx, ny),sigfix); %fit to abs...\n% Atemp = (Atemp + signum * reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1))/2;\n % Atemp = reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1);\n end\n end\n w = whiteningMatrix*Atemp;\nend\n \n% TEST % % % % % % % % % % % % % % % % % % % % % % % % %\n\n% %%% TEST version old %%%%%%%%%\n% if mod(i,5)==0\n% modifyA =1; %for now...\n% nx = 20;\n% ny = 20;\n% sigfix = 3.7/4; % sig of PSF...\n% \n% if exist ('modifyA','var')\n% if modifyA == 1\n% % fprintf ('Modifying matrix conevrgence of w...')\n% Atemp = dewhiteningMatrix * w;\n% if abs(min(Atemp))>max(Atemp) %or sum(Atemp)<0...?\n% Atemp = -Atemp;\n% end\n% [x_mu, y_mu, sig] = fitgauss2d(reshape(Atemp, nx, ny),sigfix);\n% maxA = max(abs(Atemp));\n% Atemp = (Atemp + reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1))/2;\n% % Atemp = reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1);\n% end\n% end\n% w = whiteningMatrix*Atemp;\n% \n% %%% TEST version old %%%%%%%%%\n\n% Normalize the new w.\n w = w / norm(w); \n i = i + 1;\n end\n round = round + 1;\n end\n if b_verbose, fprintf('Done.\\n'); end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Also plot the ones that may not have been plotted.\n if (usedDisplay > 0) & (rem(round-1, displayInterval) ~= 0)\n switch usedDisplay\n case 1\n % There was and may still be other displaymodes...\n % 1D signals\n temp = X'*B;\n icaplot('dispsig',temp(:,1:numOfIC)');\n drawnow;\n case 2\n % ... and now there are :-)\n % 1D basis\n icaplot('dispsig',A');\n drawnow;\n case 3\n % ... and now there are :-)\n % 1D filters\n icaplot('dispsig',W);\n drawnow;\n otherwise\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% In the end let's check the data for some security\nif ~isreal(A)\n if b_verbose, fprintf('Warning: removing the imaginary part from the result.\\n'); end\n A = real(A);\n W = real(W);\nend\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Subfunction\n% Calculates tanh simplier and faster than Matlab tanh.\nfunction y=tanh(x)\ny = 1 - 2 ./ (exp(2 * x) + 1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Samples = getSamples(max, percentage)\nSamples = find(rand(1, max) < percentage);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/ica/fpica_091123.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3675893907299582}} {"text": "function [UTC1,UTC2]=UT12UTC(UT11,UT12,deltaUTCUT1)\n%%UT12UTC Convert from UT1, which is a nonuniform timescale based on the\n% rotation rate of the Earth, to Coordinated Universal Time (UTC),\n% which is the \"standard\" time that pretty much every country uses\n% (the time zone is that of the United Kingdom) including\n% leapseconds. Due to the use of leapseconds, UT1 is always within\n% 0.9 seconds of UTC.\n%\n%INPUTS: Jul1,Jul2 Two parts of a Julian date given in UTC. The units of\n% the date are days. The full date is the sum of both\n% terms. The date is broken into two parts to provide\n% more bits of precision. It does not matter how the date\n% is split.\n% deltaUTCUT1 An optional parameter specifying the offset between UTC\n% and UT1 in seconds. If this parameter is omitted, then\n% the value of the function getEOP will be used and\n% iterations will be performed, because the correct\n% tabulated value is given in UTC, not UT1.\n%\n%OUTPUTS: Jul1,Jul2 Two parts of a pseudo-Julian date in UTC with units of\n% Julian days.\n%\n%This essentially just adds deltaUTCUT1 from the given UTC date, or\n%looks up deltaUTCUT1 using the getEOP function and then adds\n%deltaUTCUT1. The \"looking up\" step involves an interation, since the value\n%of deltaUTCUT1 is tabulated by UTC, which is unknown. To know the peroper\n%amount to subtract from the pseudo-Julian day, the function leapSecsOnDay\n%is used to determine whether the day contains a leapsecond. As that\n%function is also tabulated by UTC, an iteration is necessary even if\n%deltaUTCUT1 is given. Unlike the function iauUtcut1 in the International\n%Astronomical Union's Standards of Fundamental Astronomy library, this does\n%not try to deal with deltaUTCUT1 being off by a second near a leapsecond\n%as it was noticed that the \"corrections\" made in the library make the pair\n%of UTC2UT1 and UT12UTC inconsistent by a second when it is near a\n%leapsecond.\n%\n%Many temporal coordinate systems standards are compared in [1].\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"An Overview of Major Terrestrial, Celestial, and\n% Temporal Coordinate Systems for Target Tracking,\" Formal Report, Naval\n% Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016, 173\n% pages.\n%\n%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The initial estimate of UTC is just UT1. This will be within 0.9 seconds\n%of the correct value.\nUTC1=UT11;\nUTC2=UT12;\n\nfor curIter=1:2\n if(nargin<3)\n [~,~,deltaUTCUT1]=getEOP(UTC1,UTC2);\n end\n \n %Find the number of seconds in the day.\n [year,month,day]=UTC2Cal(UTC1,UTC2,true);\n numSecInDay=24*60*(60+leapSecsOnDay(year,month,day));\n\n %Add preserving precision.\n if(UTC1 length(Inputs)) \n error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n end\n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n elseif strcmp(narglist{jj,2}, '__output')\n if (nextoutput > nargout) \n error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n end\n if (isempty(arglist{ii,2}))\n narglist{jj,2} = 'OK_out';\n else\n narglist{jj,2} = arglist{ii,2};\n end\n\n nextoutput = nextoutput + 1;\n if (minval{jj} == 0) \n NumReqOutputs = NumReqOutputs - 1;\n end\n elseif isstr(arglist{ii,2})\n narglist{jj,2} = arglist{ii,2};\n else\n if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n end\n if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n end\n end\n end\n if ~strcmp(narglist{jj,2},'OK_out') & ~strcmp(narglist{jj,2},'OK_in') \n narglist{jj,2} = arglist{ii,2};\n end\n end\n end\n if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n if strcmp(paramtype{jj}, 'Toggle')\n if (narglist{jj,2} ==0)\n narglist{jj,1} = ''; \n end;\n narglist{jj,2} = ''; \n end;\n if ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n narglist{jj,1} = ''; \n narglist{jj,2} = ''; \n end;\n if strcmp(narglist{jj,2}, '__input')\n if (minval{jj} == 0) % meaning this input is required\n if (nextinput > size(Inputs)) \n error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n else\n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n end\n else % this is an optional input\n if (nextinput <= length(Inputs)) \n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n else \n narglist{jj,1} = '';\n narglist{jj,2} = '';\n end;\n end;\n else \n if strcmp(narglist{jj,2}, '__output')\n if (minval{jj} == 0) % this is a required output\n if (nextoutput > nargout & nargout > 1) \n error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n else\n narglist{jj,2} = 'OK_out';\n nextoutput = nextoutput + 1;\n NumReqOutputs = NumReqOutputs-1;\n end\n else % this is an optional output\n if (nargout - nextoutput >= NumReqOutputs) \n narglist{jj,2} = 'OK_out';\n nextoutput = nextoutput + 1;\n else \n narglist{jj,1} = '';\n narglist{jj,2} = '';\n end;\n end\n end\n end\nend\nif nargout\n varargout = cell(1,nargout);\nelse\n varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'meigen\" '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kmeigen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.36666579842789837}} {"text": "function [text,AIC,BIC]=igarch_display(parameters,ll,vcv,data,p,q,errorType,igarchType,constant)\n% Display parameters, tstats, pvals, log-likelihood and AIC/BIC\n% from estimates of a IGARCH(P,O,Q) produced using igarch\n%\n% USAGE:\n% [TEXT] = igarch_display(PARAMETERS,LL,VCV,DATA,P,Q)\n% [TEXT,AIC,BIC] = igarch_display(PARAMETERS,LL,VCV,DATA,P,Q,ERRORTYPE,IGARCHTYE,CONSTANT)\n%\n% INPUTS:\n% PARAMETERS - A CONSTANT+p+q-1 column vector of parameters with\n% [omega alpha(1) ... alpha(p) beta(1) ... beta(q-1) [nu lambda]]'.\n% LL - The log likelihood at the optimum\n% VCV - Non-robust standard errors (inverse Hessian)\n% DATA - A column of mean zero data\n% P - Positive, scalar integer representing the number of\n% symmetric innovations\n% Q - Non-negative, scalar integer representing the number\n% of lags of conditional variance (0 for ARCH)\n% ERRORTYPE - [OPTIONAL] The error distribution used, valid types are:\n% 'NORMAL' - Gaussian Innovations [DEFAULT]\n% 'STUDENTST' - T distributed errors\n% 'GED' - Generalized Error Distribution\n% 'SKEWT' - Skewed T distribution\n% IGARCHTYPE - [OPTIONAL] The type of variance process, either\n% 1 - Model evolves in absolute values\n% 2 - Model evolves in squares [DEFAULT]\n% CONSTANT - [OPTIONAL] Logical value indicating whether model\n% should include a constant. Default is true\n% (include)\n%\n% OUTPUTS:\n% TEXT - Character matrix with the formatted parameters of the model\n% AIC - Aikake Information Criteria computed from the LL\n% BIC - Schwartz/Bayesian Information Criteria computed from the LL\n%\n% See also IGARCH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 9/1/2005\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETER CHECKING\n%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch nargin\n case 6\n igarchType=2;\n errorType='NORMAL';\n constant = 1;\n case 7\n igarchType=2;\n constant = 1;\n case 8\n constant = 1;\n case 9\n % Nothing\n otherwise\n error('5 to 8 inputs required')\nend\nif isempty(igarchType)\n igarchType=2;\nend\nif isempty(errorType)\n errorType='NORMAL';\nend\nif isempty(constant)\n constant = 1;\nend\n% parameters, N by 1, real\nif any(~isreal(parameters)) || size(parameters,2)~=1\n error('PARAMETERS must be a column vector.')\nend\n% LL\nif ~isscalar(ll) || ~isreal(ll)\n error('LL must be a scalar.')\nend\n% VCV\nif size(vcv,2)~=size(vcv,1) || any(min(eig(vcv))<=0) || size(vcv,1)~=length(parameters)\n error('VCV must be a square positive definite matrix compatible with PARAMETERS.')\nend\n% data\nif any(~isreal(data)) || size(data,2)~=1\n error('DATA must be a T by 1 column vector.')\nend\n% p\nif ~isscalar(p) || p<1 || floor(p)~=p\n error('P must be a postitive scalar integer')\nend\n% q\nif ~isscalar(q) || q<0 || floor(q)~=q\n error('Q must be a positive scalar integer')\nend\n% errorType\nif ~ischar(errorType)\n errorType=[];\nend\nswitch errorType\n case 'NORMAL'\n errorType=1;\n extraP=0;\n case 'STUDENTST'\n errorType=2;\n extraP=1;\n case 'GED'\n errorType=3;\n extraP=1;\n case 'SKEWT'\n errorType=4;\n extraP=2;\n otherwise\n error('ERRORTYPE is not one of the supported distributions')\nend\n% igarchType\nif ~ismember(igarchType,[1 2])\n error('IGARCHTYPE must be either 1 or 2')\nend\nif length(parameters)~=(constant+p+q-1+extraP)\n error('Size of PARAMETERS is not compatible with input P, O, Q')\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETER CHECKING\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\nif igarchType==1\n model_name = ['IAVARCH(' num2str(p) ',' num2str(q) ')'];\nelse\n model_name = ['IGARCH(' num2str(p) ',' num2str(q) ')'];\nend\n\nparameters_text=num2str(parameters,'%4.4f');\nstderr=sqrt(diag(vcv));\nstderr_text=num2str(stderr,'%4.4f');\ntstats=parameters./stderr;\ntstats_text=num2str(tstats,'%4.4f');\npvals=2-2*normcdf(abs(tstats));\npvals_text=num2str(pvals,'%4.4f');\n\n% Add in the extra beta\nfinalBetaPos = constant+p+q;\narchParameters = parameters(constant+1:constant+p+q-1);\nfinalBeta = 1 - sum(archParameters);\n\nn = length(parameters);\n\nparameters_text=[parameters_text(1:finalBetaPos-1,:);\n num2str(finalBeta,'%4.4f');\n parameters_text(finalBetaPos+1:n,:)];\nstderr_text=[stderr_text(1:finalBetaPos-1,:);\n repmat('-',1,size(stderr_text,2));\n stderr_text(finalBetaPos+1:n,:)];\ntstats_text=[tstats_text(1:finalBetaPos-1,:);\n repmat('-',1,size(tstats_text,2));\n tstats_text(finalBetaPos+1:n,:)];\npvals_text=[pvals_text(1:finalBetaPos-1,:);\n repmat('-',1,size(pvals_text,2));\n pvals_text(finalBetaPos+1:n,:)];\n\n\n\n\n\nT=length(data);\nAIC = -ll/T+2*length(parameters)/T;\nBIC = -ll/T+log(T)*length(parameters)/T;\n\n\n\n\n% Format the output\ntext=[];\ntext{1,1}= ' ';\ntext{2,1}= ' ';\ntext{3,1}=repmat('-',1,50);\ntext{4,1}=model_name;\ntext{5,1}=repmat('-',1,50);\ntext{6,1}=' ';\ntext{7,1}=['Loglikelihood: ' sprintf('%1.2f',ll)];\ntext{8,1}=['AIC: ' sprintf('%1.4f',AIC)];\ntext{9,1}=['BIC: ' sprintf('%1.4f',BIC)];\ntext{10,1}=' ';\n\n\nfor i=1:size(text,1);\n disp(text{i,1})\nend\n\n\n% Format the parameter table, need to right align everything\nK=size(parameters_text,1);\nfor i=1:K\n N=size(parameters_text,2);\n if any(parameters_text(i,:)==' ')\n numSpace=sum(parameters_text(i,:)==' ');\n parameters_text(i,:)=[repmat(' ',1,numSpace) parameters_text(i,1:N-numSpace)];\n end\n N=size(stderr_text,2);\n if any(stderr_text(i,:)==' ')\n numSpace=sum(stderr_text(i,:)==' ');\n stderr_text(i,:)=[repmat(' ',1,numSpace) stderr_text(i,1:N-numSpace)];\n end\n N=size(tstats_text,2);\n if any(tstats_text(i,:)==' ')\n numSpace=sum(tstats_text(i,:)==' ');\n tstats_text(i,:)=[repmat(' ',1,numSpace) tstats_text(i,1:N-numSpace)];\n end\n N=size(pvals_text,2);\n if any(pvals_text(i,:)==' ')\n numSpace=sum(pvals_text(i,:)==' ');\n pvals_text(i,:)=[repmat(' ',1,numSpace) pvals_text(i,1:N-numSpace)];\n end\nend\n% Append column labels\nlabels={' Parameters',' Std. Err.',' T-stat',' P-val'};\ncols = {parameters_text,stderr_text,tstats_text,pvals_text};\nfor i=1:length(labels);\n text1=labels{i};\n text2=cols{i};\n maxcols=max(size(text1,2),size(text2,2));\n if size(text1,2)1\n variable_names{index}='nu';\n index=index+1;\nend\nif errorType==4\n variable_names{index}='lambda';\nend\n\n\nmaxVarNameLength=max(cellfun('length',variable_names));\nfor i=1:length(variable_names)\n variable_names{i} = [repmat(' ',1,maxVarNameLength-length(variable_names{i})) variable_names{i}];\nend\nvariable_names=cell2mat(variable_names(:));\n\n% Output the parameters\noutmat=strvcat(' ',variable_names); %#ok<*VCAT>\nfor i=1:4\n outmat=[outmat repmat(' ',size(outmat,1),1) strvcat(labels{i},cols{i})]; %#ok\nend\n\n\ntext2=[];\nfor i=1:length(text)\n text2=strvcat(text2,text{i});\nend\ntext=strvcat(text2,outmat);\n\ndisp(outmat)\n", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/univariate/igarch_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.36666579842789837}} {"text": "function mpc = t_case9_opfv2\n%T_CASE9_OPFV2 Power flow data for 9 bus, 3 generator case, with OPF data.\n% Please see CASEFORMAT for details on the case file format.\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\t30\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\t90\t30\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\t100\t35\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\t125\t50\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\t0\t0\t300\t-300\t1\t100\t1\t250\t90\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t30\t85\t0\t300\t-300\t1\t100\t1\t270\t10\t0\t200\t-30\t30\t-15\t15\t0\t0\t0\t0\t0;\n\t2\t163\t0\t300\t-300\t1\t100\t1\t300\t10\t0\t200\t-20\t20\t-10\t10\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\t0\t250\t250\t0\t0\t1\t-360\t2.48;\n\t4\t5\t0.017\t0.092\t0.158\t0\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\t30\t6\t0\t0.0586\t0\t0\t300\t300\t0\t0\t1\t-360\t360;\n\t6\t7\t0.0119\t0.1008\t0.209\t40\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-2\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\t1\t0\t0\t4\t0\t0\t100\t2500\t200\t5500\t250\t7250;\n\t1\t0\t0\t3\t0\t0\t200\t3000\t300\t5000\t0\t0;\n\t2\t0\t0\t2\t24.035\t-403.5\t0\t0\t0\t0\t0\t0;\n];\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/t/t_case9_opfv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3665097691995436}} {"text": "function [dStates, contactForces] = dynamics_doubleStance(States, Actuators, Parameters)\n% function [dStates, Actuators] = dynamics_doubleStance(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: Double Stance\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 = 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: \nddx = 0; %(m) Foot One horizontal position\nddy = 0; %(m) Foot One vertical position\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,:) = (L2.*Thip.*cos(th1).*cos(th2) - L2.*T1.*cos(th1).*cos(th2) - L2.*T1.*sin(th1).*sin(th2) + L2.*Thip.*sin(th1).*sin(th2) - L1.*L2.*M.*ddy.*cos(th2) + L1.*L2.*M.*ddx.*sin(th2) + L1.*T2.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*Thip.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*T2.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*T2.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*T2.*sin(th1 - th2).*cos(th2).*sin(th1) + L1.*Thip.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*Thip.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*Thip.*sin(th1 - th2).*cos(th2).*sin(th1) + F1.*L1.*L2.*cos(th1).*sin(th2) - F1.*L1.*L2.*cos(th2).*sin(th1) - F2.*L1.*L2.*cos(th1 - th2).*cos(th1).*sin(th2) + F2.*L1.*L2.*cos(th1 - th2).*cos(th2).*sin(th1) - F2.*L1.*L2.*sin(th1 - th2).*cos(th1).*cos(th2) - F2.*L1.*L2.*sin(th1 - th2).*sin(th1).*sin(th2) - 2.*L1.*L2.*M.*dL2.*dth2.*cos(th2).^2 - 2.*L1.*L2.*M.*dL2.*dth2.*sin(th2).^2 + L1.*L2.*M.*ddy.*cos(th1).^2.*cos(th2) + L1.*L2.*M.*g.*cos(th1).^2.*cos(th2) - L1.*L2.*M.*ddx.*cos(th1).^2.*sin(th2) + L1.*L2.*M.*ddy.*cos(th2).*sin(th1).^2 + L1.*L2.*M.*g.*cos(th2).*sin(th1).^2 - L1.*L2.*M.*ddx.*sin(th1).^2.*sin(th2))./(L1.*L2.^2.*M.*(cos(th2).^2 + sin(th2).^2));\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,:) = (L2.*T1.*cos(th2).*sin(th1) - L2.*T1.*cos(th1).*sin(th2) + L2.*Thip.*cos(th1).*sin(th2) - L2.*Thip.*cos(th2).*sin(th1) - F1.*L1.*L2.*sin(th1).*sin(th2) - L1.*L2.*M.*ddx.*cos(th2) - L1.*L2.*M.*ddy.*sin(th2) + L1.*L2.^2.*M.*dth2.^2.*cos(th2).^2 + L1.*L2.^2.*M.*dth2.^2.*sin(th2).^2 + L1.*T2.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*T2.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*T2.*sin(th1 - th2).*cos(th1).*cos(th2) + L1.*Thip.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*Thip.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*Thip.*sin(th1 - th2).*cos(th1).*cos(th2) + L1.*T2.*sin(th1 - th2).*sin(th1).*sin(th2) + L1.*Thip.*sin(th1 - th2).*sin(th1).*sin(th2) - F1.*L1.*L2.*cos(th1).*cos(th2) + F2.*L1.*L2.*cos(th1 - th2).*sin(th1).*sin(th2) - F2.*L1.*L2.*sin(th1 - th2).*cos(th1).*sin(th2) + F2.*L1.*L2.*sin(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*ddx.*cos(th1).^2.*cos(th2) + L1.*L2.*M.*ddx.*cos(th2).*sin(th1).^2 + L1.*L2.*M.*ddy.*cos(th1).^2.*sin(th2) + L1.*L2.*M.*g.*cos(th1).^2.*sin(th2) + L1.*L2.*M.*ddy.*sin(th1).^2.*sin(th2) + L1.*L2.*M.*g.*sin(th1).^2.*sin(th2) + F2.*L1.*L2.*cos(th1 - th2).*cos(th1).*cos(th2))./(L1.*L2.*M.*(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,:) = (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,:) = (L1.*M.*T2.*sin(th2) + L1.*M.*Thip.*sin(th2) + L2.*T1.*m2.*sin(th1) - L2.*Thip.*m2.*sin(th1) - L1.*L2.*M.*ddx.*m2 - L1.*T2.*m2.*cos(th1 - th2).*sin(th1) + L1.*T2.*m2.*sin(th1 - th2).*cos(th1) - L2.*T1.*m2.*cos(th1 - th2).*sin(th2) - L2.*T1.*m2.*sin(th1 - th2).*cos(th2) - L1.*Thip.*m2.*cos(th1 - th2).*sin(th1) + L1.*Thip.*m2.*sin(th1 - th2).*cos(th1) + L2.*Thip.*m2.*cos(th1 - th2).*sin(th2) + L2.*Thip.*m2.*sin(th1 - th2).*cos(th2) - F2.*L1.*L2.*M.*cos(th2) - F1.*L1.*L2.*m2.*cos(th1) + L1.*T2.*m2.*cos(th1 - th2).^2.*sin(th2) + L1.*Thip.*m2.*cos(th1 - th2).^2.*sin(th2) + L1.*T2.*m2.*sin(th1 - th2).^2.*sin(th2) + L1.*Thip.*m2.*sin(th1 - th2).^2.*sin(th2) + L1.*L2.*M.*ddx.*m2.*cos(th1).^2 + L1.*L2.*M.*ddx.*m2.*cos(th2).^2 + L1.*L2.*M.*ddx.*m2.*sin(th1).^2 + L1.*L2.*M.*ddx.*m2.*sin(th2).^2 + F1.*L1.*L2.*m2.*cos(th1 - th2).*cos(th2) + F2.*L1.*L2.*m2.*cos(th1 - th2).*cos(th1) - F1.*L1.*L2.*m2.*sin(th1 - th2).*sin(th2) + F2.*L1.*L2.*m2.*sin(th1 - th2).*sin(th1) - F2.*L1.*L2.*m2.*cos(th1 - th2).^2.*cos(th2) - F2.*L1.*L2.*m2.*sin(th1 - th2).^2.*cos(th2) + L1.*L2.*M.*ddy.*m2.*sin(th1 - th2).*sin(th1).*sin(th2) + L1.*L2.*M.*g.*m2.*sin(th1 - th2).*sin(th1).*sin(th2) - L1.*L2.*M.*ddx.*m2.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*ddy.*m2.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*L2.*M.*ddy.*m2.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*ddy.*m2.*sin(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*g.*m2.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*L2.*M.*g.*m2.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*g.*m2.*sin(th1 - th2).*cos(th1).*cos(th2) - L1.*L2.*M.*ddx.*m2.*cos(th1 - th2).*sin(th1).*sin(th2) + L1.*L2.*M.*ddx.*m2.*sin(th1 - th2).*cos(th1).*sin(th2) - L1.*L2.*M.*ddx.*m2.*sin(th1 - th2).*cos(th2).*sin(th1))./(L1.*L2.*M.*(cos(th2).^2 + sin(th2).^2));\ncontactForces(4,:) = -(L1.*M.*T2.*cos(th2) + L1.*M.*Thip.*cos(th2) + L2.*T1.*m2.*cos(th1) - L2.*Thip.*m2.*cos(th1) + L1.*L2.*M.*ddy.*m2 - L1.*T2.*m2.*cos(th1 - th2).*cos(th1) - L2.*T1.*m2.*cos(th1 - th2).*cos(th2) - L1.*Thip.*m2.*cos(th1 - th2).*cos(th1) + L2.*Thip.*m2.*cos(th1 - th2).*cos(th2) - L1.*T2.*m2.*sin(th1 - th2).*sin(th1) + L2.*T1.*m2.*sin(th1 - th2).*sin(th2) - L1.*Thip.*m2.*sin(th1 - th2).*sin(th1) - L2.*Thip.*m2.*sin(th1 - th2).*sin(th2) + F2.*L1.*L2.*M.*sin(th2) + F1.*L1.*L2.*m2.*sin(th1) + L1.*T2.*m2.*cos(th1 - th2).^2.*cos(th2) + L1.*Thip.*m2.*cos(th1 - th2).^2.*cos(th2) + L1.*T2.*m2.*sin(th1 - th2).^2.*cos(th2) + L1.*Thip.*m2.*sin(th1 - th2).^2.*cos(th2) + F2.*L1.*L2.*m2.*sin(th1 - th2).^2.*sin(th2) - L1.*L2.*M.*ddy.*m2.*cos(th1).^2 - L1.*L2.*M.*ddy.*m2.*cos(th2).^2 - L1.*L2.*M.*g.*m2.*cos(th1).^2 - L1.*L2.*M.*g.*m2.*cos(th2).^2 - L1.*L2.*M.*ddy.*m2.*sin(th1).^2 - L1.*L2.*M.*ddy.*m2.*sin(th2).^2 - L1.*L2.*M.*g.*m2.*sin(th1).^2 - L1.*L2.*M.*g.*m2.*sin(th2).^2 - F1.*L1.*L2.*m2.*cos(th1 - th2).*sin(th2) - F1.*L1.*L2.*m2.*sin(th1 - th2).*cos(th2) - F2.*L1.*L2.*m2.*cos(th1 - th2).*sin(th1) + F2.*L1.*L2.*m2.*sin(th1 - th2).*cos(th1) + F2.*L1.*L2.*m2.*cos(th1 - th2).^2.*sin(th2) + L1.*L2.*M.*ddx.*m2.*sin(th1 - th2).*sin(th1).*sin(th2) + L1.*L2.*M.*ddy.*m2.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*g.*m2.*cos(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*ddx.*m2.*cos(th1 - th2).*cos(th1).*sin(th2) - L1.*L2.*M.*ddx.*m2.*cos(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*ddx.*m2.*sin(th1 - th2).*cos(th1).*cos(th2) + L1.*L2.*M.*ddy.*m2.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*L2.*M.*ddy.*m2.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*L2.*M.*ddy.*m2.*sin(th1 - th2).*cos(th2).*sin(th1) + L1.*L2.*M.*g.*m2.*cos(th1 - th2).*sin(th1).*sin(th2) - L1.*L2.*M.*g.*m2.*sin(th1 - th2).*cos(th1).*sin(th2) + L1.*L2.*M.*g.*m2.*sin(th1 - th2).*cos(th2).*sin(th1))./(L1.*L2.*M.*(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_doubleStance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.3661198875174249}} {"text": "function nbrhood=cosmo_spherical_neighborhood(ds, varargin)\n% computes neighbors for a spherical searchlight\n%\n% nbrhood=cosmo_spherical_neighborhood(ds, opt)\n%\n% Inputs\n% ds a dataset struct, either:\n% - in fmri form (from cosmo_fmri_dataset), when\n% ds.fa has the fields .i, .j and .k\n% - in meeg source form (from cosmo_meeg_dataset),\n% when ds.fa has the field .pos. In this case, the\n% features must have positions that can be\n% converted to a grid.\n% 'radius', r } either use a radius of r, or select\n% 'count', c } approximately c voxels per searchlight\n% Notes:\n% - These two options are mutually exclusive\n% - When using this option for an fmri dataset, the\n% radius r is expressed in voxel units; for an meeg\n% source dataset, the radius r is in whatever units\n% the source dataset uses for the positions\n% 'progress', p show progress every p features (default: 1000)\n%\n% Outputs\n% nbrhood dataset-like struct without .sa or .samples, with:\n% .a dataset attributes, from dataset.a\n% .fa feature attributes with the same fields as fs.fa,\n% and in addition the fields:\n% .nvoxels 1xP number of voxels in each searchlight\n% .radius 1xP radius in voxel units\n% .center_ids 1xP feature center id\n% .neighbors Px1 cell so that center2neighbors{k}==nbrs contains\n% the feature ids of the neighbors of feature k\n% If the dataset has a field ds.fa.inside, then\n% features that are not inside are not included as\n% neighbors in the output\n% .origin Has fields .a and .fa from input dataset\n%\n%\n% Example:\n% ds=cosmo_synthetic_dataset('type','fmri');\n% radius=1; % radius=3 is typical for 'real-world' searchlights\n% nbrhood=cosmo_spherical_neighborhood(ds,'radius',radius,...\n% 'progress',false);\n% cosmo_disp(nbrhood)\n% %|| .a\n% %|| .fdim\n% %|| .labels\n% %|| { 'i' 'j' 'k' }\n% %|| .values\n% %|| { [ 1 2 3 ] [ 1 2 ] [ 1 ] }\n% %|| .vol\n% %|| .mat\n% %|| [ 2 0 0 -3\n% %|| 0 2 0 -3\n% %|| 0 0 2 -3\n% %|| 0 0 0 1 ]\n% %|| .dim\n% %|| [ 3 2 1 ]\n% %|| .xform\n% %|| 'scanner_anat'\n% %|| .fa\n% %|| .nvoxels\n% %|| [ 3 4 3 3 4 3 ]\n% %|| .radius\n% %|| [ 1 1 1 1 1 1 ]\n% %|| .center_ids\n% %|| [ 1 2 3 4 5 6 ]\n% %|| .i\n% %|| [ 1 2 3 1 2 3 ]\n% %|| .j\n% %|| [ 1 1 1 2 2 2 ]\n% %|| .k\n% %|| [ 1 1 1 1 1 1 ]\n% %|| .neighbors\n% %|| { [ 1 4 2 ]\n% %|| [ 2 1 5 3 ]\n% %|| [ 3 2 6 ]\n% %|| [ 4 1 5 ]\n% %|| [ 5 4 2 6 ]\n% %|| [ 6 5 3 ] }\n% %|| .origin\n% %|| .a\n% %|| .fdim\n% %|| .labels\n% %|| { 'i'\n% %|| 'j'\n% %|| 'k' }\n% %|| .values\n% %|| { [ 1 2 3 ]\n% %|| [ 1 2 ]\n% %|| [ 1 ] }\n% %|| .vol\n% %|| .mat\n% %|| [ 2 0 0 -3\n% %|| 0 2 0 -3\n% %|| 0 0 2 -3\n% %|| 0 0 0 1 ]\n% %|| .dim\n% %|| [ 3 2 1 ]\n% %|| .xform\n% %|| 'scanner_anat'\n% %|| .fa\n% %|| .i\n% %|| [ 1 2 3 1 2 3 ]\n% %|| .j\n% %|| [ 1 1 1 2 2 2 ]\n% %|| .k\n% %|| [ 1 1 1 1 1 1 ]\n%\n%\n% Notes:\n% - this function can return neighborhoods with either a fixed number of\n% features, or a fixed radius. When used with a searchlight, the\n% former has the advantage that the number of features is less\n% variable (especially near edges of the brain, in an fmri dataset),\n% which can make it easier to compare result in different regions as\n% the number of features can affect\n% pattern discriminablity. The latter has the advantage that the\n% smoothness of the output maps under the null hypothesis can be more\n% uniformly smooth.\n%\n% See also: cosmo_fmri_dataset, cosmo_meeg_dataset, cosmo_searchlight\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n check_input(varargin{:});\n\n defaults=struct();\n defaults.progress=1000;\n opt=cosmo_structjoin(defaults,varargin);\n\n [use_fixed_radius,radius,voxel_count]=get_selection_params(opt);\n cosmo_check_dataset(ds);\n\n % ensure not too many features are requested\n feature_mask=get_features_mask(ds);\n nfeatures=sum(feature_mask);\n if nfeatures0;\n\n if show_progress\n clock_start=clock();\n prev_progress_msg='';\n end\n\n % a position may occur at multiple features; only consider unique\n % positions\n pos(:,~feature_mask)=Inf;\n [center_idxs,unq_pos]=cosmo_index_unique(pos');\n keep_unq_pos=~any(isinf(unq_pos),2);\n center_idxs=center_idxs(keep_unq_pos);\n unq_pos=unq_pos(keep_unq_pos,:);\n nunq_centers=numel(center_idxs);\n\n % allocate space for output\n ncenters=nunq_centers;\n neighbors=cell(ncenters,1);\n nvoxels=zeros(1,ncenters);\n final_radius=zeros(1,ncenters);\n visited=false(1,ncenters);\n center_ids=zeros(1,ncenters);\n\n % go over all features\n for k=1:nunq_centers\n variable_radius=NaN;\n if voxel_count==0\n feature_ids=zeros(1,0);\n else\n center_pos=unq_pos(k,:)';\n\n % - in case of a variable radius, keep growing sphere_offsets\n % until there are enough voxels selected. This new radius is\n % kept for every subsequent iteration.\n % - in case of a fixed radius this loop is left after the first\n % iteration.\n while true\n % add offsets to center\n all_around_pos=bsxfun(@plus, center_pos', sphere_offsets);\n\n % see which ones are outside the volume\n outside_msk=all_around_pos<=0 | ...\n bsxfun(@minus,grid_dim,all_around_pos)<0;\n\n % collapse over 3 dimensions\n feature_outside_msk=any(outside_msk,2);\n\n % get rid of those outside the volume\n around_pos=all_around_pos(~feature_outside_msk,:);\n\n\n % convert to linear indices\n around_lin=fast_sub2ind(grid_dim,around_pos(:,1), ...\n around_pos(:,2), ...\n around_pos(:,3));\n\n % convert linear to feature ids\n % (transpose is necessary so that when applying the\n % mask, the indices remain sorted by distance)\n around_ids_mat=lin2feature_ids(around_lin,:)';\n around_ids_mask=lin2feature_mask(around_lin,:)';\n feature_ids=around_ids_mat(around_ids_mask);\n\n if use_fixed_radius\n break; % we're done selecting voxels\n elseif numel(feature_ids)=k;\n ds(k,msk)=center_distances(msk);\n end\n\n feature_distances=ds(~isnan(ds));\n\n\nfunction [lin2feature_ids,lin2feature_mask]=get_lin2feature_ids(...\n grid_dim,all_pos,center_mask)\n % returns a function that maps linear ids to feature ids\n % the function takes as input linear ids and the distance for each\n % linear id, and returns the feature ids and their corresponding\n % distances\n\n orig_nvoxels=prod(grid_dim);\n\n ijk=all_pos(:,center_mask);\n\n lin_ids=fast_sub2ind(grid_dim, ijk(1,:), ijk(2,:), ijk(3,:));\n [idxs,unq_lin_ids]=cosmo_index_unique(lin_ids');\n\n mask2full=find(center_mask);\n % lin2feature_ids{k}={i1,...,iN} means that the linear voxel index k\n % corresponds to features i1,...iN\n lin2feature_ids_cell=cell(orig_nvoxels,1);\n for k=1:numel(unq_lin_ids)\n lin_id=unq_lin_ids(k);\n idx=idxs{k}(:)';\n lin2feature_ids_cell{lin_id}=mask2full(idx);\n end\n\n n_max=max(cellfun(@numel,lin2feature_ids_cell));\n\n lin2feature_ids=zeros(orig_nvoxels, n_max);\n lin2feature_mask=false(orig_nvoxels,n_max);\n\n for k=1:numel(unq_lin_ids)\n lin_id=unq_lin_ids(k);\n indices=lin2feature_ids_cell{lin_id};\n\n cols=1:numel(indices);\n lin2feature_ids(lin_id,cols)=indices;\n lin2feature_mask(lin_id,cols)=true;\n end\n\n\n\n\n\n\nfunction feature_mask=get_features_mask(ds)\n % use .fa.inside if it is present, otherwise an array with only true\n % values\n nfeatures=size(ds.samples,2);\n\n if cosmo_isfield(ds,'fa.inside')\n inside=ds.fa.inside;\n\n if size(inside,1)~=1\n error('field .fa.inside must be a row vector');\n end\n\n if ~islogical(inside)\n error('field .fa.inside must be logical');\n end\n\n feature_mask=inside;\n else\n feature_mask=true(1,nfeatures);\n end\n\n\nfunction lin=fast_sub2ind(sz, i, j, k)\n lin=sz(1)*(sz(2)*(k-1)+(j-1))+i;\n\nfunction pos=boundary_at_approx(ids, distances, voxel_count)\n % pseudo-random selection of approximatly voxel_count elements\n if voxel_count<=0\n pos=0;\n return\n end\n\n assert(issorted(distances));\n\n max_distance=distances(voxel_count);\n first=find(distancesmax_distance,1,'first')-1;\n\n if isempty(first)\n first=1;\n end\n\n if isempty(last)\n last=numel(distances);\n end\n\n delta_first=voxel_count-first;\n delta_last=last-voxel_count;\n\n if delta_first==delta_last\n % select pseudo-randomly\n if delta_first==0 || mod(sum(ids)+numel(distances),2)==0\n pos=first;\n else\n pos=last;\n end\n elseif delta_firstdistances(first));\n\n\nfunction [fdim,fa,ijk,orig_dim]=get_spherical_attributes(ds, center_mask)\n % returns fdim, fa, and ijk positions for dataset\n labels=get_dim_label(ds);\n\n fdim=get_spherical_fdim(ds,labels);\n fa=get_spherical_fa(ds.fa,labels);\n\n if cosmo_isfield(ds,'fa.inside')\n fa.inside=center_mask;\n end\n\n small_ds=cosmo_slice(ds,[],1);\n small_ds_vol=cosmo_vol_grid_convert(small_ds, 'tovol');\n\n ijk=[small_ds_vol.fa.i;small_ds_vol.fa.j;small_ds_vol.fa.k];\n\n ijk_labels={'i','j','k'};\n [unused,index]=has_fdim_label(small_ds_vol,ijk_labels);\n\n orig_dim=cellfun(@numel,small_ds_vol.a.fdim.values(index));\n orig_dim=orig_dim(:)';\n\n\nfunction [tf,index]=has_fdim_label(ds, label)\n [two,index]=cosmo_dim_find(ds,label,false);\n tf=~isempty(two) && two==2;\n\n\nfunction [labels,index]=get_dim_label(ds)\n % get either pos or i, j, and k labels\n possible_labels={{'pos'},{'i';'j';'k'}};\n for j=1:numel(possible_labels)\n labels=possible_labels{j};\n [has_label,index]=has_fdim_label(ds, labels);\n if has_label\n return\n end\n end\n\n error(['Unable to find dimension labels, either ''pos'' '...\n 'or ''i'', ''j'', and ''k''']);\n\n\nfunction fdim=get_spherical_fdim(ds, target_labels)\n first_target_label=target_labels{1};\n [two, index]=cosmo_dim_find(ds,first_target_label,true);\n\n if two~=2\n error('dimension ''%s'' must be a feature dimension');\n end\n cosmo_isfield(ds,'a.fdim.labels',true);\n\n dim_labels=ds.a.fdim.labels(:);\n dim_values=ds.a.fdim.values(:);\n\n nlabels=numel(target_labels);\n idx_labels=(index+(0:(nlabels-1)))';\n if numel(dim_labels)=0\n use_fixed_radius=true;\n radius=opt.radius;\n voxel_count=NaN;\n return\n end\n elseif isfield(opt,'count') && isscalar(opt.count) && ...\n opt.count>=0 && round(opt.count)==opt.count\n use_fixed_radius=false;\n radius=1; % starting point\n voxel_count=opt.count;\n return;\n end\n\n raise_parameter_error();\n\n\nfunction raise_parameter_error()\n name=mfilename();\n error(['Illegal parameters, use one of:\\n',...\n '- %s(...,''radius'',r) to use a radius of r voxels\\n',...\n '- %s(...,''count'',c) to select c voxels per searchlight\\n',...\n '(As of January 2014 the syntax of this function has changed)'],...\n name,name);\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_spherical_neighborhood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.36600399962676916}} {"text": "function t_obj = parcel_stats2statistic_image(atlas_obj, tscores, pvalues, dfe, sig)\n% Utility that transforms parcel-wise t-statistics and p-values into a statistic_image object in voxelwise image space\n% Expands parcel values so that they are replicated for each voxel in the parcel.\n%\n% :Usage:\n% ::\n%\n% t_obj = parcel_stats2statistic_image(atlas_obj, tscores, pvalues, dfe, sig)\n%\n% For objects: Type methods(object_name) for a list of special commands\n% Type help object_name.method_name for help on specific\n% methods.\n%\n% ..\n% Author and copyright information:\n%\n% Copyright (C) 2021 Tor Wager\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%\n% :Inputs:\n%\n% **atlas_obj:**\n% An atlas-class object with k distinct regions or parcels\n%\n% **tscores:**\n% n x k matrix of k t-scores for each of n parcels, where k is,\n% e.g., the number of predictors tested in a multiple regression\n%\n% **pvalues:**\n% n x k matrix of k p-values for each of n parcels\n%\n% **dfe:**\n% n x 1 matrix of error degrees of freedom for each of n parcels\n%\n% **sig:**\n% n x k matrix of k significant tests for each of n parcels\n% This may be, e.g., corrected for multiple comparisons.\n%\n% :Optional Inputs:\n%\n% :Outputs:\n%\n% **t_obj:**\n% A statistic_image object containing t-maps. .dat contains\n% t-scores, .p contains p-values. Use statistic_image methods like\n% montage(t_obj), orthviews(t_obj), threshold(t_obj) to interact\n% with this object.\n%\n%\n% :Examples:\n% ::\n%\n% :References:\n% None \n%\n% :See also:\n% parcel_data2fmri_data\n%\n\n% Create placeholder statistic image\n\natlas_obj = replace_empty(atlas_obj); \nk = size(tscores, 2);\nplaceholder_vec = ones(atlas_obj.volInfo.n_inmask, k);\nall_parcel_idx = double(atlas_obj.dat);\nu = unique(all_parcel_idx); u(u == 0) = [];\n\n% initialize variables with correct size\n\nt_obj = statistic_image('dat', single(0 .* placeholder_vec), ...\n 'p', placeholder_vec, ...\n 'sig', logical(placeholder_vec), ...\n 'type', 'T', ...\n 'dfe', placeholder_vec, ...\n 'volInfo', atlas_obj.volInfo);\n\n% number of parcels \n\nn = size(tscores, 1); % num parcels\n\nif n ~= length(u)\n error('Parcel indices in atlas_obj and extracted parcel-wise t-values do not match. Check code.')\nend\n\n\n\nt_obj.dat = zeros(size(placeholder_vec, 1), k); % voxels x conditions\n\n\n for j = 1:length(u)\n % For each parcel, fill in statistic_image object\n % ----------------------------------------------------\n parcelidx = u(j);\n \n wh_vox = all_parcel_idx == parcelidx;\n \n % map parcels to voxels\n t_obj.dat(wh_vox, :) = repmat(tscores(j, :), sum(wh_vox), 1);\n t_obj.p(wh_vox, :) = repmat(pvalues(j, :), sum(wh_vox), 1);\n t_obj.dfe(wh_vox, :) = repmat(dfe(j, 1), sum(wh_vox), k); % replicate dfe\n t_obj.sig(wh_vox, :) = repmat(sig(j, :), sum(wh_vox), 1);\n \n end\n \nt_obj = enforce_variable_types(t_obj); % space-saving: 5/24/17\n\n% input_struct.t_statistic_obj = t_obj;\n\nend % function\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@atlas/parcel_stats2statistic_image.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3650680482911652}} {"text": "function [innermost, inside] = find_innermost_boundary(bnd)\n\n% FIND_INNERMOST_BOUNDARY locates innermost compartment of a BEM model\n% by looking at the containment of the triangular meshes describing \n% the surface boundaries\n%\n% [innermost] = find_innermost_boundary(bnd)\n%\n% with the boundaries described by a struct-array bnd with\n% bnd(i).pnt vertices of boundary i (matrix of size Nx3)\n% bnd(i).tri triangles of boundary i (matrix of size Mx3)\n\n% Copyright (C) 2003, 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\nncmp = length(bnd);\n\nif ncmp==1\n innermost = 1;\n return\nend\n\n% try to locate the innermost compartment\nfor i=1:ncmp\nfor j=1:ncmp\n % determine for a single vertex on each surface if it is inside or outside the other surfaces\n curpos1 = bnd(i).pos(1,:); % any point on the boundary is ok\n curpos = bnd(j).pos;\n curtri = bnd(j).tri;\n if i==j\n inside(i,j) = 0;\n else\n inside(i,j) = bounding_mesh(curpos1, curpos, curtri);\n end\nend\nend\n% assume that the sources are in the innermost compartment\ntmp = sum(inside, 2);\n[i, innermost] = max(tmp);\n\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/inverse/private/find_innermost_boundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.36497933765773755}} {"text": "function result = swt16rec3_GPU(dec_full, level, waveletName)\n%SWT16rec3 Stationary wavelet-based 2-level frame in 3-D.\n% swt16rec3_GPU performs a multi-level 3-D stationary wavelet synthesis\n% using a specific waveletName. \n%\n% result = swt16rec3_GPU(dec_full, level, waveletName) computes the \n% 3-D matrix 'result' at using the coefficients in 'dec_full', level \n% 'level' and using 'waveletName'. Level must be either 1 or 2. Wavelet Toolbox\n% is required to retrieve the filters using 'waveletName'. Both 'level'\n% and 'waveletName' should match those used in creating 'dec_full'.\n%\n% Requires the Parallel Computing Toolbox and a compatible GPU.\n%\n% See conv3DGPU and swt16dec3_GPU\n\n% A. Kucukelbir 12-June-2012.\n% Last Revision: 26-June-2012.\n\n% Create filters\nif ischar(waveletName)\n [~,~,LR,HR] = wfilters(waveletName); \nend\n\n% Define kernels to be used by GPU\nrowsKernel = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'rowsKernel');\ncolumnsKernel = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'columnsKernel');\nbeamsKernel = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'beamsKernel');\nhalfSum = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'halfSum');\n\n% Upsample filters and create temporary cell\nx = cell(1,1);\nfor i = 1:level-1\n LR = dyadup(LR,1);\n HR = dyadup(HR,1); \nend\n\n% Set parameters for convolution kernels on GPU\nBLOCKDIM_X = 8; \nBLOCKDIM_Y = 8; \nBLOCKDIM_Z = 8; \n\nfor i = 1:level\n\n % Grab first level of frame coeffieicents.\n dec = dec_full(1:8);\n dec_full(1:8) = [];\n \n % Downsample filters\n if(i==2)\n LR = dyaddown(LR,0);\n HR = dyaddown(HR,0); \n end\n \n % Move filters to GPU\n LR_g = gpuArray(LR);\n HR_g = gpuArray(HR);\n\n % Calculate kernel radius\n if( mod(length(LR),2) == 0 )\n kernelRadius = length(LR)/2;\n else\n kernelRadius = (length(LR)-1)/2;\n end\n\n % Ensure volume has dimensions that are a multiple of 8\n diff = 0;\n if( mod(size(dec{1,1},1),8) ~= 0 )\n diff = 8*ceil(size(dec{1,1},1)/8) - size(dec{1,1},1);\n for j=1:8\n dec{j,1} = padarray(dec{j,1},[diff diff diff],'post');\n end\n end\n\n % Calculate volume sizes and transfer to GPU\n volRowSize = size(dec{1,1},1);\n volColSize = size(dec{1,1},2);\n volBeaSize = size(dec{1,1},3);\n dec1_g = gpuArray(dec{1,1});\n dec2_g = gpuArray(dec{2,1});\n dec3_g = gpuArray(dec{3,1});\n dec4_g = gpuArray(dec{4,1});\n dec5_g = gpuArray(dec{5,1});\n dec6_g = gpuArray(dec{6,1});\n dec7_g = gpuArray(dec{7,1});\n dec8_g = gpuArray(dec{8,1});\n\n % Setup GPU grids and blocks\n rowsKernel.GridSize = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];\n rowsKernel.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];\n\n columnsKernel.GridSize = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];\n columnsKernel.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];\n\n beamsKernel.GridSize = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];\n beamsKernel.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];\n\n halfSum.GridSize = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];\n halfSum.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];\n\n % Do the SWT for this level\n tmp_g = swt3_1level(dec1_g, dec2_g, dec3_g, dec4_g, dec5_g, dec6_g, dec7_g, dec8_g,...\n LR_g, HR_g, ...\n volRowSize, volColSize, volBeaSize, kernelRadius,...\n rowsKernel, columnsKernel, beamsKernel, halfSum);\n\n % Remove multiple of 8 padding\n tmp = gather(tmp_g);\n x{i,1} = tmp(1:end-diff, 1:end-diff, 1:end-diff);\n\n % Remove kernelRadius padding\n if( mod(length(LR),2) == 0 )\n x{i,1} = x{i,1}(kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1);\n else\n x{i,1} = x{i,1}(kernelRadius+1:end-kernelRadius, kernelRadius+1:end-kernelRadius, kernelRadius+1:end-kernelRadius);\n end\n \n % Take care of second level specific processing\n if (i == 2)\n x{1,1} = padarray(x{1,1},[diff diff diff],'post');\n dec1_g = gpuArray(x{1,1});\n tmp_g = swt3_1level(dec1_g, dec2_g, dec3_g, dec4_g, dec5_g, dec6_g, dec7_g, dec8_g,...\n LR_g, HR_g, ...\n volRowSize, volColSize, volBeaSize, kernelRadius,...\n rowsKernel, columnsKernel, beamsKernel, halfSum);\n tmp = gather(tmp_g);\n tmp = tmp(1:end-diff, 1:end-diff, 1:end-diff); \n if( mod(length(LR),2) == 0 )\n x{1,1} = tmp(kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1);\n else\n x{1,1} = tmp(kernelRadius:end-kernelRadius-1, kernelRadius:end-kernelRadius-1, kernelRadius:end-kernelRadius-1);\n end\n end\n \nend\n\n% Combine results from all levels\nresult = zeros(size(x{1,1}));\nfor i = 1:level\n result = result + 1/level*x{i,1};\nend\n\nend\n\nfunction x = swt3_1level(dec1_g, dec2_g, dec3_g, dec4_g, dec5_g, dec6_g, dec7_g, dec8_g,...\n LR_g, HR_g, ...\n volRowSize, volColSize, volBeaSize, kernelRadius,...\n rowsKernel, columnsKernel, beamsKernel, halfSum)\n\n%% FIRST PASS ALONG BEAMS\n% Get the AA\naaa_Lo_Lo_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\ndaa_Lo_Lo_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\naa_Lo_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\naaa_Lo_Lo_Lo_g = feval( beamsKernel, aaa_Lo_Lo_Lo_g, dec1_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\ndaa_Lo_Lo_Hi_g = feval( beamsKernel, daa_Lo_Lo_Hi_g, dec2_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\naa_Lo_Lo_g = feval( halfSum, aa_Lo_Lo_g, aaa_Lo_Lo_Lo_g, daa_Lo_Lo_Hi_g, volRowSize, volColSize, volBeaSize );\n\n% Get the DA\nada_Lo_Hi_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\ndda_Lo_Hi_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nda_Lo_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\nada_Lo_Hi_Lo_g = feval( beamsKernel, ada_Lo_Hi_Lo_g, dec3_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\ndda_Lo_Hi_Hi_g = feval( beamsKernel, dda_Lo_Hi_Hi_g, dec4_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\nda_Lo_Hi_g = feval( halfSum, da_Lo_Hi_g, ada_Lo_Hi_Lo_g, dda_Lo_Hi_Hi_g, volRowSize, volColSize, volBeaSize );\n\n% Get the AD\naad_Hi_Lo_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\ndad_Hi_Lo_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nad_Hi_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\naad_Hi_Lo_Lo_g = feval( beamsKernel, aad_Hi_Lo_Lo_g, dec5_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\ndad_Hi_Lo_Hi_g = feval( beamsKernel, dad_Hi_Lo_Hi_g, dec6_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\nad_Hi_Lo_g = feval( halfSum, ad_Hi_Lo_g, aad_Hi_Lo_Lo_g, dad_Hi_Lo_Hi_g, volRowSize, volColSize, volBeaSize );\n\n% Get the DD\nadd_Hi_Hi_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nddd_Hi_Hi_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\ndd_Hi_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\nadd_Hi_Hi_Lo_g = feval( beamsKernel, add_Hi_Hi_Lo_g, dec7_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\nddd_Hi_Hi_Hi_g = feval( beamsKernel, ddd_Hi_Hi_Hi_g, dec8_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\ndd_Hi_Hi_g = feval( halfSum, dd_Hi_Hi_g, add_Hi_Hi_Lo_g, ddd_Hi_Hi_Hi_g, volRowSize, volColSize, volBeaSize );\n\n\n%% SECOND PASS ALONG COLUMNS\n% Get the A\naa_Lo_Lo_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nda_Lo_Hi_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\na_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\naa_Lo_Lo_gt = feval( columnsKernel, aa_Lo_Lo_gt, aa_Lo_Lo_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\nda_Lo_Hi_gt = feval( columnsKernel, da_Lo_Hi_gt, da_Lo_Hi_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\na_Lo_g = feval( halfSum, a_Lo_g, aa_Lo_Lo_gt, da_Lo_Hi_gt, volRowSize, volColSize, volBeaSize );\n\n\n% Get the D\nad_Hi_Lo_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\ndd_Hi_Hi_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nd_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\nad_Hi_Lo_gt = feval( columnsKernel, ad_Hi_Lo_gt, ad_Hi_Lo_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\ndd_Hi_Hi_gt = feval( columnsKernel, dd_Hi_Hi_gt, dd_Hi_Hi_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\nd_Hi_g = feval( halfSum, d_Hi_g, ad_Hi_Lo_gt, dd_Hi_Hi_gt, volRowSize, volColSize, volBeaSize );\n\n \n%% FIRST PASS ALONG ROWS\na_Lo_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nd_Hi_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\nx = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);\n\na_Lo_gt = feval( rowsKernel, a_Lo_gt, a_Lo_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\nd_Hi_gt = feval( rowsKernel, d_Hi_gt, d_Hi_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );\n\nx = feval( halfSum, x, a_Lo_gt, d_Hi_gt, volRowSize, volColSize, volBeaSize );\n \n \nend\n\n\n\n\n\n\n\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/37320-gpu-accelerated-3d-stationary-wavelet-based-frame/swt16rec3_GPU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.36497933765773755}} {"text": "function Ne=vertex_neighbours_double(Fa,Fb,Fc,Vx,Vy,Vz)\n\nF=[Fa Fb Fc];\nV=[Vx Vy Vz];\n\n% Neighbourh cell array \nNe=cell(1,size(V,1));\n\n% Loop through all faces\nfor i=1:length(F)\n % Add the neighbors of each vertice of a face\n % to his neighbors list.\n Ne{F(i,1)}=[Ne{F(i,1)} [F(i,2) F(i,3)]];\n Ne{F(i,2)}=[Ne{F(i,2)} [F(i,3) F(i,1)]];\n Ne{F(i,3)}=[Ne{F(i,3)} [F(i,1) F(i,2)]];\nend\n\n% Loop through all neighbor arrays and sort them (Rotation same as faces)\nfor i=1:size(V,1)\n \n Pneighf=Ne{i};\n if(isempty(Pneighf))\n Pneig=[];\n else\n start=1;\n for index1=1:2:length(Pneighf)\n found=false;\n for index2=2:2:length(Pneighf),\n if(Pneighf(index1)==Pneighf(index2))\n found=true; break\n end\n end\n if(~found)\n start=index1; break\n end\n end\n Pneig=[];\n Pneig(1)=Pneighf(start);\n Pneig(2)=Pneighf(start+1);\n \n % Add the neighbours with respect to original rotation\n for j=2+double(found):(length(Pneighf)/2)\n found = false;\n for index=1:2:length(Pneighf),\n if(Pneighf(index)==Pneig(end))\n if(sum(Pneig==Pneighf(index+1))==0)\n found =true;\n Pneig=[Pneig Pneighf(index+1)];\n end\n end\n end\n if(~found) % This only happens with weird edge vertices\n for index=1:2:length(Pneighf),\n if(sum(Pneig==Pneighf(index))==0)\n Pneig=[Pneig Pneighf(index)];\n if(sum(Pneig==Pneighf(index+1))==0)\n Pneig=[Pneig Pneighf(index+1)];\n end\n end\n end\n end\n end\n % Add forgotten neigbours\n if(length(Pneig) http://homepages.cwi.nl/~pauldz/\n% Last Revision: December 12, 2001.\n% (c) 1998-2002 Stichting CWI, Amsterdam\n%-----------------------------------------------------------------------------\n[n11, m11]=size(A11);\nif nargin == 3\n o=[0 0];\n if ~all(size(o) == size(sizeA00))\n error(' synA00Qmin - unexpected dimensions of sizeA00 ')\n else\n clear o;\n n00=sizeA00(1);\n m00=sizeA00(2); \n end\nelseif nargin == 2\n n00=n11+1;\n m00=m11+1;\nelse\n error(' synA00Qmin - number of arguments should be either 2 or 3 ')\nend\n%[n00, m00]=size(A00);\nif m00 == m11+1\n if n00 == n11+1\n S = min(extL(A11, cmax), extR(A11, cmax));\n A00=min(extD(S, cmax), extU(S, cmax));\n elseif n00 == n11\n S = min(extL(A11, cmax), extR(A11, cmax));\n A00=min(S, stripD(extU(S, cmax))); \n else\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str([n00 m00])]);\n error(' synA00Qmin - A11 and target A00 do not match ');\n end\nelseif m00 == m11\n if n00 == n11+1\n S = min(stripR(extL(A11, cmax)), A11);\n A00=min(extD(S, cmax), extU(S, cmax));\n elseif n00 == n11\n S = min(stripR(extL(A11, cmax)), A11);\n A00=min(S, stripD(extU(S, cmax)));\n else\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str([n00 m00])]);\n error(' synA00Qmin - A11 and target A00 do not match ');\n end\nelse\n disp([' size A11 = ' int2str(size(A11)) ' size A00 = ' int2str([n00 m00])]);\n error(' synA00Qmin - A11 and target A00 do not match ');\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/synA00Qmin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.364393071763558}} {"text": "classdef AMICO_ACTIVEAX\n\nproperties\n id, name % id and name of the model\n dPar % parallel diffusivity of the tensors [units of mm^2/s]\n dIso % isotropic diffusivity [units of mm^2/s]\n IC_Rs % radii of the axons [units of 1E-6 (micrometers)]\n IC_VFs % volume fractions of the axons\n OUTPUT_names % suffix of the output maps\n OUTPUT_descriptions % description of the output maps\nend\n\n\nmethods\n\n % =================================\n % Setup the parameters of the model\n % =================================\n function obj = AMICO_ACTIVEAX()\n global CONFIG\n\n % set the parameters of the model\n obj.id = 'ACTIVEAX';\n obj.name = 'ActiveAx';\n obj.dPar = 0.6 * 1E-3;\n obj.dIso = 2.0 * 1E-3;\n obj.IC_Rs = [0.01 linspace(0.5,10,20)];\n obj.IC_VFs = [0.3:0.1:0.9];\n\n obj.OUTPUT_names = { 'v', 'a', 'd' };\n obj.OUTPUT_descriptions = {'Intra-cellular volume fraction', 'Mean axonal diameter', 'Axonal density'};\n\n % set the parameters to fit it\n CONFIG.OPTIMIZATION.SPAMS_param.mode = 2;\n CONFIG.OPTIMIZATION.SPAMS_param.pos = true;\n CONFIG.OPTIMIZATION.SPAMS_param.lambda = 0.25; % l1 regularization\n CONFIG.OPTIMIZATION.SPAMS_param.lambda2 = 4; % l2 regularization\n end\n\n\n % ==================================================================\n % Generate high-resolution kernels and rotate them in harmonic space\n % ==================================================================\n function GenerateKernels( obj, ATOMS_path, schemeHR, AUX, idx_IN, idx_OUT )\n global CONFIG AMICO_data_path CAMINO_path\n\n % check if high-resolution scheme has been created\n schemeHrFilename = fullfile(ATOMS_path,'protocol_HR.scheme');\n if ~exist( schemeHrFilename, 'file' )\n error( '[AMICO_GenerateKernels_ACTIVEAX] File \"protocol_HR.scheme\" not found in folder \"%s\"', ATOMS_path )\n end\n\n filenameHr = [tempname '.Bfloat'];\n progress = ProgressBar( numel(obj.IC_Rs) + numel(obj.IC_VFs) + 1 );\n\n % Restricted\n % ==========\n for R = obj.IC_Rs\n % generate\n if exist( filenameHr, 'file' ), delete( filenameHr ); end\n CMD = sprintf( '%s/datasynth -synthmodel compartment 1 CYLINDERGPD %E 0 0 %E -schemefile %s -voxels 1 -outputfile %s 2> /dev/null', CAMINO_path, obj.dPar*1e-6, R*1e-6, schemeHrFilename, filenameHr );\n [status result] = system( CMD );\n if status>0\n disp(result)\n error( '[AMICO_ACTIVEAX.GenerateKernels] Problems generating the signal with datasynth' );\n end\n\n % rotate and save\n fid = fopen( filenameHr, 'r', 'b' );\n signal = fread(fid,'float');\n fclose(fid);\n delete( filenameHr );\n lm = AMICO_RotateKernel( signal, AUX, idx_IN, idx_OUT, false );\n save( fullfile( ATOMS_path, sprintf('A_%03d.mat',progress.i) ), '-v6', 'lm' )\n progress.update();\n end\n\n\n % Hindered\n % ========\n for ICVF = obj.IC_VFs\n % generate\n d_perp = obj.dPar * ( 1.0 - ICVF );\n if exist( filenameHr, 'file' ), delete( filenameHr ); end\n CMD = sprintf( '%s/datasynth -synthmodel compartment 1 ZEPPELIN %E 0 0 %E -schemefile %s -voxels 1 -outputfile %s 2> /dev/null', CAMINO_path, obj.dPar*1e-6, d_perp*1e-6, schemeHrFilename, filenameHr );\n [status result] = system( CMD );\n if status>0\n disp(result)\n error( '[AMICO_ACTIVEAX.GenerateKernels] problems generating the signal' );\n end\n\n % rotate and save\n fid = fopen( filenameHr, 'r', 'b' );\n signal = fread(fid,'float');\n fclose(fid);\n delete( filenameHr );\n lm = AMICO_RotateKernel( signal, AUX, idx_IN, idx_OUT, false );\n save( fullfile( ATOMS_path, sprintf('A_%03d.mat',progress.i) ), '-v6', 'lm' )\n\n progress.update();\n end\n\n\n % Isotropic\n % =========\n % generate\n if exist( filenameHr, 'file' ), delete( filenameHr ); end\n CMD = sprintf( '%s/datasynth -synthmodel compartment 1 BALL %E -schemefile %s -voxels 1 -outputfile %s 2> /dev/null', CAMINO_path, obj.dIso*1e-6, schemeHrFilename, filenameHr );\n [status result] = system( CMD );\n if status>0\n disp(result)\n error( '[AMICO_ACTIVEAX.GenerateKernels] problems generating the signal' );\n end\n\n % resample and save\n fid = fopen( filenameHr, 'r', 'b' );\n signal = fread(fid,'float');\n fclose(fid);\n delete( filenameHr );\n lm = AMICO_RotateKernel( signal, AUX, idx_IN, idx_OUT, true );\n save( fullfile( ATOMS_path, sprintf('A_%03d.mat',progress.i) ), '-v6', 'lm' )\n progress.update();\n \n progress.close();\n end\n\n\n % ==============================================\n % Project kernels from harmonic to subject space\n % ==============================================\n function ResampleKernels( obj, ATOMS_path, idx_OUT, Ylm_OUT )\n global CONFIG AMICO_data_path KERNELS\n\n % Setup the KERNELS structure\n % ===========================\n nIC = numel(obj.IC_Rs);\n nEC = numel(obj.IC_VFs);\n\n KERNELS = {};\n KERNELS.model = 'ACTIVEAX';\n KERNELS.nS = CONFIG.scheme.nS;\n KERNELS.nA = nIC + nEC + 1; % number of atoms\n\n KERNELS.dPar = obj.dPar;\n\n KERNELS.Aic = zeros( [KERNELS.nS nIC 181 181], 'single' );\n KERNELS.Aic_R = zeros( 1, nIC, 'single' );\n\n KERNELS.Aec = zeros( [KERNELS.nS nEC 181 181], 'single' );\n KERNELS.Aec_icvf = zeros( 1, nEC, 'single' );\n\n KERNELS.Aiso = zeros( [KERNELS.nS 1], 'single' );\n KERNELS.Aiso_d = NaN;\n \n progress = ProgressBar( KERNELS.nA );\n\n % Restricted\n % ==========\n for i = 1:nIC\n load( fullfile( ATOMS_path, sprintf('A_%03d.mat',progress.i) ), 'lm' );\n KERNELS.Aic(:,i,:,:) = AMICO_ResampleKernel( lm, idx_OUT, Ylm_OUT, false );\n KERNELS.Aic_R(i) = obj.IC_Rs(i);\n progress.update();\n end\n\n % Hindered\n % ========\n for i = 1:nEC\n load( fullfile( ATOMS_path, sprintf('A_%03d.mat',progress.i) ), 'lm' );\n KERNELS.Aec(:,i,:,:) = AMICO_ResampleKernel( lm, idx_OUT, Ylm_OUT, false );\n KERNELS.Aec_icvf(i) = obj.IC_VFs(i);\n progress.update();\n end\n\n % Isotropic\n % =========\n load( fullfile( ATOMS_path, sprintf('A_%03d.mat',progress.i) ), 'lm' );\n KERNELS.Aiso = AMICO_ResampleKernel( lm, idx_OUT, Ylm_OUT, true );\n KERNELS.Aiso_d = obj.dIso;\n progress.update();\n\n progress.close();\n end\n\n\n % ===========================\n % Fit the model to each voxel\n % ===========================\n function [ MAPs ] = Fit( obj, y, i1, i2 )\n global CONFIG KERNELS\n\n % prepare SIGNAL and DICTIONARY\n if numel(KERNELS.Aiso_d) > 0\n A = double( [ KERNELS.Aic(CONFIG.scheme.dwi_idx,:,i1,i2) KERNELS.Aec(CONFIG.scheme.dwi_idx,:,i1,i2) KERNELS.Aiso(CONFIG.scheme.dwi_idx) ] );\n else\n A = double( [ KERNELS.Aic(CONFIG.scheme.dwi_idx,:,i1,i2) KERNELS.Aec(CONFIG.scheme.dwi_idx,:,i1,i2) ] );\n end\n AA = [ ones(1,KERNELS.nA) ; A ];\n yy = [ 1 ; y(CONFIG.scheme.dwi_idx) ];\n\n % estimate coefficients\n x = full( mexLasso( yy, AA, CONFIG.OPTIMIZATION.SPAMS_param ) );\n\n % compute MAPS\n nIC = numel(obj.IC_Rs);\n nEC = numel(obj.IC_VFs);\n f1 = sum( x( 1:nIC ) );\n f2 = sum( x( (nIC+1):(nIC+nEC) ) );\n MAPs(1) = f1 / ( f1 + f2 + eps ); % intra-cellular volume fraction (v)\n MAPs(2) = 2 * KERNELS.Aic_R * x(1:nIC) / ( f1 + eps ); % mean axonal diameter\n MAPs(3) = (4*MAPs(1)) / ( pi*MAPs(2)^2 + eps ); % axonal density\n end\n\nend\n\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/AMICO/AMICO_matlab/models/AMICO_ACTIVEAX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3643272808796702}} {"text": "function model = assignQuantDir(model)\n% Quantitatively assigns reaction directionality based on estimated bounds\n% on transformed reaction Gibbs energies\n%\n% USAGE:\n%\n% model = assignQuantDir(model)\n%\n% INPUT:\n% model: structure with fields:\n%\n% * .SIntRxnBool - `n x 1` boolean of internal reactions\n% * .DrGtMin - `n x 1` array of estimated lower bounds on\n% transformed reaction Gibbs energies.\n% * .DrGtMax - `n x 1` array of estimated upper bounds on\n% transformed reaction Gibbs energies.\n%\n% OUTPUT:\n% model: structure with fields:\n%\n% * .quantDir - `n x 1` array indicating quantitatively assigned\n% reaction directionality. 1 for reactions that are\n% irreversible in the forward direction, -1 for\n% reactions that are irreversible in the reverse\n% direction, and 0 for reversible reactions.\n%\n% .. Author: - Hulda SH, Nov. 2012\n\nmodel.NaNdfG0MetBool=isnan(model.DfGt0);\nmodel.NaNd0GRxnBool = isnan(model.DrGt0);\n\nDrGtMin=model.DrGtMin;\nDrGtMax=model.DrGtMax;\n\n[nMet,nRxn]=size(model.S);\n\n% model.quantDir = zeros(size(DrGtMin));\n% model.quantDir(DrGtMax < 0) = 1;\n% model.quantDir(DrGtMin > 0) = -1;\n\nnEqualDrGt=nnz(DrGtMin==DrGtMax & DrGtMin~=0);\nif any(nEqualDrGt)\n fprintf('%s\\n',[num2str(nEqualDrGt) '/' num2str(length(DrGtMin)) ' reactions with DrGtMin=DrGtMax~=0' ]);\nend\n\nnZeroDrGt=nnz(DrGtMin==0 & DrGtMax==0);\nif any(nZeroDrGt)\n fprintf('%s\\n',[num2str(nZeroDrGt) '/' num2str(length(DrGtMin)) ' reactions with DrGtMin=DrGtMax=0' ]);\nend\n\n\nif any(model.NaNd0GRxnBool)\n warning('Some DfGt0 are NaN');\nend\n\nif any(DrGtMin>DrGtMax)\n error('DrGtMin greater than DrGtMax');\nend\n\n%reaction directionality\n%keep exchange bounds the same as for the recostruction\nmodel.lb_reconThermo=model.lb;\nmodel.ub_reconThermo=model.ub;\n\n%now set internal reaction directions\nfor n=1:nRxn\n if model.SIntRxnBool(n)\n if model.NaNd0GRxnBool(n)\n %for the reactions that involve a NaN metabolite standard Gibbs energy of\n %formation, use the directions given by the reconstruction\n if model.lb(n)<0 && model.ub(n)>0\n model.lb_reconThermo(n)=-Inf;\n model.ub_reconThermo(n)=Inf;\n end\n %forward\n if model.lb(n)>=0 && model.ub(n)>0\n model.lb_reconThermo(n)=0;\n model.ub_reconThermo(n)=Inf;\n end\n %reverse\n if model.lb(n)<0 && model.ub(n)<=0\n model.lb_reconThermo(n)=-Inf;\n model.ub_reconThermo(n)=0;\n end\n if model.lb(n)==0 && model.ub(n)==0\n error(['Reaction ' model.rxns{n} ' bounds set to zero'])\n end\n %note that there is no thermodynamic directionality assignment\n %for this reaction\n model.directionalityThermo{n}=NaN;\n else\n if DrGtMax(n)<0\n model.directionalityThermo{n}='forward';\n model.lb_reconThermo(n)=0;\n model.ub_reconThermo(n)=Inf;\n end\n if DrGtMin(n)>0\n model.directionalityThermo{n}='reverse';\n model.lb_reconThermo(n)=-Inf;\n model.ub_reconThermo(n)=0;\n end\n if DrGtMin(n)<0 && DrGtMax(n)>0\n model.directionalityThermo{n}='reversible';\n model.lb_reconThermo(n)=-Inf;\n model.ub_reconThermo(n)=Inf;\n end\n if DrGtMin(n)==DrGtMax(n)\n model.directionalityThermo{n}='equilibrium';\n end\n if model.lb(n)==0 && model.ub(n)==0\n error(['Reaction ' model.rxns{n} ' bounds set to zero'])\n end\n end\n end\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/analysis/thermo/thermoDirectionality/assignQuantDir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.36430503371838785}} {"text": "function G = bst_meg_sph(L, Channel, Param)\n% BST_MEG_SPH: Calculate the (overlapping) sphere models for MEG\n% \n% USAGE: G = bst_meg_sph(L, Channel, Param);\n%\n% INPUT:\n% - L : a 3 x nL array, each column a source location (x y z coordinates); nL sources\n% - Channel : a Brainstorm channel structure\n% - Param[] : array of structures (one per channel)\n% |- Center : a vector of the x, y, z locations for the sphere model \n% | (assume the same center for every sphere for the classical spherical head model)\n%\n% OUTPUT:\n% - G : the gain matrix: each column is the forward field of each source\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n\n%% ===== PARSE INPUTS =====\n% Sources locations should be 3 x m\nif(size(L,1)~=3)\n error('Matrix not given as 3 x n. Correct calling code');\nend\n% Check that the number of coils is the same for all the channels\nchanCoils = cellfun(@(c)size(c,2), {Channel.Loc});\ngrpCoils = unique(chanCoils);\n% If there are multiple sensor sensor types (different numbres of coils)\nif (length(grpCoils) > 1)\n % This function can only accept calls to groups of sensors with the same number of coils\n % => Group the sensors by number of coils and call os_meg as many times as needed\n G = NaN * zeros(length(Channel), 3 * size(L,2));\n for iGrp = 1:length(grpCoils)\n % Get all the sensors with this amount of coils\n iMegGrp = find(chanCoils == grpCoils(iGrp));\n % Compute (os_meg)\n G(iMegGrp,:) = bst_meg_sph(L, Channel(iMegGrp), Param(iMegGrp));\n end\n return;\nend\n% Number of coils for this call\nNumCoils = chanCoils(1);\n\n\n%% ===== COMPUTATION ===== \n% Get locations\nAllLocs = [Channel.Loc]; \nAllLocs = reshape(AllLocs, NumCoils*3, size(AllLocs,2)/NumCoils);\n% Get orientations\nAllOrient = [Channel.Orient];\nAllOrient = AllOrient * bst_inorcol(AllOrient);\nAllOrient = reshape(AllOrient, NumCoils*3, size(AllOrient,2)/NumCoils);\n% Get weights\nAllWeight = [Channel.Weight];\nAllWeight = reshape(AllWeight(:), NumCoils, length(AllWeight(:))/NumCoils);\n\n% Process each group of coils\nG = 0;\nfor j = 1:NumCoils\n % P.sensor is 3 x nR,each column a sensor location\n % P.orient is 3 x nR, the sensor orientation\n % P.center is 3 x nR, the sphere center for each sensor\n P.sensor = AllLocs((-2:0) + j*3, :);\n P.orient = AllOrient((-2:0) + j*3, :);\n P.weight = AllWeight(j,:);\n P.center = [Param.Center];\n % Local call below\n G = G + sarvas(L, P); \nend\n\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%% Local Sarvas functions %%%%%%%%%%%%%%%%%%%%%%%%\nfunction G = sarvas(L, P)\n% Bronzan Sarvas forward model, spherical head\n% P.sensor is 3 x nR,each column a sensor location\n% P.orient is 3 x nR, the sensor orientation\n% P.center is 3 x nR, the sphere center for each sensor\n\nif(~isfield(P,'center')), % user did not provide\n P.center = []; % initialize to null\nend\nif(isempty(P.center)), % user gave as null\n P.center = zeros(size(P.sensor)); % set to coordinate origin\nend\n\nP.sensor = P.sensor - P.center; % shift sensor coordinates\n\niMag = find(sum(P.sensor.^2,1) == 0); % Indices of channels located at P.center.\nif ~isempty(iMag)\n P.sensor(:,iMag) = repmat([1 1 1]',1,length(iMag)); % Move them away (arbitrary location).\nend\n\nnR = size(P.sensor,2); % number of sensors\nnL = size(L,2); % number of source points\n\nRn2 = sum(P.sensor.^2,1); % distance to sensor squared\nRn = sqrt(Rn2); % distance\n\nif (nR >= nL), % more sensors than dipoles\n G = zeros(nR,3*nL); % gain matrix\n for Li = 1:nL,\n Lmat = L(:,Li+zeros(1,nR)); % matrix of location repeated\n Lmat = Lmat - P.center; % each center shifted relative to its center\n D = P.sensor - Lmat; % distance from souce to sensors\n Dn2 = sum(D.^2,1); % distance squared\n Dn = sqrt(Dn2); % distance\n R_dot_D = sum(P.sensor .* D); % dot product of sensor and distance\n R_dot_Dhat = R_dot_D ./ Dn; % dot product of sensor and distance\n \n F = Dn2 .* Rn + Dn .* R_dot_D; % Sarvas' function F\n \n GF_dot_o = Dn2 .* sum(P.sensor.*P.orient) ./ Rn + ...\n (2 * Rn + R_dot_Dhat) .* sum(D.*P.orient) + ...\n Dn .* sum((D+P.sensor).*P.orient);\n \n tempF = GF_dot_o ./ F.^2;\n \n temp = bst_cross(Lmat,P.orient) ./ F([1 1 1],:) - ...\n bst_cross(Lmat,P.sensor) .* tempF([1 1 1],:);\n G(:,Li*3+[-2 -1 0]) = temp';\n\n end\n \nelse % more dipoles than sensors nL > nR\n G = zeros(3*nL,nR); % gain matrix transposed\n \n for Ri = 1:nR,\n Rmat = P.sensor(:,Ri+zeros(1,nL)); % matrix of sensor repeated\n Omat = P.orient(:,Ri+zeros(1,nL)); % orientations\n Lmat = L - P.center(:,Ri+zeros(1,nL)); % shift centers to this coordinate\n \n D = Rmat - Lmat;\n Dn2 = sum(D.^2,1); % distance squared\n Dn = sqrt(Dn2); % distance\n R_dot_D = sum(Rmat .* D); % dot product of sensor and distance\n R_dot_Dhat = R_dot_D ./ Dn; % dot product of sensor and distance\n \n F = Dn2 * Rn(Ri) + Dn .* R_dot_D; % Sarvas' function F\n \n GF_dot_o = Dn2 * sum(P.sensor(:,Ri).*P.orient(:,Ri)) / Rn(Ri) + ...\n (2 * Rn(Ri) + R_dot_D ./ Dn) .* sum(D.*Omat) + ...\n Dn .* sum((D+Rmat).*Omat);\n \n tempF = GF_dot_o ./ F.^2;\n \n temp = bst_cross(Lmat,Omat) ./ F([1 1 1],:) - ...\n bst_cross(Lmat,Rmat) .* tempF([1 1 1],:);\n \n G(:,Ri) = temp(:);\n end\n \n G = G';\nend\n\nif(isfield(P,'weight')),\n Weights = P.weight(:); %make sure column\n % scale each row by its appropriate weight\n G = Weights(:,ones(1,size(G,2))) .* G;\nend\n\nG = G * 1e-7; % mu_o over 4 pi\n\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/forward/bst_meg_sph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.36425991385512246}} {"text": "function [transform, coordsys] = ft_headcoordinates(fid1, fid2, fid3, fid4, coordsys)\n\n% FT_HEADCOORDINATES returns the homogeneous coordinate transformation matrix\n% that converts the specified fiducials in any coordinate system (e.g. MRI)\n% into the rotated and translated headcoordinate system.\n%\n% Use as\n% [transform, coordsys] = ft_headcoordinates(fid1, fid2, fid3, coordsys)\n% or\n% [transform, coordsys] = ft_headcoordinates(fid1, fid2, fid3, fid4, coordsys)\n%\n% Depending on the desired coordinate system, the order of the fiducials is\n% interpreted as follows\n%\n% fid1 = nas\n% fid2 = lpa\n% fid3 = rpa\n% fid4 = extra point (optional)\n%\n% fid1 = ac\n% fid2 = pc\n% fid3 = midsagittal\n% fid4 = extra point (optional)\n%\n% fid1 = pt1\n% fid2 = pt2\n% fid3 = pt3\n% fid4 = extra point (optional)\n%\n% fid1 = bregma\n% fid2 = lambda\n% fid3 = midsagittal\n% fid4 = extra point (optional)\n%\n% The fourth argument fid4 is optional and can be specified as an an extra point\n% which is assumed to have a positive Z-coordinate. It will be used to ensure correct\n% orientation of the Z-axis (ctf, 4d, bti, eeglab, yokogawa, neuromag, itab) or\n% X-axis (acpc, spm, mni, tal). The specification of this extra point may result in\n% the handedness of the transformation to be changed, but ensures consistency with\n% the handedness of the input coordinate system.\n%\n% The coordsys input argument is a string that determines how the location of the\n% origin and the direction of the axis is to be defined relative to the fiducials:\n% according to CTF conventions: coordsys = 'ctf'\n% according to 4D conventions: coordsys = '4d' or 'bti'\n% according to EEGLAB conventions: coordsys = 'eeglab'\n% according to NEUROMAG conventions: coordsys = 'itab'\n% according to ITAB conventions: coordsys = 'neuromag'\n% according to YOKOGAWA conventions: coordsys = 'yokogawa'\n% according to ASA conventions: coordsys = 'asa'\n% according to FTG conventions: coordsys = 'ftg'\n% according to ACPC conventions: coordsys = 'acpc'\n% according to SPM conventions: coordsys = 'spm'\n% according to MNI conventions: coordsys = 'mni'\n% according to Talairach conventions: coordsys = 'tal'\n% according to PAXINOS conventions: coordsys = 'paxinos'\n% If the coordsys input argument is not specified, it will default to 'ctf'.\n%\n% The CTF, 4D, YOKOGAWA and EEGLAB coordinate systems are defined as follows:\n% the origin is exactly between lpa and rpa\n% the X-axis goes towards nas\n% the Y-axis goes approximately towards lpa, orthogonal to X and in the plane spanned by the fiducials\n% the Z-axis goes approximately towards the vertex, orthogonal to X and Y\n%\n% The TALAIRACH, SPM and ACPC coordinate systems are defined as:\n% the origin corresponds with the anterior commissure\n% the Y-axis is along the line from the posterior commissure to the anterior commissure\n% the Z-axis is towards the vertex, in between the hemispheres\n% the X-axis is orthogonal to the midsagittal-plane, positive to the right\n%\n% The NEUROMAG and ITAB coordinate systems are defined as follows:\n% the X-axis is from the origin towards the RPA point (exactly through)\n% the Y-axis is from the origin towards the nasion (exactly through)\n% the Z-axis is from the origin upwards orthogonal to the XY-plane\n% the origin is the intersection of the line through LPA and RPA and a line orthogonal to L passing through the nasion\n%\n% The ASA coordinate system is defined as follows:\n% the origin is at the orthogonal intersection of the line from rpa-lpa and the line trough nas\n% the X-axis goes towards nas\n% the Y-axis goes through rpa and lpa\n% the Z-axis goes approximately towards the vertex, orthogonal to X and Y\n%\n% The FTG coordinate system is defined as:\n% the origin corresponds with pt1\n% the x-axis is along the line from pt1 to pt2\n% the z-axis is orthogonal to the plane spanned by pt1, pt2 and pt3\n%\n% The PAXINOS coordinate system is defined as:\n% the origin is at bregma\n% the x-axis extends along the Medial-Lateral direction, with positive towards the right\n% the y-axis points from dorsal to ventral, i.e. from inferior to superior\n% the z-axis passes through bregma and lambda and points from cranial to caudal, i.e. from anterior to posterior\n%\n% See also FT_ELECTRODEREALIGN, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN, FT_AFFINECOORDINATES, COORDSYS2LABEL\n\n% Copyright (C) 2003-2022, 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% figure out the input arguments\nif nargin==3\n coordsys = 'ctf'; % default\n fid4 = [];\nelseif nargin==4 && ischar(fid4)\n coordsys = fid4;\n fid4 = [];\nelseif nargin==4 && isnumeric(fid4)\n coordsys = 'ctf'; % default\nelseif nargin==5\n % do nothing\nelse\n ft_error('incorrect specification of input parameters');\nend\n\nif isnumeric(coordsys)\n % these are for backward compatibility, but should preferably not be used any more\n if coordsys==0\n coordsys = 'ctf';\n elseif coordsys==1\n coordsys = 'asa';\n elseif coordsys==2\n coordsys = 'ftg';\n else\n ft_error('if coordsys is numeric, it should assume one of the values 0/1/2');\n end\nend\n\n% ensure that they are row vectors\nfid1 = fid1(:)';\nfid2 = fid2(:)';\nfid3 = fid3(:)';\nfid4 = fid4(:)';\n\nassert(numel(fid1)==3, 'incorrect specification of fiducial 1');\nassert(numel(fid2)==3, 'incorrect specification of fiducial 2');\nassert(numel(fid3)==3, 'incorrect specification of fiducial 3');\nassert(isempty(fid4) || numel(fid4)==3, 'incorrect specification of fiducial 4');\n\n% ensure that it is lower case\ncoordsys = lower(coordsys);\n\n% compute the origin and direction of the coordinate axes in MRI coordinates\nswitch coordsys\n case {'ctf' '4d' 'bti' 'eeglab' 'yokogawa'}\n % rename the marker points for convenience\n nas = fid1; lpa = fid2; rpa = fid3; extrapoint = fid4; clear fid*\n origin = (lpa+rpa)/2;\n dirx = nas-origin;\n dirz = cross(dirx,lpa-rpa);\n diry = cross(dirz,dirx);\n dirx = dirx/norm(dirx);\n diry = diry/norm(diry);\n dirz = dirz/norm(dirz);\n case {'asa'}\n % rename the marker points for convenience\n nas = fid1; lpa = fid2; rpa = fid3; extrapoint = fid4; clear fid*\n dirz = cross(nas-rpa, lpa-rpa);\n diry = lpa-rpa;\n dirx = cross(diry,dirz);\n dirx = dirx/norm(dirx);\n diry = diry/norm(diry);\n dirz = dirz/norm(dirz);\n origin = rpa + dot(nas-rpa,diry)*diry;\n case {'neuromag' 'itab'}\n % rename the fiducials\n nas = fid1; lpa = fid2; rpa = fid3; extrapoint = fid4; clear fid*\n dirz = cross(rpa-lpa,nas-lpa);\n dirx = rpa-lpa;\n diry = cross(dirz,dirx);\n dirx = dirx/norm(dirx);\n diry = diry/norm(diry);\n dirz = dirz/norm(dirz);\n origin = lpa + dot(nas-lpa,dirx)*dirx;\n case 'ftg'\n % rename the marker points for convenience\n pt1 = fid1; pt2 = fid2; pt3 = fid3; extrapoint = fid4; clear fid*\n origin = pt1;\n dirx = pt2-origin;\n diry = pt3-origin;\n dirz = cross(dirx,diry);\n diry = cross(dirz,dirx);\n dirx = dirx/norm(dirx);\n diry = diry/norm(diry);\n dirz = dirz/norm(dirz);\n case {'acpc' 'spm' 'mni' 'tal'}\n % rename the marker points for convenience\n ac = fid1; pc = fid2; midsagittal = fid3; extrapoint = fid4; clear fid*\n origin = ac;\n diry = ac-pc;\n dirz = midsagittal-ac;\n dirx = cross(diry,dirz);\n dirz = cross(dirx,diry);\n dirx = dirx/norm(dirx);\n diry = diry/norm(diry);\n dirz = dirz/norm(dirz);\n case 'paxinos'\n bregma = fid1; lambda = fid2; midsagittal = fid3; extrapoint = fid4; clear fid*\n origin = bregma; % bregma is slightly above the brain\n dirz = lambda-bregma; % lambda is slightly above the brain\n diry = bregma-midsagittal; % midsagittal should be somewhere in the middle of the brain\n dirx = cross(diry,dirz); % compute the positive x-direction, i.e. towards the right\n diry = cross(dirz,dirx); % update the y-direction\n dirx = dirx/norm(dirx);\n diry = diry/norm(diry);\n dirz = dirz/norm(dirz);\n otherwise\n ft_error('unrecognized headcoordinate system \"%s\"', coordsys);\nend\n\n% use the extra point to validate that it is a right-handed coordinate system\nif ~isempty(extrapoint)\n dirq = extrapoint-origin;\n dirq = dirq/norm(dirq);\n if any(strcmp(coordsys, {'ctf' '4d' 'bti' 'eeglab' 'yokogawa' 'neuromag' 'itab'}))\n phi = dirq(:)'*dirz(:);\n if sign(phi)<0\n ft_warning('the input coordinate system seems left-handed, flipping z-axis to keep the transformation matrix consistent');\n dirz = -dirz;\n end\n elseif any(strcmp(coordsys, {'acpc' 'spm' 'mni' 'tal'}))\n phi = dirq(:)'*dirx(:);\n if sign(phi)<0\n ft_warning('the input coordinate system seems left-handed, flipping x-axis to keep the transformation matrix consistent');\n dirx = -dirx;\n end\n else\n ft_warning('the extra input coordinate is not used with coordsys \"%s\"', coordsys);\n end\nend\n\n% compute the rotation matrix\nrot = eye(4);\nrot(1:3,1:3) = inv(eye(3) / [dirx; diry; dirz]);\n% compute the translation matrix\ntra = eye(4);\ntra(1:4,4) = [-origin(:); 1];\n% combine these to compute the full homogeneous transformation matrix\ntransform = rot * tra;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/utilities/ft_headcoordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.36425357623877624}} {"text": "function [s, cfg] = ft_statfun_roc(cfg, dat, design)\n\n% FT_STATFUN_ROC computes the area under the curve (AUC) of the Receiver Operator\n% Characteristic (ROC). This is a measure of the separability of the data observed in\n% two conditions. The AUC can be used for statistical testing whether the two\n% conditions can be distinguished on the basis of the data.\n%\n% Use this function by calling one of the high-level statistics functions as\n% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)\n% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)\n% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)\n% with the following configuration option\n% cfg.statistic = 'ft_statfun_roc'\n%\n% The experimental design is specified as:\n% cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1)\n%\n% The labels for the independent variable should be specified as the number 1 and 2.\n%\n% Note that this statfun performs a one sided test in which condition \"1\" is assumed\n% to be larger than condition \"2\". This function does not compute an analytic\n% probability of condition \"1\" being larger than condition \"2\", but can be used in a\n% randomization test, including clustering.\n%\n% A low-level example with 10 channel-time-frequency points and 1000 observations per\n% condition goes like this:\n% dat1 = randn(10,1000) + 1;\n% dat2 = randn(10,1000);\n% design = [1*ones(1,1000) 2*ones(1,1000)];\n% stat = ft_statfun_roc([], [dat1 dat2], design);\n%\n% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS\n\n% Copyright (C) 2008, 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% set the defaults\ncfg.ivar = ft_getopt(cfg, 'ivar', 1);\n\n% on-the-fly log transformation is not supported any more, please use FT_MATH instead\ncfg = ft_checkconfig(cfg, 'forbidden', 'logtransform');\ncfg = ft_checkconfig(cfg, 'forbidden', 'numbins');\n\n% start with a quick test to see whether there appear to be NaNs\nif any(isnan(dat(1,:)))\n % exclude trials that contain NaNs for all observed data points\n sel = all(isnan(dat),1);\n dat = dat(:,~sel);\n design = design(:,~sel);\nend\n\n% logical indexing is faster than using find(...)\nselA = (design(cfg.ivar,:)==1);\nselB = (design(cfg.ivar,:)==2);\n% select the data in the two classes\ndatA = dat(:, selA);\ndatB = dat(:, selB);\n\nnobs = size(dat,1);\nna = size(datA,2);\nnb = size(datB,2);\nauc = zeros(nobs, 1);\n\nfor k = 1:nobs\n % compute the area under the curve for each channel/time/frequency\n a = datA(k,:);\n b = datB(k,:);\n\n % to speed up the AUC, the critical value is determined by the actual\n % values in class B, which also ensures a regular sampling of the False Alarms\n b = sort(b);\n\n ca = zeros(nb+1,1);\n ib = zeros(nb+1,1);\n % cb = zeros(nb+1,1);\n % ia = zeros(nb+1,1);\n\n for i=1:nb\n % for the first approach below, the critval could also be choosen based on e.g. linspace(min,max,n)\n critval = b(i);\n\n % for each of the two distributions, determine the number of correct and incorrect assignments given the critical value\n % ca(i) = sum(a>=critval);\n % ib(i) = sum(b>=critval);\n % cb(i) = sum(b=critval); % correct assignments to class A\n ib(i) = nb-i+1; % incorrect assignments to class B\n end\n\n % add the end point\n ca(end) = 0;\n ib(end) = 0;\n % cb(end) = nb;\n % ia(end) = na;\n\n hits = ca/na;\n fa = ib/nb;\n\n % the numerical integration is faster if the points are sorted\n hits = fliplr(hits);\n fa = fliplr(fa);\n\n if false\n % this part is optional and should only be used when exploring the data\n figure\n plot(fa, hits, '.-')\n xlabel('false positive');\n ylabel('true positive');\n title('ROC-curve');\n end\n\n % compute the area under the curve using numerical integration\n auc(k) = numint(fa, hits);\n\nend\n\n% return the area under the curve as the statistic of interest\ns.stat = auc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NUMINT computes a numerical integral of a set of sampled points using\n% linear interpolation. Alugh the algorithm works for irregularly sampled points\n% along the x-axis, it will perform best for regularly sampled points\n%\n% Use as\n% z = numint(x, y)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction z = numint(x, y)\nif ~all(diff(x)>=0)\n % ensure that the points are sorted along the x-axis\n [x, i] = sort(x);\n y = y(i);\nend\nn = length(x);\nz = 0;\nfor i=1:(n-1)\n x0 = x(i);\n y0 = y(i);\n dx = x(i+1)-x(i);\n dy = y(i+1)-y(i);\n z = z + (y0 * dx) + (dy*dx/2);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/statfun/ft_statfun_roc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3638053464556831}} {"text": "function [ vX, vV, mX ] = ProjectedGdFista( vX, vV, hG, hP, numIterations, stepSize )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX, vV, mX ] = ProjectedGdFista( vX, vV, hG, hP, numIterations, stepSize )\n% Solves an objective function by the Projected Gradient Descent /\n% Projected Gradient Method (PGM) with FISTA Acceleration.\n% Input:\n% - vX - Input Vector.\n% The starting point for the gradient iterations.\n% Structure: Vector (numElements x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vV - Acceleration Vector.\n% The buffer to hold the accelerated direction\n% vector.\n% Structure: Vector (numElements x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - hG - Gradient Function Handler.\n% A function handler which accepts a vector of\n% size (numElements x 1) and returns the gradient\n% in the form of a vector (numElements x 1).\n% Structure: Function Handler.\n% Type: NA.\n% Range: NA.\n% - hP - Gradient Function Handler.\n% A function handler which accepts a vector of\n% size (numElements x 1) and returns the gradient\n% in the form of a vector (numElements x 1).\n% Structure: Function Handler.\n% Type: NA.\n% Range: NA.\n% - numIterations - Number of Iterations.\n% Sets the number of iterations of the gradient\n% descent.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ...}.\n% - stepSize - Step Size.\n% Sets the step size of the Gradient step.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% Output:\n% - vX - Output Vector.\n% The end point for the gradient iterations.\n% Structure: Vector (numElements x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vV - Acceleration Vector.\n% The buffer to hold the accelerated direction\n% vector of last iteration. May used by a wrapper\n% for warm start.\n% Structure: Vector (numElements x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - mX - The Path Matrix.\n% The points of the gradient iterations.\n% Structure: Matrix (numElements x numIterations).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References:\n% 1. Geoff Gordon & Ryan Tibshirani - Accelerated First Order Methods (https://www.cs.cmu.edu/~ggordon/10725-F12/slides/09-acceleration.pdf).\n% Remarks:\n% 1. B\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 26/12/2020 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nmX = zeros(size(vX, 1), numIterations);\n\nvG = zeros(size(vX, 1), 1);\nmX(:, 1) = vX;\nmX(:, 2) = vX - stepSize * hG(vX);\n\nfor ii = 3:numIterations\n vV(:) = mX(:, ii - 1) + (((ii - 2) / (ii + 1)) * (mX(:, ii - 1) - mX(:, ii - 2)));\n vG(:) = hG(vV); % 30% of highest peak\n \n fho=(iframe-1)*kframe+spoff;\n sff=sf((iframe-1)*kframed+sfj);\n sffdc=mean(sff(sfi)); % mean of initial correlation window length\n sff=sff-sffdc; % subtract off the mean\n nccfd=normxcor(sff(1:kcorwd),sff(minlag+1:end));\n [ipkd,vpkd]=v_findpeaks(nccfd,'q');\n \n % Debugging: execute the line below to plot the autocorrelation peaks.\n % v_findpeaks(nccfd,'q'); xlabel(sprintf('Lag = (x+%d)*%g ms',minlag-1,1000*kdsmp/fs)); ylabel('Normalized Cross Correlation'); title (sprintf('Frame %d/%d',iframe,nframe));\n \n vipkd=[vpkd ipkd];\n vipkd(vpkdncands-1\n vipkd=sortrows(vipkd);\n vipkd(1:size(vipkd,1)-ncands+1,:)=[]; % eliminate lowest to leave only ncands-1\n end\n lagcan=round(vipkd(:,2)*kdsmp+lagoff); % convert the lag candidate values to the full sample rate\n nlcan=length(lagcan);\n else\n nlcan=0;\n end\n \n % If there are any candidate lag values (nlcan>0) then refine their accuracy at the full sample rate\n \n if nlcan\n laglist=reshape(repmat(lagcan(:)',nfullag,1)+repmat((-hnfullag:hnfullag)',1,nlcan),nfullag*nlcan,1);\n sfh=s(fho+(1:kcorw+max(lagcan)+hnfullag));\n sfhdc=mean(sfh(sfhi));\n sfh=sfh-sfhdc;\n e0=sum(sfh(sfhi).^2); % energy of initial correlation window (only needed to store in tv(:,6)\n lagl2=repmat(lagcan(:)',nfullag+kcorw-1,1)+repmat((1-hnfullag:hnfullag+kcorw)',1,nlcan);\n nccf=normxcor(sfh(1:kcorw),sfh(lagl2),afact);\n \n [maxcc,maxcci]=max(nccf,[],1);\n vipk=[maxcc(:) lagcan(:)+maxcci(:)-hnfullag-1];\n vipk=vipk(:,[1 2 2]);\n maxccj=maxcci(:)'+nfullag*(0:nlcan-1); % vector index into nccf array\n msk=mod(maxcci,nfullag-1)~=1 & 2*nccf(maxccj)-nccf(mod(maxccj-2,nfullag*nlcan)+1)-nccf(mod(maxccj,nfullag*nlcan)+1)>0; % don't do quadratic interpolation for the end ones\n if any(msk)\n maxccj=maxccj(msk);\n vipk(msk,3)=vipk(msk,3)+(nccf(maxccj+1)-nccf(maxccj-1))'./(2*(2*nccf(maxccj)-nccf(maxccj-1)-nccf(maxccj+1)))';\n end\n vipk(maxccncands-1\n vipk=sortrows(vipk);\n vipk(1:size(vipk,1)-ncands+1,:)=[]; % eliminate lowest to leave only ncands-1\n end\n \n % vipk(:,1) has NCCF value, vipk(:,2) has integer peak position, vipk(:,3) has refined peak position\n \n mc=size(vipk,1);\n else\n mc=0;\n end\n \n % We now have mc lag candidates at the full sample rate\n \n mc1=mc+1; % total number of candidates including \"unvoiced\" possibility\n mcands(iframe)=mc; % save number of lag candidates (needed for pitch consistency cost calculation)\n if mc\n lagval(iframe,1:mc)=vipk(:,3)';\n cost(iframe,1)=vobias+max(vipk(:,1)); % voiceless cost\n cost(iframe,2:mc1)=1-vipk(:,1)'.*(1-beta*vipk(:,3)'); % local voiced costs\n tv(iframe,2)=min(cost(iframe,2:mc1));\n else\n cost(iframe,1)=vobias; % if no lag candidates (mc=0), then the voiceless case is the only possibility\n end\n tv(iframe,1)=cost(iframe,1);\n if iframe>1 % if it is not the first frame, then calculate pitch consistency and v/uv transition costs\n mcp=mcands(iframe-1);\n costm=zeros(mcp+1,mc1); % cost matrix: rows and cols correspond to candidates in previous and current frames (incl voiceless)\n \n % if both frames have at least one lag candidate, then calculate a pitch consistency cost\n \n if mc*mcp\n lrat=abs(log(repmat(lagval(iframe,1:mc),mcp,1)./repmat(lagval(iframe-1,1:mcp)',1,mc)));\n costm(2:end,2:end)=p.freqwt*min(lrat,doublec+abs(lrat-log2)); % allow pitch doubling/halving\n end\n \n % if either frame has a lag candidate, then calculate the cost of voiced/voiceless transition and vice versa\n \n if mc+mcp\n rr=sqrt((rmswin'*s(fho+rmsix).^2)/(rmswin'*s(fho+rmsix-kdrms).^2)); % amplitude \"gradient\"\n ss=0.2/(v_distitar(v_lpcauto(sp(fho+rmsix),lpcord),v_lpcauto(sp(fho+rmsix-kdrms),lpcord),'e')-0.8); % Spectral stationarity: note: Talkin uses Hanning instead of Hamming windows for LPC\n costm(1,2:end)= vtranc+vtrsc*ss+vtrac/rr; % voiceless -> voiced cost\n costm(2:end,1)= vtranc+vtrsc*ss+vtrac*rr;\n tv(iframe,4:5)=[costm(1,mc1) costm(mcp+1,1)];\n end\n costm=costm+repmat(cost(iframe-1,1:mcp+1)',1,mc1); % add in cumulative costs\n [costi,previ]=min(costm,[],1);\n cost(iframe,1:mc1)=cost(iframe,1:mc1)+costi;\n prev(iframe,1:mc1)=previ;\n else % first ever frame\n costm=zeros(1,mc1); % create a cost matrix in case doing a backward recursion\n end\n if mc\n tv(iframe,3)=cost(iframe,1)-min(cost(iframe,2:mc1));\n tv(iframe,6)=5*log10(e0*e0/afact);\n end\n if doback\n costms{iframe}=costm; % need to add repmatted cost into this\n end\nend\n\n% now do traceback\n\nbest=zeros(nframe,1);\n[cbest,best(nframe)]=min(cost(nframe,1:mcands(nframe)+1));\nfor i=nframe:-1:2\n best(i-1)=prev(i,best(i));\nend\nvix=find(best>1);\nfx=repmat(NaN,nframe,1); % unvoiced frames will be NaN\nfx(vix)=fs*lagval(vix+nframe*(best(vix)-2)).^(-1); % leave as NaN if unvoiced\ntt=zeros(nframe,3);\ntt(:,1)=(1:nframe)'*kframe+spoff; % find frame times\ntt(:,2)=tt(:,1)+kframe-1;\njratm=(jumprat+1/jumprat)/2;\ntt(2:end,3)=abs(fx(2:end)./fx(1:end-1)-jratm)>jumprat-jratm; % new spurt if frequency ratio is outside (1/jumprat,jumprat)\ntt(1,3)=1; % first frame always starts a spurt\ntt(1+find(isnan(fx(1:end-1))),3)=1; % NaN always forces a new spurt\n\n% plot results if there are no output arguments of if the 'g' mode option is specified\n\nif ~nargout || any(mode=='g')\n tf=spoff+(0:nframe-1)'*kframe; % one sample before start of each frame\n blag=repmat(NaN,nframe,1); % unvoiced frames will be NaN\n blag(vix)=lagval(vix+nframe*(best(vix)-2)); % leave as NaN if unvoiced\n ts=(1:ns)/fs; % time scale for speech samples\n tsa=[1:tf(1) tf(end)+kframe+1:ns]; % indexes for unprocessed speech [-1 term is an error methinks]\n sup=repmat(NaN,ns,1); % unprocessed speech - plot in black\n sup(tsa)=s(tsa);\n sv=reshape(s(tf(1)+1:tf(end)+kframe),kframe,nframe); % processed speech\n su=sv;\n su(:,best>1)=NaN; % delete all voiced samples\n sv(:,best==1)=NaN; % delete all unvoiced samples\n tsuv=(tf(1)+1:tf(end)+kframe)/fs;\n su=su(:);\n sv=sv(:);\n ax=zeros(2,1);\n ax(1)=subplot(211);\n plot(ts,sup,'-k',tsuv,su,'r-',tsuv,sv,'b-');\n title('Speech');\n ax(2)=subplot(212);\n plot((tf+(kframe+1)/2)/fs,lagval*1000/fs,'xr',(tf+(kframe+1)/2)/fs,blag*1000/fs,'-b')\n xlabel('Time (s)');\n ylabel('Period (ms)');\n title('Lag Candidates');\n linkaxes(ax,'x');\nend\nif ~any(mode=='u')\n tt(isnan(fx),:)=[]; % remove NaN spurts\n fx(isnan(fx),:)=[];\nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction v=normxcor(x,y,d)\n% Calculate the normalized cross correlation of column vectors x and y\n% we can calculate this in two ways but fft is much faster even for nx small\n% We must have nx<=ny and the output length is ny-nx+1\n% note that this routine does not do mean subtraction even though this is normally a good idea\n% if y is a matrix, we correlate with each column\n% d is a constant added onto the normalization factor\n% v(j)=x'*yj/sqrt(d + x'*x * yj'*yj) where yj=y(j:j+nx-1) for j=1:ny-nx+1\n\nif nargin<3\n d=0;\nend\nnx=length(x);\n[ny,my]=size(y);\nnv=1+ny-nx;\nif nx>ny\n error('second argument is shorter than the first');\nend\n\nnf=pow2(nextpow2(ny));\nw=v_irfft(repmat(conj(v_rfft(x,nf,1)),1,my).*v_rfft(y,nf,1));\ns=zeros(ny+1,my);\ns(2:end,:)=cumsum(y.^2,1);\nv=w(1:nv,:)./sqrt(d+(x'*x).*(s(nx+1:end,:)-s(1:end-nx,:)));", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_fxrapt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3628168701034234}} {"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: September 9th, 2016\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 geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Make_Scallop_Geo_and_Input_Files()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 256; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nLx = 1.0; % Length of Eulerian Grid in x-Direction\ndx = Lx/Nx; % Grid spatial resolution\n\n%\n% Immersed Structure Geometric / Dynamic Parameters %\n%\nds = 0.5*dx; % Lagrangian Pt. Spacing (2x resolution of Eulerian grid)\nstruct_name = 'scallop'; % Name for .vertex, .spring, etc files. (must match what's in 'input2d')\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,Lx);\n\n\nhalf_len = (length(xLag)-1)/2; % Computes # of Lag Pts on each \"Arm\"\nind_off = ceil( 0.4*half_len ); % Computes # of lags from center pt for muscle placement\nb_ind = half_len - ind_off; % Bottom index\nt_ind = half_len+2 + ind_off; % Top index\n\n%b_ind = 1;\n%t_ind = length(xLag);\nm_dist = sqrt( ( xLag(b_ind)-xLag(t_ind) )^2 + ( yLag(b_ind)-yLag(t_ind) )^2 );\n\n\n\n% Test Muscle Placement\nplot( xLag( b_ind ), yLag( b_ind ), 'm*'); hold on;\nplot( xLag( t_ind ), yLag( t_ind ), 'm*'); hold on;\n\n\n% Prints .vertex file!\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n\n% Prints .spring file!\nk_Spring = 2e6; % Spring stiffness (does not need to be equal for all springs)\nds_Rest = ds; % Spring resting length (does not need to be equal for all springs)\nprint_Lagrangian_Springs(xLag,yLag,k_Spring,ds_Rest,struct_name);\n\n\n% Prints .beam file!\nk_Beam = 1e11; % Beam Stiffness (does not need to be equal for all beams)\nC = compute_Curvatures(xLag,yLag); % Computes curvature of initial configuration\nprint_Lagrangian_Beams(xLag,yLag,k_Beam,C,struct_name);\n\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 = m_dist; SK = 0.3; a = 0.25; b = 4.0; Fmax = 1e2;\nprint_Lagrangian_Muscles(xLag,LFO,SK,a,b,Fmax,struct_name,b_ind,t_ind)\n\n\n% Prints .target file!\n%k_Target = 1e7;\n%print_Lagrangian_Target_Pts(xLag,k_Target,struct_name);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints VERTEX points to a file called 'struct_name'.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Vertices(xLag,yLag,struct_name)\n\n N = length(xLag); % Total # of Lag. Pts\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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,ind_b,ind_t)\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', 1 ); % Only 1 muscle\n\n %MUSCLES BETWEEN VERTICES\n fprintf(muscle_fid, '%d %d %1.16e %1.16e %1.16e %1.16e %1.16e\\n', ind_b, ind_t, LFO, SK, a,b,Fmax); \n \n fclose(muscle_fid);\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called 'struct_name'.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-1 ); % Print # of springs \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: prints TARGET points to a file called 'struct_name'.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', N );\n\n %Loops over all Lagrangian Pts.\n for s = 1:N\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_name'.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(s) ); \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(s) ); \n end\n end\n fclose(beam_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes \"curvature\" of starting configuration\n% \n% NOTE: not curvature in the traditional geometric sense, in the 'discrete'\n% sense through cross product.\n%\n% NOTE: assumes a CLOSED structure\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = compute_Curvatures(xLag,yLag)\n\nN = length(xLag);\nC = zeros( N );\n\n%Note: needs to be done same order as you print .beam file!\nfor i=1:N\n \n % Pts Xp -> Xq -> Xr (same as beam force calc.)\n \n if ( (i > 1) && (i < N) )\n \n Xp = xLag(i-1); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(i-1); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==1)\n \n Xp = xLag(N); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(N); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==N)\n \n Xp = xLag(N-1); Xq = xLag(N); Xr = xLag(1);\n Yp = yLag(N-1); Yq = yLag(N); Yr = yLag(1);\n \n end\n \n C(i) = (Xr-Xq)*(Yq-Yp) - (Yr-Yq)*(Xq-Xp); %Cross product btwn vectors\n \nend\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \nfunction [xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(ds,Lx)\n \n% ds: Lagrangian pt. spacing\n% Lx: Length of Eulerian grid\n \n% The immsersed structure is initially \"an angle\" of 10 degrees %\nang = 70*pi/180; % original angle\nL = 1/10*Lx; % Structure will be 1/20 of the length of the grid\n\n% Create line of points\nx = 0:ds:L;\ny = zeros( 1, length( x ) );\n\n% Rotate line of points\n[xB,yB] = rotate_geometry_please(x,y,-ang/2);\n[xT,yT] = rotate_geometry_please(x,y,ang/2);\n\n% Put together!\nxLag = [ xB(end:-1:2) xT ];\nyLag = [ yB(end:-1:2) yT ];\n\n[xLag,yLag] = rotate_geometry_please(xLag,yLag,-pi/4);\n\nlength(xLag)\n\nxLag = xLag + 0.75*Lx;\nyLag = yLag + 0.25*Lx;\n\n% TESTING GEOMETRY\nplot(xB,yB,'r*'); hold on;\nplot(xT,yT,'go'); hold on;\nplot( xLag, yLag, 'k+'); hold on;\naxis([0 Lx 0 Lx]);\n\n% for i=1:length(xLag)\n% plot( xLag(i), yLag(i), 'k+'); hold on;\n% axis([0 Lx 0 Lx]);\n% pause();\n% end\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: rotate set of points\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xN,yN] = rotate_geometry_please(x,y,ang)\n\n% x,y original (x,y) coordinates before rotation\n% ang: angle rotating by\n\nxN = zeros( 1, length( x ) ); yN = xN;\nfor i=1:length(x)\n xN(i) = x(i)*cos(ang) - y(i)*sin(ang); \n yN(i) = x(i)*sin(ang) + y(i)*cos(ang); \nend\n\n\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_Scallop/Scallop_FV_LT_Muscle/Make_Scallop_Geo_and_Input_Files.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.36267365565384224}} {"text": " function xs = de_pl_osps(x, Gb, ymi, Im, rmi, R, ftab, Gtab, masseff, niter, pixmax, gi, denom)\n%function xs = de_pl_osps(x, Gb, ymi, Im, rmi, R, ftab, Gtab, masseff, niter, pixmax, gi, denom)\n% The Dual-Energy PL-OS-SPS algorithm for transmission Poisson problem\n% (ordered subsets, separable paraboloidal surrogates)\n% uses fast precomputed curvatures described in paper fessler::\n% in:\n%\tx\t\t[np,2] initial guess\n%\tGb\t\tGblock object\n%\tymi\t\t[nb,na,2] raw polyenergetic measurements\n%\tIm\t\t[2] source intensities\n%\trmi\t\t[nb,na,2] (or scalar) background/scatter\n%\tR\t\tpenalty object (see Robject.m)\n%\tftab\t\tF table\n%\tGtab\t\tG table\n%\tmasseff\t\t[2,2] effective mass atten coef's\n%\t\t\t2 energies by 2 materials\n%\tniter\t\t# iterations (including initial guess)\n%\t\t\tfix: allow relaxation parameters here!\n%\tpixmax\t\tupper constraint for pixel values\n%\t\tcan be scalar (e.g. 'inf') or an array the size of x\n%\tgi\t\tsum(Gt)'\n%\t\tdenom\t\t[np,2] (if precomputed denominator)\n% out:\n%\tx [np,2,niter]\tupdated image vectors each iteration\n%\n% Copyright 2001-04-28, Jeff Fessler, The University of Michigan\n\nif nargin < 6, ir_usage, end\n\nif ~isvar('Im') | isempty(Im)\n\tIm = [1 1];\nend\nif ~isvar('rmi') | isempty(rmi)\n\trmi = zeros(size(ymi));\nend\n\ntrl_check(ymi(:,:,1), [], rmi(:,:,1));\ntrl_check(ymi(:,:,2), [], rmi(:,:,2));\n\nif ~isvar('R') | isempty(R), error 'R required', end\n\nnblock = block_ob(Gb, 'n');\nif ~isvar('niter')\t| isempty(niter),\tniter = 1;\tend\nif ~isvar('pixmax')\t| isempty(pixmax),\tpixmax = inf;\tend\nif ~isvar('chat')\t| isempty(chat),\tchat = 0;\tend\n\nstarts = subset_start(nblock);\n[nb, na, nm] = size(ymi);\n\n%\n% precompute denominator\n%\nif ~isvar('denom'), error 'use de_pl_denom', end\n\n%\n% loop over iterations\n%\nxs = zeros([size(x) niter]);\t% [np,2,niter]\nx = max(x,0);\nxs(:,:,1) = x;\nfor it=2:niter\n\tprintf('DE-PL-OSPS iteration %d', it)\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\t% s=G*x \"mass integrals\"\n\t\ts1 = Gb{iblock} * x(:,1);\n\t\ts2 = Gb{iblock} * x(:,2);\n\n\t\t% predicted meas. means\n\t\ts1 = reshape(s1, nb, length(ia));\n\t\ts2 = reshape(s2, nb, length(ia));\n\t\tfh = ftab.feval(ftab, s1, s2);\n\t\tyb1 = Im(1) * exp(-fh(:,:,1)) + rmi(:,ia,1);\n\t\tyb2 = Im(2) * exp(-fh(:,:,2)) + rmi(:,ia,2);\n\n\t\tdh1 = ymi(:,ia,1) ./ yb1 - 1;\t% m=1\n\t\tdh2 = ymi(:,ia,2) ./ yb2 - 1;\t% m=2\n\n\tif 0\n\t\tG11 = interp2(Gtab.s1, Gtab.s2, Gtab.Gm1(:,:,1)', s1, s2);\n\t\tG21 = interp2(Gtab.s1, Gtab.s2, Gtab.Gm1(:,:,2)', s1, s2);\n\t\tG12 = interp2(Gtab.s1, Gtab.s2, Gtab.Gm2(:,:,1)', s1, s2);\n\t\tG22 = interp2(Gtab.s1, Gtab.s2, Gtab.Gm2(:,:,2)', s1, s2);\n\n\t\t% undo nonlinearity associated with table of Gml\n\t\tG11 = -exp(-G11);\n\t\tG12 = -exp(-G12);\n\t\tG21 = -exp(-G21);\n\t\tG22 = -exp(-G22);\n\n\telse\n\t\t% Gml using polynomial model!\n\t\t% note: 'coef' is indexed by m, but d_l\nif it*iset == 2, warning 'not tested', end\n\t\td11 = reshape(ftab.basis_d1(s1(:), s2(:)) * ftab.coef(:,1), ...\n\t\t\t\tsize(s1));\n\t\td21 = reshape(ftab.basis_d1(s1(:), s2(:)) * ftab.coef(:,2), ...\n\t\t\t\tsize(s1));\n\t\td12 = reshape(ftab.basis_d2(s1(:), s2(:)) * ftab.coef(:,1), ...\n\t\t\t\tsize(s2));\n\t\td22 = reshape(ftab.basis_d2(s1(:), s2(:)) * ftab.coef(:,2), ...\n\t\t\t\tsize(s2));\n\t\tG11 = -(yb1-rmi(:,ia,1)) .* d11;\n\t\tG21 = -(yb2-rmi(:,ia,2)) .* d21;\n\t\tG12 = -(yb1-rmi(:,ia,1)) .* d12;\n\t\tG22 = -(yb2-rmi(:,ia,2)) .* d22;\n\tend\n\n\t\t% g_l is sum over m\n\t\tg1 = G11 .* dh1 + G21 .* dh2;\n\t\tg2 = G12 .* dh1 + G22 .* dh2;\n\n\t\tgrad = Gb{iblock}' * [g1(:) g2(:)];\t% [np,2]\n\n%%\t\tfor isub=1:1\n\t\t\tfor ll=1:2\n\t\t\t\tpgrad(:,ll) = R{ll}.cgrad(R{ll}, x(:,ll));\n\t\t\t\tRdenom(:,ll) = R{ll}.denom(R{ll}, x(:,ll));\n\t\t\tend\n\n\t\t\tnum = nblock * grad - pgrad;\n\t\t\tden = denom + Rdenom;\t% semi-constant denom\n\n\t\t\tx = x + num ./ den;\t\t% the update!\n%%\t\t\tx = x + ((x-xold) .* Lden + num) ./ den; % the update!\n\t\t\tx = max(x,0);\t\t% enforce nonnegativity\n\t\t\tx = min(x,pixmax);\t% enforce upper bound constraint\n%%\t\tend\n\tend\n\n\tif chat, printf('Range %g %g', min(x), max(x)), end\n\txs(:,:,it) = x;\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/de_pl_osps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3626199249882209}} {"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 Rubberband()\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\n\n\n% Immersed Structure Geometric / Dynamic Parameters %\nN = 2*Nx; % Number of Lagrangian Pts. (2x resolution of Eulerian grid)\na = 0.2; % Length of semi-major axis.\nb = 0.2; % Length of semi-minor axis.\nds_Rest = 0; % Resting length of springs\nstruct_name = 'rubberband'; % Name for .vertex, .spring, etc files.\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Immsersed_Boundary_Geometry(N,a,b);\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 .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 = 1e7;\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);\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 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 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 );\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,rmin,rmax)\n\n% The immsersed structure is an ellipse %\nt = 2*pi/N;\nfor i=1:N\n \n xLag(i) = 0.25 + rmax * cos( 2*pi/N*(i-1) );\n yLag(i) = 0.25 + rmin * sin( 2*pi/N*(i-1) );\nend", "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_Moving_Rubberband/Rubberband.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.36252952540656586}} {"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\" THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% file: get_rate_diff_ci3.m\n% computes confidence interval\n% - assumes x's are the number of successes in n Bernoulli trials\n% - finds confidence interval around the estimate for r1-r2\n% - with confidence level 1 - alpha\n% - finds a symmetrical two-sided interval, unless one side\n% would cross zero or one, in which case the interval is \n% offset.\n\n% 030113 tdr created\n\nfunction ci = get_rate_diff_ci3(x1,A1,x2,A2,alpha,method,verbose)\n% balanced width\n\nr1_hat = x1/A1; r2_hat = x2/A2; delta_r_hat = r1_hat - r2_hat;\n\ntolerance = 1e-6;\nmax_count = 50;\ncount = 0;\n\n%set limits on search for width\nwidth_too_small = 0; width_too_big = 1e12;\n\n%check that width_too_big is indeed too big\na = delta_r_hat - width_too_big; b = delta_r_hat + width_too_big; \nlower_tail_contribution = 1- rate_diff(x1,A1,x2,A2,a); upper_tail_contribution = rate_diff(x1,A1,x2,A2,b);\nalpha_width_too_big = lower_tail_contribution + upper_tail_contribution;\nif alpha_width_too_big > alpha, error('Failure to set upper bound on CI width'); end;\n\n% set initial guess and corresponding alpha\nwidth_guess = (width_too_big + width_too_small)/2;\na = delta_r_hat - width_guess; b = delta_r_hat + width_guess; \nlower_tail_contribution = 1- rate_diff(x1,A1,x2,A2,a); upper_tail_contribution = rate_diff(x1,A1,x2,A2,b);\nalpha_guess = lower_tail_contribution + upper_tail_contribution;\n\n% binary search\nwhile (abs(alpha_guess - alpha) > tolerance & (count < max_count))\n if (alpha_guess < alpha)\n width_too_big = width_guess;\n width_guess = (width_too_small + width_guess)/2;\n else\n width_too_small = width_guess;\n width_guess = (width_too_big + width_guess)/2;\n end;\n count = count+1;\n a = delta_r_hat - width_guess; b = delta_r_hat + width_guess; \n lower_tail_contribution = 1- rate_diff(x1,A1,x2,A2,a); upper_tail_contribution = rate_diff(x1,A1,x2,A2,b);\n alpha_guess = lower_tail_contribution + upper_tail_contribution;\nend;\n\nci = [delta_r_hat a b];\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/3031-accurate-confidence-intervals/ci_tool/get_rate_diff_ci3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.362430456252567}} {"text": "% SP_EVAL_BOUNDARY_SIDE: Construct the space structure of one side of the boundary.\n%\n% sp_side = sp_eval_boundary_side (sp, msh_side)\n%\n% INPUTS:\n%\n% sp: space object (see sp_scalar)\n% msh_side: mesh structure containing the information of the quadrature\n% rule on the boundary edge (see msh_cartesian/msh_eval_boundary_side)\n%\n% OUTPUT:\n%\n% sp_side: structure that contains the following fields\n% (see the article for a detailed description)\n%\n% FIELD_NAME (SIZE) DESCRIPTION\n% ncomp (scalar) number of components of the functions of the space (actually, 1)\n% nsh_max (scalar) maximum number of shape functions per element\n% nsh (1 x msh_side.nel vector) actual number of shape functions per each element\n% ndof (scalar) total number of degrees of freedom\n% connectivity (nsh_max x msh_side.nel vector) indices of basis functions that do not vanish in each element\n% shape_functions (msh_side.nqn x nsh_max x msh_side.nel) basis functions evaluated at each quadrature node in each element\n% dofs (1 x ndof vector) numbering of the degrees of freedom in the volumetric space\n%\n% Copyright (C) 2009, 2010 Carlo de Falco\n% Copyright (C) 2011, 2015 Rafael Vazquez\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\nfunction sp_side = sp_eval_boundary_side (sp, msh_side)\n\n iside = msh_side.side_number;\n sp_side = sp_precompute (sp.boundary(iside), msh_side);\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/@sp_scalar/sp_eval_boundary_side.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.3621682238273678}} {"text": "function p = prior_sqrtt(varargin)\n%PRIOR_SQRTT Student-t prior structure for the square root of the parameter\n% \n% Description\n% P = PRIOR_SQRTT('PARAM1', VALUE1, 'PARAM2', VALUE2, ...) \n% creates for the square root of the parameter Student's\n% t-distribution prior structure in which the named parameters\n% have the specified values. Any unspecified parameters are set\n% to default values.\n%\n% P = PRIOR_SQRTT(P, 'PARAM1', VALUE1, 'PARAM2', VALUE2, ...)\n% modify a prior structure with the named parameters altered\n% with the specified values.\n%\n% Parameters for Student-t prior [default]\n% mu - location [0]\n% s2 - scale [1]\n% nu - degrees of freedom [4]\n% mu_prior - prior for mu [prior_fixed]\n% s2_prior - prior for s2 [prior_fixed]\n% nu_prior - prior for nu [prior_fixed]\n%\n% See also\n% PRIOR_t, PRIOR_*\n\n% Copyright (c) 2000-2001,2010 Aki Vehtari\n% Copyright (c) 2009 Jarno Vanhatalo\n% Copyright (c) 2010 Jaakko Riihim�ki\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 = 'PRIOR_SQRTT';\n ip.addOptional('p', [], @isstruct);\n ip.addParamValue('mu',0, @(x) isscalar(x));\n ip.addParamValue('mu_prior',[], @(x) isstruct(x) || isempty(x));\n ip.addParamValue('s2',1, @(x) isscalar(x) && x>0);\n ip.addParamValue('s2_prior',[], @(x) isstruct(x) || isempty(x));\n ip.addParamValue('nu',4, @(x) isscalar(x) && x>0);\n ip.addParamValue('nu_prior',[], @(x) isstruct(x) || isempty(x));\n ip.parse(varargin{:});\n p=ip.Results.p;\n \n if isempty(p)\n init=true;\n p.type = 'Sqrt-t';\n else\n if ~isfield(p,'type') && ~isequal(p.type,'Sqrt-t')\n error('First argument does not seem to be a valid prior structure')\n end\n init=false;\n end\n\n % Initialize parameters\n if init || ~ismember('mu',ip.UsingDefaults)\n p.mu = ip.Results.mu;\n end\n if init || ~ismember('s2',ip.UsingDefaults)\n p.s2 = ip.Results.s2;\n end\n if init || ~ismember('nu',ip.UsingDefaults)\n p.nu = ip.Results.nu;\n end\n % Initialize prior structure\n if init\n p.p=[];\n end\n if init || ~ismember('mu_prior',ip.UsingDefaults)\n p.p.mu=ip.Results.mu_prior;\n end\n if init || ~ismember('s2_prior',ip.UsingDefaults)\n p.p.s2=ip.Results.s2_prior;\n end\n if init || ~ismember('nu_prior',ip.UsingDefaults)\n p.p.nu=ip.Results.nu_prior;\n end\n\n if init\n % set functions\n p.fh.pak = @prior_sqrtt_pak;\n p.fh.unpak = @prior_sqrtt_unpak;\n p.fh.lp = @prior_sqrtt_lp;\n p.fh.lpg = @prior_sqrtt_lpg;\n p.fh.recappend = @prior_sqrtt_recappend;\n end\n\nend\n\nfunction [w, s] = prior_sqrtt_pak(p)\n \n w=[];\n s={};\n if ~isempty(p.p.mu)\n w = p.mu;\n s=[s; 'Sqrt-Student-t.mu'];\n end \n if ~isempty(p.p.s2)\n w = [w log(p.s2)];\n s=[s; 'log(Sqrt-Student-t.s2)'];\n end\n if ~isempty(p.p.nu)\n w = [w log(p.nu)];\n s=[s; 'log(Sqrt-Student-t.nu)'];\n end\nend\n\nfunction [p, w] = prior_sqrtt_unpak(p, w)\n \n if ~isempty(p.p.mu)\n i1=1;\n p.mu = w(i1);\n w = w(i1+1:end);\n end\n if ~isempty(p.p.s2)\n i1=1;\n p.s2 = exp(w(i1));\n w = w(i1+1:end);\n end\n if ~isempty(p.p.nu)\n i1=1;\n p.nu = exp(w(i1));\n w = w(i1+1:end);\n end\nend\n\nfunction lp = prior_sqrtt_lp(x, p)\n \n lJ = -log(2*sqrt(x)); % log(1/(2*x^(1/2))) log(|J|) of transformation\n xt = sqrt(x); % transformation\n lp = sum(gammaln((p.nu+1)./2) - gammaln(p.nu./2) - 0.5*log(p.nu.*pi.*p.s2) - (p.nu+1)./2.*log(1+(xt-p.mu).^2./p.nu./p.s2) + lJ);\n \n if ~isempty(p.p.mu)\n lp = lp + p.p.mu.fh.lp(p.mu, p.p.mu);\n end\n if ~isempty(p.p.s2)\n lp = lp + p.p.s2.fh.lp(p.s2, p.p.s2) + log(p.s2);\n end\n if ~isempty(p.p.nu)\n lp = lp + p.p.nu.fh.lp(p.nu, p.p.nu) + log(p.nu);\n end\nend\n\nfunction lpg = prior_sqrtt_lpg(x, p)\n\n lJg = -1./(2*x); % gradient of log(|J|) of transformation\n xt = sqrt(x); % transformation\n xtg = 1./(2*sqrt(x)); % derivative of transformation\n lpg = xtg.*(-(p.nu+1).*(xt-p.mu)./(p.nu.*p.s2 + (xt-p.mu).^2)) + lJg;\n \n if ~isempty(p.p.mu)\n lpgmu = sum((p.nu+1).*(xt-p.mu)./(p.nu.*p.s2 + (xt-p.mu).^2)) + p.p.mu.fh.lpg(p.mu, p.p.mu);\n lpg = [lpg lpgmu];\n end\n if ~isempty(p.p.s2)\n lpgs2 = (sum(-1./(2.*p.s2)+((p.nu + 1)*(p.mu - xt)^2)./(2*p.s2*((p.mu-xt)^2 + p.nu*p.s2))) + p.p.s2.fh.lpg(p.s2, p.p.s2)).*p.s2 + 1;\n lpg = [lpg lpgs2];\n end\n if ~isempty(p.p.nu)\n lpgnu = (0.5*sum(digamma1((p.nu+1)./2)-digamma1(p.nu./2)-1./p.nu-log(1+(xt-p.mu).^2./p.nu./p.s2)+(p.nu+1)./(1+(xt-p.mu).^2./p.nu./p.s2).*(xt-p.mu).^2./p.s2./p.nu.^2) + p.p.nu.fh.lpg(p.nu, p.p.nu)).*p.nu + 1;\n lpg = [lpg lpgnu];\n end\nend\n\nfunction rec = prior_sqrtt_recappend(rec, ri, p)\n% The parameters are not sampled in any case.\n rec = rec;\n if ~isempty(p.p.mu)\n rec.mu(ri,:) = p.mu;\n end \n if ~isempty(p.p.s2)\n rec.s2(ri,:) = p.s2;\n end\n if ~isempty(p.p.nu)\n rec.nu(ri,:) = p.nu;\n end\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/dist/prior_sqrtt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3618375330280303}} {"text": "function prandtl_values_test ( )\n\n%*****************************************************************************80\n%\n%% PRANDTL_VALUES_TEST demonstrates the use of PRANDTL_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRANDTL_VALUES_TEST:\\n' );\n fprintf ( 1, ' PRANDTL_VALUES stores values of\\n' );\n fprintf ( 1, ' the Prandtl number of water\\n' );\n fprintf ( 1, ' as a function of temperature and pressure.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T P Pr(T,P)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, tc, p, pr ] = prandtl_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %12f %24.16f\\n', tc, p, pr );\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/test_values/prandtl_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.3617124852144536}} {"text": "function [tracks, revived, dropped_criteria, dropped_vicinity] = tolerance_track_lnn( eddies_path, type, time_frequency, tolerance, minimumArea ) % old args: eddies, time_frequency, tolerance\n%TOLERANCE_TRACK_LNN Tracking eddies by lnn method with loss tolerance\n\n% ---- NOTE ----: This is not the regular version of track_lnn. This\n% version of track_lnn will interpolate fake eddies in-between two close\n% tracks. Our theory is that these nearby tracks are the same eddy, but\n% the eddy on the missing day just wasn't strong enough to be picked up\n% by the original track_lnn. We created this function to try to recover\n% some of the dropped eddies so that we could connect the broken tracks.\n\n% For each eddy in a timestep, all eddies in next timestep within a boundary are checked to see if there's an eddy\n% that qualifies some conditions to be stitched to current eddy. The north, south and east bounds are the gate\n% distance while the west bound is computed based on rossby-phase_speed.\n% Input:\n% eddies_path: The path to the directory where eddies that were detected\n% by eddyscan were saved\n% type: Cyclone type of eddies ('anticyc' or 'cyclonic')\n% time_frequency: Number of days between timesteps. For weekly data, put\n% 7, for daily data, put 1\n% tolerance: Number of timesteps an eddy can be lost for\n% minimumArea: Minimum area of the eddies we want to include in the\n% tracking. I.E. eddy size is 4+, but we only want to\n% include eddies of size 9+ in the tracks. Set minimumArea\n% to 9\n%\n% Understanding the columns of the tracks\n% Column 1 is the latitude of the centroid of the eddy\n% Column 2 is the longitude of the centroid of the eddy\n% Column 3 is the time slice (day) that the eddy is from. To use this data to\n% get the actual day that the eddy is from, use this value as an index to a\n% dates array, and the return value of your dates array will be the day the\n% eddy is from.\n% Column 4 is the index in the struct array of eddies for that particular\n% day. If you get the correct eddies struct that corresponds to the date in\n% column 3, the value in this column is the index in that struct where this\n% actual eddy resides. It is through getting the appropriate struct and\n% accessing the appropriate entry that we relate this track data to actual\n% eddies in the struct.\n% Column 5 is whether the eddy in the tracking data is a \"fake\" eddy or\n% not. Normal eddies will be denoted by a '0' in the fifth column. Fake\n% eddies that are generated by this tolerance_track_lnn function will have\n% a '1' in the fifth column.\n\n\n%% Setting constants\ntemp = load('rossby_daily_phase_speeds.mat');\nrossby_phase_speed = temp.rossby_daily_phase_speeds;\nrossby_phase_speed(:, 3) = rossby_phase_speed(:, 3) * time_frequency;\n\ngate_distance = 150/7 * time_frequency; % 150km is default maximum travel distance for 1 week\ngate_distance_in_degree = km2deg(gate_distance);\n\n% Make lat and lon to be in [-180 180]\nrossby_phase_speed(rossby_phase_speed(:, 2) > 180, 2) = rossby_phase_speed(rossby_phase_speed(:, 2) > 180, 2) - 360;\nrossby_phase_speed(rossby_phase_speed(:, 2) < -180, 2) = rossby_phase_speed(rossby_phase_speed(:, 2) < -180, 2) + 360;\nmax_rossby_lat = max(rossby_phase_speed(:, 1));\nmin_rossby_lat = min(rossby_phase_speed(:, 1));\n\nrangesearch_radius = 5; % euclidean radius in degree for rangesearch\n\n% All next eddies with longitude in range [min_lon (min_lon + pad_range)] and [(max_lon - pad_range) max_lon] will be\n% duplicated with longitude lon+360 or lon-360 to make sure Euclidean distances can still get the eddies on the other\n% side of the map\npad_range = 5;\nrevived = 0;\ndropped_criteria = 0;\ndropped_vicinity = 0;\n\neddies_names = get_eddies_names(eddies_path, type);\neddy_length = length(eddies_names);\nfake_eddy_count = ones(eddy_length, 1);\neddies = cell(eddy_length, 1);\nindices = cell(eddy_length, 1);\norig_count = zeros(eddy_length, 1);\n[eddies, indices, orig_count] = load_eddies_cell(eddies, indices, orig_count, eddies_names, minimumArea);\n\n%% Begin tracking\ntracks = {};\n\ncurr_track_indexes = nan(length(eddies{1}), 1); % track index of first eddies\n\nfor curr_time_step = 1:(length(eddies) - 1)\n curr_eddies_coordinates = [[eddies{curr_time_step}.Lat]' [eddies{curr_time_step}.Lon]'];\n next_eddies_coordinates = [[eddies{curr_time_step + 1}.Lat]' [eddies{curr_time_step + 1}.Lon]'];\n orig_next_eddies_coordinates_length = size(next_eddies_coordinates, 1);\n \n curr_real_indices = indices{curr_time_step};\n next_real_indices = indices{curr_time_step + 1};\n % eddy entries for connecting tracks.\n \n disp(curr_time_step)\n \n % The availability of next eddies, will be updated when an in-ranged eddy matches current eddy and the tracks are updated\n next_eddies_availabilities = true(size(next_eddies_coordinates, 1), 1);\n % Index of the tracks of the tracked next eddies, NaN for untracked eddies\n next_eddies_track_indexes = NaN(size(next_eddies_coordinates, 1), 1);\n \n % First, pad the next eddies so that euclidean distances don't mess up eddy distances at the edge of world map\n [padding_eddy_index, padding_eddies] = pad_eddies(next_eddies_coordinates, pad_range);\n padded_next_eddies = [next_eddies_coordinates; padding_eddies];\n \n padding_eddies_length = size(padding_eddies, 1);\n \n % Get in-ranged next eddies\n [next_padded_eddy_in_range_indexes, ~] = ...\n rangesearch(padded_next_eddies(:, 1:2), curr_eddies_coordinates(:, 1:2), rangesearch_radius);\n \n %next_padded_eddy_in_range_indexes =\n \n % Get distances from current eddies to in-ranged next eddies\n [dists, first_curr_eddy_index_in_distance_data] = get_eddy_distances(curr_eddies_coordinates, padded_next_eddies, ...\n next_padded_eddy_in_range_indexes);\n \n % Get westbound of curr eddies\n westbounds = get_west_bounds(curr_eddies_coordinates(:, 1:2), gate_distance, rossby_phase_speed, ...\n max_rossby_lat, min_rossby_lat);\n % For each current eddy, check if any in-ranged next eddy matches and update tracks\n for curr_eddy_index = 1:size(curr_eddies_coordinates, 1)\n % Index of the distance between current eddy and next eddy in the dists array\n curr_distance_index = first_curr_eddy_index_in_distance_data(curr_eddy_index);\n eddies_within_range = 0;\n matched = false;\n \n if curr_eddy_index <= length(curr_real_indices)\n curr_real_index = curr_real_indices(curr_eddy_index);\n else\n curr_real_index = orig_count(curr_time_step) + (curr_eddy_index - length(curr_real_indices));\n end\n \n for next_padded_eddy_index = next_padded_eddy_in_range_indexes{curr_eddy_index}\n % Get real next eddy index\n if next_padded_eddy_index > orig_next_eddies_coordinates_length && next_padded_eddy_index < orig_next_eddies_coordinates_length + ...\n padding_eddies_length + 1\n % This is index of a padded eddy\n next_eddy_index = padding_eddy_index(next_padded_eddy_index - orig_next_eddies_coordinates_length);\n else\n next_eddy_index = next_padded_eddy_index;\n end\n \n % Check if the next eddy matches the current eddy\n if next_eddies_availabilities(next_eddy_index)\n % Only check available next eddies\n curr_eddy_lat = curr_eddies_coordinates(curr_eddy_index, 1);\n curr_eddy_lon = curr_eddies_coordinates(curr_eddy_index, 2);\n next_eddy_lat = next_eddies_coordinates(next_eddy_index, 1);\n next_eddy_lon = next_eddies_coordinates(next_eddy_index, 2);\n \n next_real_index = next_real_indices(next_eddy_index);\n \n if ~is_within_range(curr_eddy_lat, curr_eddy_lon, next_eddy_lat, next_eddy_lon, ...\n dists(curr_distance_index), westbounds(curr_eddy_index), gate_distance, gate_distance_in_degree)\n continue;\n else\n eddies_within_range = eddies_within_range + 1;\n end\n \n if is_matched(eddies{curr_time_step}(curr_eddy_index), eddies{curr_time_step + 1}(next_eddy_index));\n \n % Update tracks and get out of the loop\n if isnan(curr_track_indexes(curr_eddy_index))\n % new track\n track_id = length(tracks) + 1;\n tracks{track_id}(1, :) = ...\n [curr_eddy_lat curr_eddy_lon curr_time_step curr_real_index];\n tracks{track_id}(2, :) = ...\n [next_eddy_lat next_eddy_lon (curr_time_step + 1) next_real_index];\n else\n % old track\n track_id = curr_track_indexes(curr_eddy_index);\n %check if track is flagged\n if length(tracks{track_id}(end,:)) == 5\n if tracks{track_id}(end,5) ~= 0\n revived = revived + 1;\n %need to interpolate new locations for flagged\n %track entries\n for i = 1:size((tracks{track_id}), 1)\n if tracks{track_id}(i,5) ~= 0\n flag = tracks{track_id}(i,5);\n break\n end\n end\n \n number_of_flags_at_end = 0;\n for j = size(tracks{track_id},1):1\n if tracks{track_id}(j,5) ~= 0\n number_of_flags_at_end = number_of_flags_at_end + 1;\n else\n break;\n end\n end\n \n last_real_track_index = size(tracks{track_id},1) - number_of_flags_at_end;\n \n lat_increment = (next_eddy_lat - tracks{track_id}(last_real_track_index, 1))/(number_of_flags_at_end + 1);\n lon_increment = (next_eddy_lon - tracks{track_id}(last_real_track_index, 2))/(number_of_flags_at_end + 1);\n %now just increment the flagged tracks' lat and lon by these amounts\n for k = last_real_track_index + 1: size(tracks{track_id},1)\n tracks{track_id}(k,1) = tracks{track_id}(last_real_track_index,1) + (k - last_real_track_index)*lat_increment;\n tracks{track_id}(k,2) = tracks{track_id}(last_real_track_index,2) + (k - last_real_track_index)*lon_increment;\n end\n end\n tracks{track_id}(end + 1, :) = ...\n [next_eddy_lat next_eddy_lon (curr_time_step + 1) next_real_index 0 ];\n else\n tracks{track_id}(end + 1, :) = ...\n [next_eddy_lat next_eddy_lon (curr_time_step + 1) next_real_index];\n end\n end\n next_eddies_track_indexes(next_eddy_index) = track_id;\n next_eddies_availabilities(next_eddy_index) = false;\n matched = true;\n break;\n end\n % getting here means that it had at least one eddy within\n % range but it wasn't a match for criteria\n \n end\n \n curr_distance_index = curr_distance_index + 1;\n \n end\n \n if ~matched\n if ~isnan(curr_track_indexes(curr_eddy_index))\n % getting here means there were no matches\n if ~eddies_within_range\n dropped_vicinity = dropped_vicinity + 1;\n else\n %there was at least one within range but none were matches\n dropped_criteria = dropped_criteria + 1;\n end\n end\n \n if tolerance > 0\n %if a track already exists, add flag for potential\n %missing track.\n %This section checks if it has the max tolerated\n %number of flagged tracks already\n if ~isnan(curr_track_indexes(curr_eddy_index))\n track_id = curr_track_indexes(curr_eddy_index);\n \n if length(tracks{track_id}(end,:)) == 5 % protect against out of bounds indexing (too large)\n if size(tracks{track_id}, 1) > tolerance %protect against negative indexing\n if tracks{track_id}(end - tolerance + 1, 5) ~= 0\n %remove flagged tracks\n \n tracks{track_id} = tracks{track_id}(1: (end - tolerance),:);\n continue;\n end\n end\n else\n %track isn't flagged at all, so add 5th column in order to add flags\n tracks{track_id}(:,5) = 0;\n end\n %won't get here if it got trimmed due to the\n %continue statement above\n %now make entry to next coordinates and eddies arrays so we can\n %search from this fake eddy in next timestep\n lat_increment = tracks{track_id}(end, 1) - tracks{track_id}(end - 1, 1);\n lon_increment = tracks{track_id}(end, 2) - tracks{track_id}(end - 1, 2);\n next_eddies_coordinates(end+1,:) = [curr_eddies_coordinates(curr_eddy_index, 1) + lat_increment ...\n curr_eddies_coordinates(curr_eddy_index, 2) + lon_increment];\n %now add the stats of the current eddy to the\n %end of the next time steps eddies, but alter\n %the coordinates\n eddies{curr_time_step + 1}(end+1) = eddies{curr_time_step}(curr_eddy_index);\n eddies{curr_time_step + 1}(end).Lat = curr_eddies_coordinates(curr_eddy_index,1) + lat_increment;%next_eddies_coordinates(end,1);\n eddies{curr_time_step + 1}(end).Lon = curr_eddies_coordinates(curr_eddy_index,2) + lon_increment;%next_eddies_coordinates(end,2);\n %make a flagged track entry with the above interpolated stats\n if ~eddies_within_range\n flag = -1; %dropped for vicinity\n else\n flag = 1; % dropped for criteria\n end\n next_size = orig_count(curr_time_step + 1) + fake_eddy_count(curr_time_step + 1);\n fake_eddy_count(curr_time_step + 1) = fake_eddy_count(curr_time_step + 1) + 1;\n tracks{track_id}(end + 1, :) = ...\n [next_eddies_coordinates(end, 1) next_eddies_coordinates(end, 2)...\n (curr_time_step + 1) next_size flag];\n next_eddies_track_indexes(length(eddies{curr_time_step + 1})) = track_id;\n next_eddies_availabilities(size(next_eddies_coordinates), 1) = false;\n end\n end\n \n end\n end\n curr_track_indexes = next_eddies_track_indexes;\n eddies{curr_time_step} = [];\n [eddies, indices, orig_count] = load_eddies_cell(eddies, indices, orig_count, eddies_names, minimumArea);\nend\n\nfor i = 1:length(tracks)\n track = tracks{i};\n [~,b] = size(track);\n if b < 5\n track(:, 5) = 0;\n tracks{i} = track;\n end\nend\n\nend\n\n\nfunction within_range = is_within_range(curr_lat, curr_lon, next_lat, next_lon, km_distance, westbound, ...\n gate_distance, gate_distance_in_degree)\n% An approximate way of checking if the eddy in next timestep is within edddy in current timestep's range,\n% following the description in D.B. Chelton et al. / Progress in Oceanography 91 (2011) page 208\n% The north, east and south bounds are defined by the gate distance while the westbound is precomputed by rossby\n% phase speed.\n% Input:\n% curr_lat: latitude of the eddy in current timestep\n% curr_lon: longitude of the eddy in current timestep\n% next_lat: latitude of the eddy in next timestep\n% next_lon: longitude of the eddy in next timestep\n% km_distance: distance in km between the eddies in current and next timestep\n% gate_distance: default value of how far an eddy can travel in one timestep in km\n% gate_distance: default value of how far an eddy can travel in one timestep in degree\n\n% Check north and south bound\nif next_lat > curr_lat + gate_distance_in_degree || next_lat < curr_lat - gate_distance_in_degree\n within_range = false; % Avoid using km2deg or deg2km because\nelse\n % Check east and west bound\n if abs(next_lon - curr_lon) > 180\n if next_lon > curr_lon\n curr_lon = curr_lon + 360;\n else\n next_lon = next_lon + 360;\n end\n end\n if next_lon >= curr_lon\n is_on_east_side = true;\n else\n is_on_east_side = false;\n end\n \n if is_on_east_side\n within_range = km_distance <= gate_distance;\n else\n within_range = km_distance <= westbound;\n end\n \nend\n\nend\n\nfunction westbounds = get_west_bounds(eddy_coordinates, gate_distance, phase_speed_data, max_rossby_lat, min_rossby_lat)\n% Getting westbound of eddies by eddy coordinates and rossby phasespeed data\n% West bound of an eddy is defined as the maximum value between 1.75 * rossby_phase_speed and default gate_distance\n% eddy_coordinates: coordinates of eddies in format [lat lon]\n% gate_distance: the default maximum distance an eddy can travel in a single timestep\n% phase_speed_data: rossby phase speed data in format [lat lon speed]\n% max_rossby_lat: to make sure eddies with latitude out of range get the default gate distance\n% min_rossby_lat: to make sure eddies with latitude out of range get the default gate distance\n\ncurr_eddy_lats = eddy_coordinates(:, 1);\ncurr_eddy_lons = eddy_coordinates(:, 2);\n% Convert eddy longtidue format to -180 to 180 to make sure knn search work\ncurr_eddy_lons(curr_eddy_lons > 180) = curr_eddy_lons(curr_eddy_lons > 180) - 360;\ncurr_eddy_lons(curr_eddy_lons < -180) = curr_eddy_lons(curr_eddy_lons < -180) + 360;\n\nnearest_ind = knnsearch(phase_speed_data(:, 1:2), [curr_eddy_lats curr_eddy_lons]);\nwestbounds = 1.75 * phase_speed_data(nearest_ind, 3);\nwestbounds(westbounds < gate_distance) = gate_distance;\n% Make sure out of range eddies get the default value\nwestbounds(curr_eddy_lats > max_rossby_lat | curr_eddy_lats < min_rossby_lat) = gate_distance;\n\nend\n\nfunction [dists, first_curr_eddy_index_in_distance_data] = get_eddy_distances(curr_eddies, next_eddies, ...\n next_eddies_indexes)\n% Get distances from current eddies to next eddies with indexes in the cell array next_eddies_indexes. This function\n% computes the distance in one distance and deg2km to increase the tracking function performance\n% Also return an array of indexes of the first appearance of a curr eddy in the distance array\n% Input:\n% curr_eddies: eddies in current timestep with format [lat lon ...]\n% next_eddies: eddies in next timestep with format [lat lon ...]\n% next_eddies_indexes: a cell array of indexes of next eddies that will be computed the distances to current eddies\n\nnext_eddy_indexes_lengths = cellfun('length', next_eddies_indexes);\nvectorized_next_eddy_indexes = [next_eddies_indexes{:}]';\nvectorized_curr_eddy_indexes = zeros(sum(next_eddy_indexes_lengths), 1);\ncurr_index = 1;\nfor i = 1:length(next_eddy_indexes_lengths)\n vectorized_curr_eddy_indexes(curr_index:(curr_index + next_eddy_indexes_lengths(i) - 1)) = i;\n curr_index = curr_index + next_eddy_indexes_lengths(i);\nend\n\ndists = deg2km(distance(curr_eddies(vectorized_curr_eddy_indexes, 1:2), ...\n next_eddies(vectorized_next_eddy_indexes, 1:2)));\n\nfirst_curr_eddy_index_in_distance_data = ones(length(next_eddy_indexes_lengths), 1);\nfor i = 2:length(next_eddy_indexes_lengths)\n first_curr_eddy_index_in_distance_data(i) = first_curr_eddy_index_in_distance_data(i - 1) + next_eddy_indexes_lengths(i - 1);\nend\n\nend\n\nfunction [padding_eddy_index, padding_eddies] = pad_eddies(eddies, pad_range)\n% Duplicate eddies in range [min_lon (min_lon + pad_range)] and [(max_lon - pad_range) max_lon] to make sure knnsearch\n% work correctly to get in-range eddies in next timestep\n% eddies: eddies in format [lat lon ...]\n% pad_range: how far we want to pad (in degree)\n\nmin_lon = min(eddies(:, 2));\nmax_lon = max(eddies(:, 2));\npadding_eddy_index = find( (eddies(:, 2) >= min_lon & eddies(:, 2) <= (min_lon + pad_range)) ...\n | (eddies(:, 2) >= (max_lon - pad_range) & eddies(:, 2) <= max_lon ) );\n\npadding_eddies = eddies(padding_eddy_index, :);\npadding_eddies(padding_eddies(:, 2) <= (min_lon + pad_range), 2) = ...\n padding_eddies(padding_eddies(:, 2) <= (min_lon + pad_range), 2) + 360;\npadding_eddies(padding_eddies(:, 2) >= (max_lon - pad_range), 2) = ...\n padding_eddies(padding_eddies(:, 2) >= (max_lon - pad_range), 2) - 360;\n\nend\n\nfunction matched = is_matched(curr_eddy, next_eddy)\n% An eddy is consider matched with current eddy if the amplitude and surface area is in range [0.25 2.75] *\n% curr_eddy_amp/surface_area\n% curr_eddy: an eddy in current timestep in format [lat lon amp surface_area]\n% next_eddy: an eddy in next timestep in format [lat lon amp surface_area]\n\ncurr_amplitude = curr_eddy.Amplitude;\nnext_amplitude = next_eddy.Amplitude;\ncurr_surface_area = curr_eddy.SurfaceArea;\nnext_surface_area = next_eddy.SurfaceArea;\n%if isempty(curr_amplitude) | isempty(next_amplitude) | isempty\n%end\nmatched_amp = curr_amplitude > .25* next_amplitude && curr_amplitude < 2.75 * next_amplitude;\nmatched_area = curr_surface_area > .25 * next_surface_area && curr_surface_area < 2.75 * next_surface_area;\n\n% matched = curr_amplitude > 0.25 * next_amplitude && curr_amplitude < 2.75 * next_amplitude ...\n% && curr_surface_area > 0.25 * next_surface_area && curr_surface_area < 2.75 * next_surface_area;\nmatched = matched_amp && matched_area;\nend\n\nfunction [eddies_names] = get_eddies_names(path, type)\n% path is the path to the eddies directory\n% type is anticyclonic or cyclonic\nif ~strcmp(path(end), '/')\n path = strcat(path, '/');\nend\nfiles = dir(path);\nx = 0;\nfor i = 1:length(files)\n if ~isempty(strfind(files(i).name, [type, '_']))\n x = x + 1;\n end\nend\neddies_names = cell(x, 1);\nx = 1;\nfor i = 1:length(files)\n if files(i).isdir && ~isequal(files(i).name, '.') && ~isequal(files(i).name, '..')\n rec_names = get_eddies_names([path, files(i).name, '/'], type);\n for j = 1:length(rec_names)\n eddies_names{x} = rec_names{j};\n x = x + 1;\n end\n continue;\n end\n file = files(i).name;\n [~, name, ext] = fileparts([path, file]);\n if ~isempty(strfind(name, [type, '_'])) && strcmp(ext, '.mat')\n eddies_names{x} = [path, file];\n x = x + 1;\n end\nend\nend\n\nfunction [modified_eddies_cell, modified_indices_cell, modified_orig_count_array] = load_eddies_cell(eddies_cell, real_indices_cell, orig_count_array, eddies_names, minimumArea)\ncount_to_load = 10;\nnames_length = length(eddies_names);\nx = 0;\npos_1 = 1;\nfor i = 1:length(eddies_cell)\n if ~isempty(eddies_cell{i})\n if x == 0\n pos_1 = i;\n end\n x = x + 1;\n end\nend\niterations = count_to_load - x;\nfirst_empty_pos = pos_1 + x;\nlast_empty_pos = first_empty_pos + iterations - 1;\nif last_empty_pos > names_length\n last_empty_pos = names_length;\nend\nfor i = first_empty_pos:last_empty_pos\n eddy_name = eddies_names{i};\n vars = load(eddy_name);\n names = fieldnames(vars);\n eddies = vars.(names{1});\n [f_eddies, real_indices, orig_count] = filter_eddies(eddies, minimumArea);\n eddies_cell{i} = f_eddies;\n real_indices_cell{i} = real_indices;\n orig_count_array(i) = orig_count;\nend\nmodified_eddies_cell = eddies_cell;\nmodified_indices_cell = real_indices_cell;\nmodified_orig_count_array = orig_count_array;\nend\n\nfunction [filtered_eddies, real_indices, original_eddy_count] = filter_eddies(eddies, minimumArea)\nstats = [eddies.Stats];\nareas = [stats.Area];\nx = 1;\noriginal_eddy_count = length(eddies);\nfor i = 1:length(eddies)\n if areas(i) >= minimumArea\n filtered_eddies(x) = eddies(i);\n real_indices(x) = i;\n x = x + 1;\n end\nend\nend", "meta": {"author": "jfaghm", "repo": "OceanEddies", "sha": "a5e33155f9cc534093c88b1a514b0c8281591755", "save_path": "github-repos/MATLAB/jfaghm-OceanEddies", "path": "github-repos/MATLAB/jfaghm-OceanEddies/OceanEddies-a5e33155f9cc534093c88b1a514b0c8281591755/track_lnn/tolerance_track_lnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.36141485620450403}} {"text": "function [granger, v, n] = ft_connectivity_granger(H, Z, S, varargin)\n\n% FT_CONNECTIVITY_GRANGER computes spectrally resolved granger causality. This\n% implementation is loosely based on the code used in Brovelli, et. al., PNAS 101,\n% 9849-9854 (2004).\n%\n% Use as\n% [granger, v, n] = ft_connectivity_granger(H, Z, S, ...)\n%\n% The input data should be\n% H = spectral transfer matrix, Nrpt x Nchan x Nchan x Nfreq (x Ntime),\n% or Nrpt x Nchancmb x Nfreq (x Ntime). Nrpt can be 1.\n% Z = the covariance matrix of the noise, Nrpt x Nchan x Nchan (x Ntime),\n% or Nrpt x Nchancmb (x Ntime).\n% S = the cross-spectral density matrix with the same dimensionality as H.\n%\n% Additional optional input arguments come as key-value pairs:\n% 'dimord' = required string specifying how to interpret the input data\n% supported values are 'rpt_chan_chan_freq(_time) and\n% 'rpt_chan_freq(_time), 'rpt_pos_pos_freq(_time)' and\n% 'rpt_pos_freq(_time)'\n% 'method' = 'granger' (default), or 'instantaneous', or 'total'\n% 'hasjack' = boolean, specifying whether the input contains leave-one-outs,\n% required for correct variance estimate (default = false)\n% 'powindx' = is a variable determining the exact computation, see below\n%\n% If the inputdata is such that the channel-pairs are linearly indexed, granger\n% causality is computed per quadruplet of consecutive entries, where the convention\n% is as follows:\n%\n% H(:, (k-1)*4 + 1, :, :, :) -> 'chan1-chan1'\n% H(:, (k-1)*4 + 2, :, :, :) -> 'chan1->chan2'\n% H(:, (k-1)*4 + 3, :, :, :) -> 'chan2->chan1'\n% H(:, (k-1)*4 + 4, :, :, :) -> 'chan2->chan2'\n%\n% The same holds for the Z and S matrices.\n%\n% Pairwise block-granger causality can be computed when the inputdata has\n% dimensionality Nchan x Nchan. In that case 'powindx' should be specified, as a 1x2\n% cell-array indexing the individual channels that go into each 'block'.\n%\n% See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Undocumented option: powindx can be a struct. In that case, blockwise\n% conditional granger can be computed.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2009-2017, 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% check for a supported dimord\nft_checkopt(varargin, 'dimord', 'char');\n\nmethod = ft_getopt(varargin, 'method', 'granger');\nhasjack = ft_getopt(varargin, 'hasjack', false);\npowindx = ft_getopt(varargin, 'powindx');\ndimord = ft_getopt(varargin, 'dimord');\n\n%FIXME speed up code and check\nsiz = size(H);\nif numel(siz)==4\n siz(5) = 1;\nend\nn = siz(1);\nNc = siz(2);\n\noutsum = zeros(siz(2:end));\noutssq = zeros(siz(2:end));\n\n% crossterms are described by chan_chan_therest\nissquare = length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2;\n\nswitch method\n case 'granger'\n \n if issquare && isempty(powindx)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % data are chan_chan_therest\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n for kk = 1:n\n for ii = 1:Nc\n for jj = 1:Nc\n if ii ~=jj\n zc = reshape(Z(kk,jj,jj,:) - Z(kk,ii,jj,:).^2./Z(kk,ii,ii,:),[1 1 1 1 siz(5)]);\n zc = repmat(zc,[1 1 1 siz(4) 1]);\n numer = reshape(abs(S(kk,ii,ii,:,:)),[1 1 siz(4:end)]);\n denom = reshape(abs(S(kk,ii,ii,:,:)-zc.*abs(H(kk,ii,jj,:,:)).^2),[1 1 siz(4:end)]);\n outsum(jj,ii,:,:) = outsum(jj,ii,:,:) + log(numer./denom);\n outssq(jj,ii,:,:) = outssq(jj,ii,:,:) + (log(numer./denom)).^2;\n end\n end\n outsum(ii,ii,:,:) = 0; %self-granger set to zero\n end\n end\n \n elseif ~issquare && isempty(powindx)\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n %data are linearly indexed\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n \n for j = 1:n\n for k = 1:Nc\n %FIXME powindx is not used here anymore\n %iauto1 = sum(powindx==powindx(k,1),2)==2;\n %iauto2 = sum(powindx==powindx(k,2),2)==2;\n %icross1 = k;\n %icross2 = sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2;\n \n % The following is based on hard-coded assumptions: which is fair\n % to do if the order of the labelcmb is according to the output of\n % ft_connectivity_csd2transfer\n if mod(k-1, 4)==0\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n elseif mod(k-1, 4)==1\n iauto1=k+2;iauto2=k-1;icross1=k;icross2=k+1;\n elseif mod(k-1, 4)==2\n iauto1=k-2;iauto2=k+1;icross1=k;icross2=k-1;\n elseif mod(k-1, 4)==3\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n end\n \n zc = Z(j,iauto2,:,:) - Z(j,icross1,:,:).^2./Z(j,iauto1,:,:);\n numer = abs(S(j,iauto1,:,:));\n denom = abs(S(j,iauto1,:,:)-zc(:,:,ones(1,size(H,3)),:).*abs(H(j,icross1,:,:)).^2);\n outsum(icross2,:,:) = outsum(icross2,:,:) + reshape(log(numer./denom), [1 siz(3:end)]);\n outssq(icross2,:,:) = outssq(icross2,:,:) + reshape((log(numer./denom)).^2, [1 siz(3:end)]);\n end\n end\n \n elseif issquare && iscell(powindx)\n %%%%%%%%%%%%%%%%%%%\n % blockwise granger\n %%%%%%%%%%%%%%%%%%%\n \n % H = transfer function nchan x nchan x nfreq\n % Z = noise covariance nchan x nchan\n % S = crosspectrum nchan x nchan x nfreq\n % powindx{k} is a list of indices for block k\n \n nblock = numel(powindx);\n n = size(H,1);\n nfreq = size(H,4);\n \n outsum = zeros(nblock,nblock,nfreq);\n outssq = zeros(nblock,nblock,nfreq);\n \n for k = 1:nblock\n for m = (k+1):nblock\n indx = [powindx{k}(:);powindx{m}(:)];\n indx = cat(1,indx,setdiff((1:size(Z,2))',indx));\n n1 = numel(powindx{k});\n n2 = numel(powindx{m});\n ntot = numel(indx);\n indx1 = 1:n1;\n indx1_ = (1:ntot)'; indx1_(indx1) = [];\n indx2 = n1+(1:n2);\n indx12_ = (1:ntot)'; indx12_([indx1(:);indx2(:)]) = [];\n \n for kk = 1:n\n tmpZ = reshape(Z(kk,indx,indx), [ntot ntot]);\n \n % projection matrix for therest+block2 -> block1\n P1 = [eye(n1) zeros(n1,ntot-n1);\n -tmpZ(indx1_,indx1)/tmpZ(indx1,indx1) eye(ntot-n1)];\n \n % projection matrix for therest+block1 -> block2\n P2 = [ eye(n1) -tmpZ(indx1,indx2)/tmpZ(indx2,indx2) zeros(n1,ntot-n1-n2);\n zeros(n2,n1) eye(n2) zeros(n2, ntot-n1-n2);\n zeros(ntot-n1-n2,n1) -tmpZ(indx12_,indx2)/tmpZ(indx2,indx2) eye(ntot-n1-n2)];\n \n % invert only once\n for jj = 1:nfreq\n % post multiply transfer matrix with the inverse of the projection matrix\n % this is equivalent to time domain pre multiplication with P\n Sj = reshape(S(kk,indx,indx,jj), [ntot ntot]);\n Zj = tmpZ; %(:,:);\n H1 = reshape(H(kk,indx,indx,jj), [ntot ntot])/P1;\n H2 = reshape(H(kk,indx,indx,jj), [ntot ntot])/P2;\n num1 = abs(det(Sj(indx1,indx1))); % numerical round off leads to tiny imaginary components\n num2 = abs(det(Sj(indx2,indx2))); % numerical round off leads to tiny imaginary components\n denom1 = abs(det(H1(indx1,indx1)*Zj(indx1,indx1)*H1(indx1,indx1)'));\n denom2 = abs(det(H2(indx2,indx2)*Zj(indx2,indx2)*H2(indx2,indx2)'));\n %rH1 = real(H1(indx1,indx1));\n %rH2 = real(H2(indx2,indx2));\n %iH1 = imag(H1(indx1,indx1));\n %iH2 = imag(H2(indx2,indx2));\n %h1 = rH1*Zj(indx1,indx1)*rH1' + iH1*Zj(indx1,indx1)*iH1';\n %h2 = rH2*Zj(indx2,indx2)*rH2' + iH2*Zj(indx2,indx2)*iH2';\n %denom1 = abs(det(h1));\n %denom2 = abs(det(h2));\n \n outsum(m,k,jj) = log( num1./denom1 ) + outsum(m,k,jj);\n outsum(k,m,jj) = log( num2./denom2 ) + outsum(k,m,jj);\n outssq(m,k,jj) = log( num1./denom1 ).^2 + outssq(m,k,jj);\n outssq(k,m,jj) = log( num2./denom2 ).^2 + outssq(k,m,jj);\n end\n end\n \n end\n end\n \n elseif ~issquare && isstruct(powindx) && isfield(powindx, 'n')\n %%%%%%%%%%%%%%%%%%%%%%\n %blockwise conditional\n %%%%%%%%%%%%%%%%%%%%%%\n \n n = size(H,1);\n ncmb = size(H,2);\n nfreq = size(H,3);\n ncnd = size(powindx.cmbindx,1);\n \n outsum = zeros(ncnd, nfreq);\n outssq = zeros(ncnd, nfreq);\n for k = 1:n\n tmpS = reshape(S, [ncmb nfreq]);\n tmpH = reshape(H, [ncmb nfreq]);\n tmpZ = reshape(Z, [ncmb 1]);\n tmp = blockwise_conditionalgranger(tmpS,tmpH,tmpZ,powindx.cmbindx,powindx.n);\n \n outsum = outsum + tmp;\n outssq = outssq + tmp.^2;\n end\n \n elseif ~issquare && isstruct(powindx)\n %%%%%%%%%%%%%%%%%%%%%%\n %triplet conditional\n %%%%%%%%%%%%%%%%%%%%%%\n \n % decode from the powindx struct which rows in the data correspond with\n % the triplets, and which correspond with the duplets\n ublockindx = unique(powindx.blockindx);\n nperblock = zeros(size(ublockindx));\n for k = 1:numel(ublockindx)\n nperblock(k,1) = sum(powindx.blockindx==ublockindx(k));\n end\n if ~all(ismember(nperblock,[4 9]))\n error('the data should be a mixture of trivariate and bivariate decompositions');\n end\n indx_triplets = ismember(powindx.blockindx, ublockindx(nperblock==9)); ntriplets = sum(indx_triplets)./9;\n indx_duplets = ismember(powindx.blockindx, ublockindx(nperblock==4)); nduplets = sum(indx_duplets)./4;\n \n % this assumes well-behaved powindx.cmbindx\n cmbindx2 = reshape(powindx.cmbindx(indx_duplets, 1), 2, [])';\n cmbindx3 = reshape(powindx.cmbindx(indx_triplets,1), 3, [])';\n \n cmbindx2 = cmbindx2(1:2:end,:);\n cmbindx3 = cmbindx3(1:3:end,:);\n \n cmbindx = powindx.outindx;\n \n n = size(H,1);\n siz = size(H);\n \n outsum = zeros(size(cmbindx,1), size(H,3));\n outssq = outsum;\n \n % call the low-level function\n for k = 1:n\n H3 = reshape(H(k,indx_triplets,:,:), [3 3 ntriplets siz(3:end)]);\n Z3 = reshape(Z(k,indx_triplets), [3 3 ntriplets]);\n \n H2 = reshape(H(k,indx_duplets,:,:), [2 2 nduplets siz(3:end)]);\n Z2 = reshape(Z(k,indx_duplets), [2 2 nduplets]);\n \n tmp = triplet_conditionalgranger(H3,Z3,cmbindx3,H2,Z2,cmbindx2,cmbindx);\n \n outsum = outsum + tmp;\n outssq = outssq + tmp.^2;\n end\n \n \n \n end\n \n case 'instantaneous'\n \n if issquare && isempty(powindx)\n % data are chan_chan_therest\n for kk = 1:n\n for ii = 1:Nc\n for jj = 1:Nc\n if ii ~=jj\n zc1 = reshape(Z(kk,jj,jj,:) - Z(kk,ii,jj,:).^2./Z(kk,ii,ii,:),[1 1 1 1 siz(5)]);\n zc2 = reshape(Z(kk,ii,ii,:) - Z(kk,jj,ii,:).^2./Z(kk,jj,jj,:),[1 1 1 1 siz(5)]);\n zc1 = repmat(zc1,[1 1 1 siz(4) 1]);\n zc2 = repmat(zc2,[1 1 1 siz(4) 1]);\n term1 = abs(S(kk,ii,ii,:,:)) - zc1.*abs(H(kk,ii,jj,:,:)).^2;\n term2 = abs(S(kk,jj,jj,:,:)) - zc2.*abs(H(kk,jj,ii,:,:)).^2;\n numer = term1.*term2;\n denom = abs(S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:) - S(kk,ii,jj,:,:).*S(kk,jj,ii,:,:));\n outsum(jj,ii,:,:) = outsum(jj,ii,:,:) + reshape(log(numer./denom), [1 1 siz(4:end)]);\n outssq(jj,ii,:,:) = outssq(jj,ii,:,:) + reshape((log(numer./denom)).^2, [1 1 siz(4:end)]);\n end\n end\n outsum(ii,ii,:,:) = 0; %self-granger set to zero\n end\n end\n elseif ~issquare && isempty(powindx)\n % data are linearly indexed\n for j = 1:n\n for k = 1:Nc\n %iauto1 = sum(powindx==powindx(k,1),2)==2;\n %iauto2 = sum(powindx==powindx(k,2),2)==2;\n %icross1 = k;\n %icross2 = sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2;\n if mod(k-1, 4)==0\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n elseif mod(k-1, 4)==1\n iauto1=k+2;iauto2=k-1;icross1=k;icross2=k+1;\n elseif mod(k-1, 4)==2\n iauto1=k-2;iauto2=k+1;icross1=k;icross2=k-1;\n elseif mod(k-1, 4)==3\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n end\n \n zc1 = Z(j,iauto1,:, :) - Z(j,icross2,:, :).^2./Z(j,iauto2,:, :);\n zc2 = Z(j,iauto2,:, :) - Z(j,icross1,:, :).^2./Z(j,iauto1,:, :);\n term1 = abs(S(j,iauto2,:,:)) - zc1(:,:,ones(1,size(H,3)),:).*abs(H(j,icross2,:,:)).^2;\n term2 = abs(S(j,iauto1,:,:)) - zc2(:,:,ones(1,size(H,3)),:).*abs(H(j,icross1,:,:)).^2;\n numer = term1.*term2;\n denom = abs(S(j,iauto1,:,:).*S(j,iauto2,:,:) - S(j,icross1,:,:).*S(j,icross2,:,:));\n \n outsum(icross2,:,:) = outsum(icross2,:,:) + reshape(log(numer./denom), [1 siz(3:end)]);\n outssq(icross2,:,:) = outssq(icross2,:,:) + reshape((log(numer./denom)).^2, [1 siz(3:end)]);\n end\n end\n elseif issquare && iscell(powindx)\n % blockwise granger\n % H = transfer function nchan x nchan x nfreq\n % Z = noise covariance nchan x nchan\n % S = crosspectrum nchan x nchan x nfreq\n % powindx{1} is a list of indices for block1\n % powindx{2} is a list of indices for block2\n ft_error('instantaneous causality is not implemented for blockwise factorizations');\n elseif isstruct(powindx)\n %blockwise conditional\n ft_error('blockwise conditional instantaneous causality is not implemented');\n else\n ft_error('not implemented');\n end\n \n case 'total'\n \n if issquare && isempty(powindx)\n % data are chan_chan_therest\n for kk = 1:n\n for ii = 1:Nc\n for jj = 1:Nc\n if ii ~=jj\n numer = abs(S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:));\n denom = abs(S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:) - S(kk,ii,jj,:,:).*S(kk,jj,ii,:,:));\n outsum(jj,ii,:,:) = outsum(jj,ii,:,:) + reshape(log(numer./denom), [1 1 siz(4:end)]);\n outssq(jj,ii,:,:) = outssq(jj,ii,:,:) + reshape((log(numer./denom)).^2, [1 1 siz(4:end)]);\n end\n end\n outsum(ii,ii,:,:) = 0; %self-granger set to zero\n end\n end\n elseif ~issquare && isempty(powindx)\n % data are linearly indexed\n for j = 1:n\n for k = 1:Nc\n %iauto1 = sum(powindx==powindx(k,1),2)==2;\n %iauto2 = sum(powindx==powindx(k,2),2)==2;\n %icross1 = k;\n %icross2 = sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2;\n if mod(k-1, 4)==0\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n elseif mod(k-1, 4)==1\n iauto1=k+2;iauto2=k-1;icross1=k;icross2=k+1;\n elseif mod(k-1, 4)==2\n iauto1=k-2;iauto2=k+1;icross1=k;icross2=k-1;\n elseif mod(k-1, 4)==3\n continue; % auto granger set to 0\n %iauto1=k;iauto2=k;icross1=k;icross2=k;\n end\n \n numer = abs(S(j,iauto1,:,:).*S(j,iauto2,:,:));\n denom = abs(S(j,iauto1,:,:).*S(j,iauto2,:,:) - S(j,icross1,:,:).*S(j,icross2,:,:));\n outsum(icross2,:,:) = outsum(icross2,:,:) + reshape(log(numer./denom), [1 siz(3:end)]);\n outssq(icross2,:,:) = outssq(icross2,:,:) + reshape((log(numer./denom)).^2, [1 siz(3:end)]);\n end\n end\n elseif issquare && iscell(powindx)\n % blockwise total interdependence\n \n % S = crosspectrum nchan x nchan x nfreq\n % powindx{k} is a list of indices for block k\n \n nblock = numel(powindx);\n n = size(S,1);\n nfreq = size(S,4);\n \n outsum = zeros(nblock,nblock,nfreq);\n outssq = zeros(nblock,nblock,nfreq);\n \n for k = 1:nblock\n for m = (k+1):nblock\n indx = [powindx{k}(:);powindx{m}(:)];\n n1 = numel(powindx{k});\n n2 = numel(powindx{m});\n ntot = n1+n2;\n indx1 = 1:n1;\n indx2 = (n1+1):ntot;\n \n for kk = 1:n\n for jj = 1:nfreq\n Sj = reshape(S(kk,indx,indx,jj), [ntot ntot]);\n num1 = abs(det(Sj(indx1,indx1))); % numerical round off leads to tiny imaginary components\n num2 = abs(det(Sj(indx2,indx2))); % numerical round off leads to tiny imaginary components\n num = num1.*num2;\n denom = abs(det(Sj));\n \n outsum(m,k,jj) = log( num./denom ) + outsum(m,k,jj);\n outsum(k,m,jj) = log( num./denom ) + outsum(k,m,jj);\n outssq(m,k,jj) = log( num./denom ).^2 + outssq(m,k,jj);\n outssq(k,m,jj) = log( num./denom ).^2 + outssq(k,m,jj);\n end\n end\n \n end\n end\n \n elseif issquare && isstruct(powindx)\n %blockwise conditional\n ft_error('blockwise conditional total interdependence is not implemented');\n end\n \n case 'iis'\n ft_warning('THIS IS EXPERIMENTAL CODE, USE AT YOUR OWN RISK!');\n % this is experimental\n if ~issquare && isempty(powindx)\n A = transfer2coeffs(shiftdim(H),(0:size(H,3)-1));\n ncmb = size(A,1)./4;\n iis = coeffs2iis(reshape(A,[2 2 ncmb size(A,2)]),reshape(Z,[2 2 ncmb]));\n iis = repmat(iis(:),[1 4])';\n outsum = iis(:);\n outssq = nan(size(outsum));\n else\n ft_error('iis can only be computed when the input contains sets of bivariate factorizations');\n end\n \n otherwise\n ft_error('unsupported output requested');\nend\n\ngranger = outsum./n;\nif n>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", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/connectivity/ft_connectivity_granger.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3611441282085781}} {"text": "function [alpha_log_all,alpha_log_hc,h_0_threshold,n_soundings] = sounding_new(start_date,end_date,plot_flag,hydro,wet)\n% This function computes the refractivity and integrated LOS delays.\n% In addition it will estimate the power-law decay cofficient and height at which the relative \n% tropopsheric delays are approximately zero. Both coefficients are given based on the full heifght range\n% and the lower height range up to hc. Note that alpha is dimensionless and\n% h0 is the height in m units. Sounding data needs to be stored in the \n% correct format! Read below:\n% \n% ---- Input ----\n% All inputs will be retreived from the aps_parms file. Set the inputs by change \n% setparm_aps('Parameter_name',new_value)\n%\n% Variables include:\n% look_angle Mean look angle of the data in rad. By default this is\n% assumed to be 21 degees.\n% lambda Radar wavelength in m. By default this is assumed to be\n% 0.056 cm (C-band).\n% h_0_threshold Consider only soundings that go up till the h0 threshold in km.\n% Being the height at which the differential delay is small.\n% When '0' is specified it is estimated from the data. Note that\n% \t\t soundings should go up high enough to cover the lower tropopshere (up to 16 km).\n% By default the threshold is set to be 15 km.\n% h_thres_hc Height range [0 h_thres_hc] over which the power-law decay \n% coefficient is estimated computed. By default this is set to be 4 km.\n% start_date\t Start date of the sounding period, by default [], full period\n% is considered. Specify as a string in 'yyyymmdd' format.\n% end_date End date of the sounding period, by default [], full period \n% is considered. Specify as a string in 'yyyymmdd' format.\n% time_stamp\t Include a time stamp to it. This is a column vector with \n% strings e.g. ['00';'12'] for 00Z and 12Z. Only those files \n% ending with this are considered in the computation.\n% sounding_dir\t Optional argument giving directly the full path to the soundings.\n% The files on this path should be the YYYYMMDD_HH.mat files. \n% error_promp_flag By default ([] or 'y') this is turn on. Can be usefull to turn of\n% when running in a batch mode. Instead NaN values will be outputed.\n%\n% Output:\n% alpha and h0. The computed sounding delays: refractivity, the (mean) LOS delay [m],\n% the (mean) LOS phase delay [rad], and corresponding heights are appended to the existing \n% sounding .mat files. \n%\n%\n% NOTE on data format:\n% sounding data needs to be stored in a folder called sounding_data, \n% within your processing directory. Within this folder, each sounding \n% aquisition needs to be stored in as 8 digit .mat files, e.g. YYYYMMDD_HH.mat \n% format, with the pressure (hPa), temperature (degree), relative humidity (%)\n% and heights (m) as matlab variables P, T, RH and h.\n%\n% OPTIONAL: \n% - visulize intermediate results (refractivity, delay,\n% mean delay and hc relation with H), by putting plot_flag to 1. By\n% default this is not done.\n% - Overwrite all the data to recompute the delays by putting recompute flag to 1\n%\n% Copyright (C) 2015 Bekaert David - University of Leeds\n% Email: eedpsb@leeds.ac.uk or davidbekaert.com\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 along\n% with this program; if not, write to the Free Software Foundation, Inc.,\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% September 2010 --- Bekaert David \n% Modifications:\n% 01/11/2011: DB Modify from initial version\n% 01/12/2011: DB Making compatible to other datasets\n% 01/11/2012: DB Made program more efficient\n% 05/11/2012: DB Fix bug in loading of the files\n% 10/02/2013: DB Integrate with other part of toolbox\n% 18/03/2013: DB Include a time stamp to it.\n% 18/03/2013: DB Include a start and end time.\n% 18/03/2013: DB Account for NaN values by removing them for all data columns\n% 19/03/2013: DB Set the min height range of the delay curve by comparing it to \n% the median of the height range\n% 19/03/2013: DB Include a flag to suppress error messages by lack of sounding data and \n% directly pass NaN value through it.\n% 25/03/2013: DB Compute the power law coefficient from loglog relation\n% 03/04/2013: DB Include h0 estimation option from the net delays\n% 24/04/2013: DB Incorporate in the bigger aps toolbox. Change towards\n% loglog powerlaw computation.\n% 10/05/2013: DB Loading the default parameters from the parms_aps file.\n% 02/10/2013: DB Change filename to sounding and clean the syntax\n% 29/10/2013: DB Allow the look angle to be a specified as a file\n% 29/11/2013: DB Get stamps processing flag before lookangle loading\n% 06/11/2014: DB Add hydrostatic and wet delay options\n\n% --------- VARIABELS ---------- %\nfontsize = 20; % fontsize of the figures\nsave_fig =0; % when 1 save figures\nrecompute = 0; % Use earlier computed data unless it is missing\nif nargin<3 || isempty(plot_flag)\n plot_flag =0; % Control plots of the refractivity, delay and net delay.\nend\nif nargin<4\n hydro=1;\nend\nif nargin<5\n wet=1;\nend\nnetdelay_color = [];\ncurdir = pwd;\n\nhydro\nwet\n\n%% Setting the defaults were needed\nlook_angle = getparm_aps('look_angle');\nlambda = getparm_aps('lambda');\nh_0_threshold= getparm_aps('sounding_h0');\nh_thres_hc= getparm_aps('sounding_h_alpha_thres');\n\nif nargin<1 || isempty(start_date)\n start_date= getparm_aps('sounding_start_date');\nend \nif nargin<2 || isempty(end_date)\n end_date= getparm_aps('sounding_end_date');\nend\ntime_stamp= getparm_aps('sounding_time_stamp');\nsounding_dir= getparm_aps('sounding_dir');\nerror_promp_flag= getparm_aps('sounding_error_promp');\n\nclear h_0_threshold_default h_thres_hc_default look_angle_default lambda_default\n\nstamps_processed = getparm_aps('stamps_processed');\n\n% checking if the look angle is a file or not\nif ischar(look_angle)\n\t% look angle is specified as a file [rad]\n\tif strcmp(stamps_processed,'y')\n look_angle = load(look_angle);\n\t look_angle = look_angle.la;\n look_angle = mean(look_angle);\n\telse\n\t look_angle = load(look_angle);\n\t % use the mean of the look angles\n\t look_angle = mean(look_angle);\n\tend\nend\n\n% convert units\ntheta = look_angle; % mean angle of incidence [rad]\nh_0_threshold = h_0_threshold*1000; % put threshold to [m]\nh_thres_hc = h_thres_hc*1000; % put threshold to [m]\nclear look_angle\n\n% get height information\nif plot_flag==1\n hgt_matfile = getparm_aps('hgt_matfile');\n hgt = load(hgt_matfile);\n max_height = max(hgt.hgt);\n min_height = min(hgt.hgt);\n clear hgt hgt_matfile\nend\n\n% Include a while loop. Depending on error message flag, it will break out of the loop and pass\n% NaN values as output.\ncontinue_flag =1;\nabord_flag = 0;\t\t% when 1 abnormal termination get NaN values instead.\nwhile continue_flag\n\n%% Getting the file list of the sounding data\nif isempty(sounding_dir)~=1\n\tif exist([sounding_dir filesep],'dir')~=7\n error('myApp:argChk', ['The specified filepath of the sounding data does not exist,... \\nAbort,... \\n'])\n end \n\tcd(sounding_dir)\nelse\n\tif exist('sounding_data/','dir')~=7\n \t\terror('myApp:argChk', ['There is no sounding_data directory,... \\nAbort,... \\n']) \n\tend\n\tcd sounding_data\nend\nif exist('sounding.list','file')~=2\n % making a list of all the sounding files\n [dummy dummy2] = system('echo sounding_list > sounding.list');\n clear dummy dummy2\n for k=1:size(time_stamp,1)\n command_str = ['ls [0-9]???????_' time_stamp(k,:) '.mat >> sounding.list']; \n [dummy dummy2] = system(command_str);\n clear dummy dummy2\n end\nend\ntemp = tdfread('sounding.list');\n[dummy dummy2] = system('rm sounding.list');\nclear dummy dummy2\ndate_list_temp = temp.sounding_list(:,[1:8]);\nsounding_list = temp.sounding_list;\n\n% selecting a date range when requested\nclear ix\n\nif isempty(start_date)~=1 && isempty(end_date)~=1\n\tix = find(datenum(date_list_temp,'yyyymmdd')>=datenum(start_date,'yyyymmdd') & datenum(date_list_temp,'yyyymmdd')<=datenum(end_date,'yyyymmdd'));\n\tsave_name = ['Delay_' start_date '_' end_date];\nelseif isempty(start_date)~=1 && isempty(end_date)==1\n ix = find(datenum(date_list_temp,'yyyymmdd')>=datenum(start_date,'yyyymmdd'));\n save_name = ['Delay_' start_date '_end' ];\nelseif isempty(start_date)==1 && isempty(end_date)~=1\n ix = find(datenum(date_list_temp,'yyyymmdd')<=datenum(end_date,'yyyymmdd'));\n save_name = ['Delay_start_' end_date];\nelse\n save_name = ['Delay'];\nend\n% checking if the save figures folder exist\nif save_fig ==1 & exist('figures','dir')~=7\n mkdir('figures') \nend\n\n\nif isempty(start_date)~=1 || isempty(end_date)~=1\n\tif isempty(ix)~=1\n\t\tdate_list_temp = date_list_temp(ix,:);\n\t\tsounding_list = sounding_list(ix,:);\n\telse\n\t\tfprintf('No sounding has been acquired in this period \\n' )\n\t\tcontinue_flag = 0;\n abord_flag = 1;\n break\n\tend\n\tclear temp ix\nend\n\n\n\n%% Computing refractivity\nfprintf('Computing the refractivity \\n')\nix_skip_sounding = [];\t\t\t% in case soundings are rejected along the way\nwarning('off','MATLAB:load:variableNotFound')\nfor i=1:size(sounding_list,1)\n temp = load(sounding_list(i,:),'h_min_souding'); \n if isfield(temp,'h_min_souding') && recompute==0\n % storing variables for latter processing\n h_range(i,1) = temp.h_min_souding; % [m]\n \n if plot_flag==1\n data = load(sounding_list(i,:),'h_max_souding','Ndelay');\n Ndelay = data.Ndelay;\n else\n data = load(sounding_list(i,:),'h_max_souding');\n end\n h_range(i,2) = data.h_max_souding; % [m]\n clear data\n skip_sounding = 0;\n\n else\n load(sounding_list(i,:)); \n % This includes variables: \n % - P (pressure in [hPa])\n % - T (temperature in [degrees])\n % - RH (relative humidity in [%]) \n % - h (altitude in [m])\n \n \n % coping with NaN values in the RH data\n ix1 = find(isnan(RH)==1);\n ix2 = find(isnan(h)==1);\n ix = unique([ix1; ix2]);\n P(ix)=[]; \n RH(ix)=[]; \n T(ix)=[]; \n h(ix)=[]; \n clear ix ix1 ix2\n\n % coping with errors in the data when a double recording was made\n ix_repeat = find(diff(sort(h))==0);\n h(ix_repeat) = [];\n P(ix_repeat)=[];\n RH(ix_repeat)=[]; \n T(ix_repeat)=[];\n clear ix_repeat\n\n\n % Checking if there is still data left\n if isempty(h)==1 && size(sounding_list,1)==1 && strcmp(error_promp_flag,'y') \n error('myApp:argChk', ['Datafile contains no numeric data. \\n'])\n elseif isempty(h)==1 \n fprintf([sounding_list(i,:) ' sounding skipped as it containes no numeric data\\n'])\n skip_sounding = 1;\n ix_skip_sounding = [ix_skip_sounding ; i];\n else\n skip_sounding = 0;\n end\n\n % when possible compute the refractivity\n if skip_sounding==1\n % case of no data\n h_range(i,1) = NaN; % [m]\n h_range(i,2) = NaN; % [m]\n else\t\n % saterated pressure es\n Rv = 461.524; % [J/K]\n T0 = 273.16; % [k] \n L = 2.5e6; % [J/kg] Latent heat\n e0 = 6.11; % [hPa] \n T = T+273.15; % [degree] to [K] Temperature\n es = e0.*exp(L./Rv.*(1./T0-1./T));\n\n % partial pressure of water vapour e\n RH = RH./100; % [%] to [-] Relative humidity\n e = RH.*es; % [hPa]\n\n % Refractivety - Hydrostatic term\n k1 = 77.6; % [K/hPa]\n Ndelay.Nhydro = k1.*P./T; % [K/hPa*hPa/K] = [-] \n\n % Refractivity - Wet term\n k2_n = 23.3; % [K/hPa]\n k3 = 3.75e5; % [K^2/hPa]\n Ndelay.Nwet = k2_n.*e./T+k3.*e./T.^2; % [ppm]\n\n % refractivety \n Ndelay.N = Ndelay.Nhydro+Ndelay.Nwet; \n\n % save the heights of the delay as well\n Ndelay.h = h;\n\n\n h_min_souding = min(h);\n h_max_souding = max(h);\n\n % saving the data\n save(sounding_list(i,:),'-append','Ndelay','h_min_souding','h_max_souding')\n\n % storing variables for latter processing\n h_range(i,1) = h_min_souding; % [m]\n h_range(i,2) = h_max_souding; % [m]\n clear h_max_souding h_min_souding\n \n end\n end\n\n if floor(i/10)*10 == i\n fprintf([num2str(i) ' refraction dates completed out of ' num2str(size(sounding_list,1)) ' \\n']);\n end\n \t\n % Test visualizing refractivity with height\n if plot_flag==1 && skip_sounding~=1\n if i==1\n figure1 = figure('name','Refractivity with height'); \n ylabel('Height [km]','fontsize',12)\n xlabel('Refractivity [ppm]','fontsize',12)\n line_colors = hsv(size(sounding_list,1));\n box on\n set(gca,'fontsize',12)\n end\n figure(figure1)\n hold on\n if hydro==1 && wet==0 \n if i==1\n title('Refractivity with height','fontsize',12)\n end\n plot(Ndelay.Nhydro,Ndelay.h./1000,'-','color',line_colors(i,:)) \n elseif hydro==0 && wet==1\n if i==1\n title('Refractivity with height (hydro)','fontsize',12)\n end\n plot(Ndelay.Nwet,Ndelay.h./1000,'-','color',line_colors(i,:)) \n else\n if i==1\n title('Refractivity with height (wet)','fontsize',12)\n end\n plot(Ndelay.N,Ndelay.h./1000,'-','color',line_colors(i,:)) \n end\n end\n clear P h RH T Ndelay N\nend\nclear Rv T0 L e0 es e k1 k2_n k3 i figure1\n% remove those sounding acqusitions that have no data coverage\nif isempty(ix_skip_sounding)~=1\n\tsounding_list(ix_skip_sounding,:)=[];\n\th_range(ix_skip_sounding,:)=[];\t\nend\n\n\n\n%% Computing the height range\nfprintf('Computing delay \\n')\n\n% defining the height range (equal for the whole dataset)\nh_max = min(h_range(:,2));\nh_max_mean = mean(h_range(:,2));\n\nif h_0_threshold<=0\n % estimate h0 from the data\n h0_estimate_flag = 1;\n h_0_threshold = 0;\t\t\t% set the height threshold low such all the delays can be used to compute a net delay \nelse\n h0_estimate_flag = 0; \nend\n\n\n% check if the delays goes high enough\nif h_maxh_0_threshold && h0_estimate_flag==0\n % h0 is lower than the h_max. \n h_max = h_0_threshold;\nelseif h_max_mean-h_max >1000 && h0_estimate_flag==1\n % Make h_max larger possible as the h0 value needs to be estimated\n % this will be at the cost of some soundings but they will be included\n % latter on\n h_max = h_max_mean;\n ix = find(h_range(:,2) 1000\n h_min = h_min_median;\n\n ix = find(h_range(:,1)>h_min);\n n = [1:size(sounding_list,1)]';\n n(ix)=[];\n h_range(ix,:)=[];\n if isempty(ix)==1\n error('myApp:argChk', ['This should not occur.'])\n end\n clear ix\n if size(n,1)<3 || isempty(n)==1\n error('myApp:argChk', 'Too few soundings are left for mean delay computation. Check for incomplete data files or differences in sounding height ranges \\n.')\n end\n if size(n,1)<5\n fprintf(['Only ',num2str(size(n,1)),' soundings are used to compute mean delay \\n']);\n end\n sounding_list = sounding_list(n,:);\n clear n\nend\n\nfprintf([num2str(size(sounding_list,1)),' soundings are used to compute mean delay \\n']);\nh_delay = [h_min:1:h_max]'; % set to 1 [m] interval\nclear h_range h_min h_max\n \n\n%% computing the integrated refractivity\nfor i=1:size(sounding_list,1)\n compute_flag=0;\n % checking if it has already been computed. If so use this data at once\n % else compute it\n temp = load(sounding_list(i,:),'h_delay'); \n if isfield(temp,'h_delay') && recompute==0\n h_delay_temp=temp.h_delay;\n if h_delay(1)==h_delay_temp(1) && h_delay(end)==h_delay_temp(end)\n if hydro==1 && wet==0\n data = load(sounding_list(i,:),'delay_hydro','phase_delay_hydro');\n if ~isfield(data,'delay_hydro')\n compute_flag=1;\n else\n delay = data.delay_hydro;\n phase_delay = data.phase_delay_hydro;\n end\n elseif hydro==0 && wet==1 \n data = load(sounding_list(i,:),'delay_wet','phase_delay_wet');\n if ~isfield(data,'delay_wet')\n compute_flag=1;\n else\n delay = data.delay_wet;\n phase_delay = data.phase_delay_wet;\n end\n else\n data = load(sounding_list(i,:),'delay','phase_delay');\n if ~isfield(data,'delay')\n compute_flag=1;\n else\n delay = data.delay;\n phase_delay = data.phase_delay;\n end\n end\n \n if compute_flag==0\n % store all delays for later mean LOS delay computation\n delay_matrix(1:length(delay),i) = delay;\n % do the same for the phase delay\n phase_delay_matrix(1:length(delay),i) = phase_delay; \n compute_flag=0;\n end\n else\n % delay needs to be computed\n compute_flag=1;\n end\n else\n compute_flag=1;\n end\n\n \n if compute_flag==1 \n load(sounding_list(i,:),'Ndelay')\n \n % interpolation to 1 m interval \n if hydro==1 && wet==0\n N_regular = interp1(Ndelay.h,Ndelay.Nhydro,h_delay,'linear');\n elseif hydro==0 && wet==1\n N_regular = interp1(Ndelay.h,Ndelay.Nwet,h_delay,'linear');\n else\n N_regular = interp1(Ndelay.h,Ndelay.N,h_delay,'linear');\n end\n \n \n\n % integration of refractivity with height (= delay) and projection on the LOS\n delay = zeros([length(N_regular) 1]); % initialize\n delay = flipud(cumsum(flipud(N_regular))./10^6.*cos(theta)); % 10^6 factor is for correction of ppm, theta for LOS projection\n phase_delay = delay*4*pi./lambda; \n clear scale N_regular \n\n % store all delays for later mean LOS delay computation\n delay_matrix(1:length(delay),i) = delay;\n % do the same for the phase delay\n phase_delay_matrix(1:length(delay),i) = phase_delay; \n\n % saving the data\n if hydro==1 && wet==0\n delay_hydro = delay;\n phase_delay_hydro = phase_delay;\n save(sounding_list(i,:),'-append','delay_hydro','phase_delay_hydro','h_delay')\n elseif hydro==0 && wet==1\n phase_delay_wet=phase_delay;\n delay_wet = delay;\n save(sounding_list(i,:),'-append','delay_wet','phase_delay_wet','h_delay')\n else\n save(sounding_list(i,:),'-append','delay','phase_delay','h_delay')\n end\n \n end\n\n % Test visualizing delay with height \n if plot_flag==1\n if i==1\n figure2 = figure('name','Delay with height'); \n xlabel('LOS phase delay [rad]','fontsize',fontsize)\n ylabel('Height [km]','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n end\n figure(figure2)\n hold on\n plot(phase_delay,h_delay./1000,'-','color',[0.7 0.7 0.7])\n box on\n\n if i==size(sounding_list,1) && h0_estimate_flag==1\n Ax1 = gca;\n ylimits = get(Ax1,'ylim');\n set(Ax1,'ylim',[0 ylimits(2)])\n % adding a second axis \n box on\n set(gca,'fontsize',fontsize)\n if hydro==1 && wet==0\n title({'LOS hydro delay [m]',' '},'fontsize',fontsize)\n fig_save_name = ['figures' filesep 'Delay_hydro_curves_all.eps'];\n elseif hydro==0 && wet==1\n title({'LOS wet delay [m]',' '},'fontsize',fontsize)\n fig_save_name = ['figures' filesep 'Delay_wet_curves_all.eps'];\n else\n title({'LOS delay [m]',' '},'fontsize',fontsize)\n fig_save_name = ['figures' filesep 'Delay_curves_all.eps'];\n end\n Ax2 = axes('Position',get(Ax1,'Position'),'XAxisLocation','top');\n set(Ax2,'ylim',get(Ax1,'ylim'),'ytick',[],'yticklabel','');\n xlims = get(Ax1,'xlim');\n xtick_new = get(Ax1,'xtick')./xlims(2);\n new_x_label = get(Ax1,'xtick').*lambda./(4*pi);\n xtick_labels = round((new_x_label)*100)./100;\n xtick_labels = num2str(xtick_labels');\n set(Ax2,'xtick',xtick_new,'xticklabel',xtick_labels);\n set(Ax2,'color','none');\n set(Ax2,'fontsize',fontsize)\n box on\n % saving of the figure when requested\n if save_fig==1 \n set(figure2,'PaperPositionMode','auto')\n print(figure2,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n clear figure2 \n end\n end\n clear Ndelay.N Ndelay.h delay \nend\nclear i theta\n\nn_soundings = size(delay_matrix,2);\n\n\nif n_soundings <=3\n continue_flag = 0;\n abord_flag = 1;\n break\nend\n\n\n%% estimating h0 from the delay curves, when required.\n% this is based on the net delays and used the std \n% as criteria for setting h0\nif h0_estimate_flag==1\n n_netdelays_max = 400;\n if (n_soundings*n_soundings-n_soundings)/2<=n_netdelays_max\n \tfprintf(['Estimating h0 from all (', num2str((n_soundings*n_soundings-n_soundings)/2),') possible net delay combinations \\n'])\n \tix1_random=repmat(1:n_soundings,n_soundings,1);\n ix1_random=single(ix1_random);\n \tix2_random=ix1_random';\n \tix_temp=logical(tril(ones(n_soundings)))&~eye(n_soundings);\n \tix_random=[ix1_random(ix_temp),ix2_random(ix_temp)]; \n clear ix1_random ix2_random\n else\n fprintf(['Estimating h0 from (', num2str(n_netdelays_max),') net delay combinations \\n'])\n % take 2 random sets of n_netdelays_max\n new_set_search = 1;\n loop_counter = 0;\n while new_set_search\n ix1_random = ceil(rand(n_netdelays_max*5,1)*n_soundings);\n ix2_random = ceil(rand(n_netdelays_max*5,1)*n_soundings);\n ix_random = [ix1_random ix2_random];\n clear ix1_random ix2_random\n \n % remove those net delays of the same date\n ix_temp = find(ix_random(:,1)-ix_random(:,2)==0);\n ix_random(ix_temp,:)=[];\n clear ix_temp\n \n % remove repetition of pair combination\n ix_random = unique(ix_random,'rows');\n \n % check if enough combinations are left otherwize rerun\n if size(ix_random,1)>=n_netdelays_max\n ix_random(n_netdelays_max+1:end,:)=[];\n new_set_search=0;\n\n end\n loop_counter = loop_counter+1;\n if loop_counter == 50\n fprintf('Having difficulty determining net delay combinations \\n')\n keyboard\n end\n end\n end\n \n % computation of the net delay\n netdelays = delay_matrix(:,ix_random(:,1)) - delay_matrix(:,ix_random(:,2));\n netphasedelays = phase_delay_matrix(:,ix_random(:,1)) - phase_delay_matrix(:,ix_random(:,2));\n\n if plot_flag==1\n fig_netdelay = figure('name','Net delays');\n if isempty(netdelay_color)\n plot(netdelays,h_delay/1000) \n else\n plot(netdelays,h_delay/1000,'color',netdelay_color) \n end\n max_spacing = max([abs([min(min(netdelays)) max(max(netdelays))])]);\n xlim([-1.1*max_spacing max_spacing*1.1]);\n xlabel('Net LOS delay [m]','fontsize',fontsize)\n ylabel('Height [km]','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n \n \n \n fig_netphasedelay = figure('name','Net phase delays');\n if isempty(netdelay_color)\n plot(netphasedelays,h_delay/1000) \n else\n plot(netphasedelays,h_delay/1000,'color',netdelay_color) \n end\n max_spacing = max([abs([min(min(netphasedelays)) max(max(netphasedelays))])]);\n xlim([-1.1*max_spacing max_spacing*1.1]);\n xlabel('\\Delta\\phi_{tropo} [rad]','fontsize',fontsize)\n ylabel('Height [km]','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n \n \n \n \n end\n \n \n \n \n % computation of the netdelay standard deviation\n netdelays_std = std(netdelays,[],2);\n clear netdelays\n \n % find the height at which the lowest standard deviation becomes larger\n % than the 0.5 cm threshold.\n fprintf(['Estimating h0 from the height at which the std varies more than ' num2str(0.05) ' cm \\n'])\n ix = (netdelays_std<=0.0005);\n h_0_threshold = min(h_delay(ix));\n clear ix\n ix = find(h_delay>h_0_threshold);\n \n % make some sanity checks\n if h_0_threshold<6000\n fprintf(['h0 is estimated to be ' num2str(h_0_threshold/1000) ' km. This is low abord. \\n'])\n if strcmp(error_promp_flag,'y') \n error('myApp:argChk', 'Put h_0_threshold to a lower value. \\n')\n else\n fprintf('Try setting h_0_threshold manually \\n')\n continue_flag = 0; \n abord_flag = 1; \n break\n end\n else\n % plotting the estimate h0 on the netdelay curve\n if plot_flag==1\n figure(fig_netdelay)\n hold on\n plot(get(gca,'xlim'),[h_0_threshold/1000 h_0_threshold/1000],'k--')\n \n figure(fig_netphasedelay)\n hold on\n plot(get(gca,'xlim'),[h_0_threshold/1000 h_0_threshold/1000],'k--')\n \n % saving of the figure when requested\n if save_fig==1\n fig_save_name = ['figures' filesep 'NetDelay_curves.eps'];\n set(fig_netdelay,'PaperPositionMode','auto')\n print(fig_netdelay,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n \n fig_save_name = ['figures' filesep 'NetPhaseDelay_curves.eps'];\n set(fig_netphasedelay,'PaperPositionMode','auto')\n print(fig_netphasedelay,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n end\n \n fprintf(['h0 is estimated to be ' num2str(h_0_threshold/1000) ' km. \\n']) \n\n % removing all the other variables\n h_delay(ix:end)=[];\n delay_matrix(ix:end,:)=[];\n phase_delay_matrix(ix:end,:)=[];\n \n % setting the start of the integration to h_0\n delay_matrix = delay_matrix - repmat(delay_matrix(end,:),length(h_delay),1);\n phase_delay_matrix = phase_delay_matrix - repmat(phase_delay_matrix(end,:),length(h_delay),1);\n \n if plot_flag==1\n figure2 = figure('name','Delay with height'); \n plot(phase_delay_matrix,h_delay./1000,'-','color',[0.7 0.7 0.7] ) \n xlabel('LOS phase delay [rad]','fontsize',fontsize)\n ylabel('Height [km]','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n % saving of the figure when requested\n if save_fig==1\n fig_save_name = ['figures' filesep 'Delay_curves.eps'];\n set(figure2,'PaperPositionMode','auto')\n print(figure2,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n\n end\n end\nend \n\n%% Computing mean delay \nfprintf('Computing mean delay \\n')\ndelay_mean = mean(delay_matrix,2); % given in [m]\nphase_delay_mean = mean(phase_delay_matrix,2);\nif plot_flag==1\n % plot mean delay on top of the existing figure\n figure(figure2)\n hold on \n plot(phase_delay_mean,h_delay./1000,'k-','linewidth',2) \n Ax1 = gca;\n ylimits = get(Ax1,'ylim');\n set(Ax1,'ylim',[0 ylimits(2)])\n % adding a second axis \n box on\n set(gca,'fontsize',fontsize)\n title({'LOS delay [m]',' '},'fontsize',fontsize)\n Ax2 = axes('Position',get(Ax1,'Position'),'XAxisLocation','top');\n set(Ax2,'ylim',get(Ax1,'ylim'),'ytick',[],'yticklabel','');\n xlims = get(Ax1,'xlim');\n xtick_new = get(Ax1,'xtick')./xlims(2);\n new_x_label = get(Ax1,'xtick').*lambda./(4*pi);\n xtick_labels = round((new_x_label)*100)./100;\n xtick_labels = num2str(xtick_labels');\n set(Ax2,'xtick',xtick_new,'xticklabel',xtick_labels);\n set(Ax2,'color','none');\n set(Ax2,'fontsize',fontsize)\n % saving of the figure when requested\n if save_fig==1\n fig_save_name = ['figures' filesep 'Delay_curves.eps'];\n set(figure2,'PaperPositionMode','auto')\n print(figure2,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n clear figure2\n\n % an individual figure for the mean delay\n figure4 = figure('name','Mean delay with height'); \n xlabel('LOS phase delay [rad]','fontsize',fontsize)\n ylabel('Height [km]','fontsize',fontsize)\n set(gca,'fontsize',fontsize) \n hold on \n plot(phase_delay_mean,h_delay./1000,'k-','linewidth',2)\n set(gca,'fontsize',fontsize)\nend\nsave([save_name '.mat'],'delay_mean','h_delay','n_soundings','delay_matrix')\n\n\n\n\n\n%% estimating the power law directly from the log log plot\n% computing the loglog powerlaw\n\n\nh_log = log10(h_0_threshold-h_delay);\nphi_delay_log = log10(phase_delay_mean);\ndelay_log = log10(delay_mean);\nA = [h_log ones(size(h_log))];\n\n% based on the full height range\nix_all = find(h_log<=0.001);\nA_all = A;\nA_all(ix_all,:)=[];\ndelay_log_temp_all = delay_log;\ndelay_log_temp_all(ix_all,:)=[];\nphase_delay_log_temp_all = phi_delay_log;\nphase_delay_log_temp_all(ix_all,:)=[];\ncoeff_all = inv(A_all'*A_all)*A_all'*delay_log_temp_all;\ncoeff_all_phase = inv(A_all'*A_all)*A_all'*phase_delay_log_temp_all;\nalpha_log_all = coeff_all(1);\nK_log_all = exp(coeff_all(2));\n\n\n% based on the height range till hc_threshold\nix_hc = find(h_log<=0.001 | h_delay>h_thres_hc);\nA_hc = A;\nA_hc(ix_hc,:)=[];\ndelay_log_temp_hc = delay_log;\ndelay_log_temp_hc(ix_hc,:)=[];\nphase_delay_log_temp_hc = phi_delay_log;\nphase_delay_log_temp_hc(ix_hc,:)=[];\ncoeff_hc = inv(A_hc'*A_hc)*A_hc'*delay_log_temp_hc;\ncoeff_hc_phase = inv(A_hc'*A_hc)*A_hc'*phase_delay_log_temp_hc;\nalpha_log_hc = coeff_hc(1);\nK_log_hc = exp(coeff_hc(2));\n\n\n\nif plot_flag==1\n xlimits = [log10(h_0_threshold-max_height) log10(h_0_threshold+1)];\n % an individual figure for the mean delay\n figure4_1 = figure('name','Log-Log plot of the Mean delay with height');\n ylabel('Log(tropopsheric LOS delay [m])','fontsize',fontsize)\n xlabel('Height [km])','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n hold on\n plot(h_log,delay_log,'k-','linewidth',2) \n hold on\n plot(A_hc(:,1),A_hc*coeff_hc,'r--','linewidth',2)\n set(gca,'fontsize',fontsize)\n % plotting the powerlaw based on the lower height range\n hold on \n xlim(xlimits)\n ylimits = get(gca,'ylim');\n legend('Mean delay','Power law',2)\n legend boxoff\n set(gca,'xtick',[get(gca,'xtick') log10(h_0_threshold)],'xticklabel',num2str([get(gca,'xtick') log10(h_0_threshold)]'))\n\n % updating the lables to be heights\n temp_loc = get(gca,'xtick');\n temp = round((h_0_threshold-10.^temp_loc)/1000*100)/100;\n temp_str = num2str(temp');\n set(gca,'xtick',temp_loc,'xticklabel',temp_str)\n box on\n \n \n if save_fig==1\n fig_save_name = ['figures' filesep 'loglog_mean_delay.eps'];\n set(figure4_1,'PaperPositionMode','auto')\n print(figure4_1,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n \n \n \n \n \n \n \n % an individual figure for the mean delay\n figure4_2 = figure('name','Log-Log plot of the Mean phase delay with height');\n ylabel('Log(\\phi_{tropo} [rad])','fontsize',fontsize)\n xlabel('Height [km])','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n hold on\n plot(h_log,phi_delay_log,'k-','linewidth',2) \n hold on\n plot(A_hc(:,1),A_hc*coeff_hc_phase,'r--','linewidth',2)\n set(gca,'fontsize',fontsize)\n % plotting the powerlaw based on the lower height range\n hold on \n xlim(xlimits)\n ylimits = get(gca,'ylim');\n legend('Mean delay','Power law',2)\n legend boxoff\n set(gca,'xtick',[get(gca,'xtick') log10(h_0_threshold)],'xticklabel',num2str([get(gca,'xtick') log10(h_0_threshold)]'))\n\n % updating the lables to be heights\n temp_loc = get(gca,'xtick');\n temp = round((h_0_threshold-10.^temp_loc)/1000*100)/100;\n temp_str = num2str(temp');\n set(gca,'xtick',temp_loc,'xticklabel',temp_str)\n box on\n \n \n if save_fig==1\n fig_save_name = ['figures' filesep 'loglog_mean_phasedelay.eps'];\n set(figure4_2,'PaperPositionMode','auto')\n print(figure4_2,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n \n \n \n \n \n \n \n \n \n \nend\n\nsave([save_name '.mat'],'-append','alpha_log_all','alpha_log_hc')\nclear ix_all A_all delay_log_temp_all coeff_all ix_hc A_hc delay_log_temp_hc coeff_hc delay_log phi_delay_log h_log\n\n\n\n\n\n\n%% evaluating the performance of the estimation by plotting the estimated powerlaw wrt to the mean delay from sounding\nif plot_flag==1\n % powerlaw estimated from log log plot full height range\n delay_log_all = K_log_all*(h_0_threshold-h_delay).^alpha_log_all;\n\n % powerlaw delay from log log plot estimated from the 0 till hc height range \n delay_log_hc = K_log_hc*(h_0_threshold-h_delay).^alpha_log_hc;\n % plot mean delay on top of the existing figure\n hfig_powerlawdelay = figure('name','Fitted power law delay to mean delay curve');\n plot(delay_mean,h_delay./1000,'k-','linewidth',2)\n hold on\n plot(delay_log_hc,h_delay./1000,'r-','linewidth',2)\n hold on\n xlimits = get(gca,'xlim');\n plot([xlimits(1) xlimits(2)],[max_height max_height]./1000,'k--')\n legend('Mean delay','Fitted power law','Max height of the region')\n ylabel('Height [km]','fontsize',fontsize)\n xlabel('LOS delay [m]','fontsize',fontsize)\n set(gca,'fontsize',fontsize)\n box on\n \n if save_fig==1\n fig_save_name = ['figures' filesep 'MeanDelay_PowerLawDelay.eps'];\n set(hfig_powerlawdelay,'PaperPositionMode','auto')\n print(hfig_powerlawdelay,'-depsc','-r150',fig_save_name)\n clear fig_save_name\n end\n clear hfig_powerlawdelay\n \nend\n\n\n\ncontinue_flag=0;\nabord_flag=0;\n\nend\n\n% The while loop was existed because of an error statement.\nif abord_flag == 1\n\talpha_log_all = NaN;\n\talpha_log_hc = NaN;\n\tn_soundings=NaN;\n h_0_threshold = NaN;\n\tfprintf('Early termination \\n')\nelse\n h_0_threshold = h_0_threshold/1000; % put threshold to [km]\n\tfprintf('DONE \\n')\nend\n\ncd(curdir)\n\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/sounding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.36114412820857805}} {"text": "function [Xc3,tri3,xc3,xp3,dc3,xc_texture,nc3,conf_nc3,Nn3] = Meshing(Xc2,xc2,xp2,Thresh_connect,N_smoothing,om,T,N_x,N_y,fc,cc,kc,alpha_c,fp,cp,kp,alpha_p),\n\n% scaled connection threshold\n\nT_connect = Thresh_connect; \t% scaled threshold\n\nfprintf(1,'Organizing the data...\\n');\n\nxp_frac = rem(xp2,1);\nxc_frac = rem(xc2(1,:),1);\n\nif std(xp_frac) > std(xc_frac),\n disp('Dense depth map in the image coordinates');\n temporal = 1;\n spatial = 0;\nelse\n disp('Dense depth map in the cross image and projector frame');\n temporal = 0;\n spatial = 1;\nend;\n\n\nif spatial,\n \n % Something to fix the organization:\n xpmin = min(xp2);\n xp_ind = round(unique(xp2 - xpmin));\n step_xp = min(diff(xp_ind)); %xp_ind(2) - xp_ind(1);\n xp4 = (xp2 - xpmin)/step_xp + xpmin;\n \n xpmin = min(xp4);\n xpmax = max(xp4);\n \n xcmin = min(xc2(2,:));\n xcmax = max(xc2(2,:));\n \nelse\n \n % Something to fix the organization:\n \n xp4 = xc2(1,:);\n \n xpmin = min(xp4);\n xpmax = max(xp4);\n \n xcmin = min(xc2(2,:));\n xcmax = max(xc2(2,:));\n \nend;\n\n\nNrow = xcmax - xcmin + 1;\nNcol = xpmax - xpmin + 1;\n\nXmesh = zeros(Nrow,Ncol);\nYmesh = zeros(Nrow,Ncol);\nZmesh = zeros(Nrow,Ncol);\nCmesh = zeros(Nrow,Ncol);\nxcmesh = zeros(Nrow,Ncol);\nycmesh = zeros(Nrow,Ncol);\n\nind_col = round(xp4 - xpmin + 1);\nind_row = xc2(2,:) - xcmin + 1;\nind = ind_row + (ind_col-1)*Nrow;\nni = length(ind);\n\n\n% Good format for ivview:\nXmesh(ind) = Xc2(1,:);\nYmesh(ind) = Xc2(2,:); \t\t% tries to have it in the right position\nZmesh(ind) = Xc2(3,:); \t\t% tries to have it in the right position\nCmesh(ind) = ones(1,ni);\nxcmesh(ind) = xc2(1,:);\nycmesh(ind) = xc2(2,:);\n\n% Hypothesis on the triangles:\n\nD1 = Cmesh(2:Nrow,1:(Ncol-1)) & Cmesh(1:(Nrow-1),2:Ncol);\nF1 = Cmesh(1:(Nrow-1),1:(Ncol-1)) & D1;\nF2 = Cmesh(2:Nrow,2:Ncol) & D1;\nC1 = (F1 | F2);\n\nD2 = Cmesh(1:(Nrow-1),1:(Ncol-1)) & Cmesh(2:Nrow,2:Ncol);\nF3 = Cmesh(1:(Nrow-1),2:Ncol) & D2;\nF4 = Cmesh(2:Nrow,1:(Ncol-1)) & D2;\nC2 = (F3 | F4);\n\nAmbi = C1 & C2; \t\t\t% ambiguous zones\nDiv1 = C1 & ~C2; \t\t\t% needs to check relative distance of points\nDiv2 = ~C1 & C2; \t\t\t% needs to check relative distance of points\n\n% diagonal measure:\n\n%Dm1 = abs(Zmesh(2:Nrow,1:(Ncol-1)) - Zmesh(1:(Nrow-1),2:Ncol));\n\n\nDm1 =( Xmesh(2:Nrow,1:(Ncol-1)) - Xmesh(1:(Nrow-1),2:Ncol)).^2 + (Ymesh(2:Nrow,1:(Ncol-1)) - Ymesh(1:(Nrow-1),2:Ncol)).^2 + (Zmesh(2:Nrow,1:(Ncol-1)) - Zmesh(1:(Nrow-1),2:Ncol)).^2;\n\n%Dm2 = abs(Zmesh(1:(Nrow-1),1:(Ncol-1)) - Zmesh(2:Nrow,2:Ncol));\n\nDm2 = (Xmesh(1:(Nrow-1),1:(Ncol-1)) - Xmesh(2:Nrow,2:Ncol)).^2 + (Ymesh(1:(Nrow-1),1:(Ncol-1)) - Ymesh(2:Nrow,2:Ncol)).^2 + (Zmesh(1:(Nrow-1),1:(Ncol-1)) - Zmesh(2:Nrow,2:Ncol)).^2 ;\n\nDiv1n = Div1 | ((Dm1 <= Dm2)&Ambi);\nDiv2n = Div2 | ((Dm2 < Dm1)&Ambi);\n\nDiv11 = Div1n & F1;\nDiv12 = Div1n & F2;\nDiv21 = Div2n & F3;\nDiv22 = Div2n & F4;\n\n\n% look at local difference:\n\ndZ_r = abs(Zmesh(:,2:Ncol)-Zmesh(:,1:(Ncol-1)));\ndZ_c = abs(Zmesh(2:Nrow,:)-Zmesh(1:(Nrow-1),:));\n\nDiv11 = Div11 & (dZ_r(1:(Nrow-1),:) 1) & (is < Nrow) & (js > 1) & (js < Ncol));\n \n is = is(indd);\n js = js(indd);\n \n sm = is + (js-1)*(Nrow);\n sm_t = is + (js-1)*(Nrow) - 1;\n sm_b = is + (js-1)*(Nrow) + 1;\n sm_r = is + (js)*(Nrow);\n sm_l = is + (js-2)*(Nrow);\n \n sm_tr = is + (js)*(Nrow) - 1;\n sm_br = is + (js)*(Nrow) + 1;\n sm_tl = is + (js-2)*(Nrow) -1;\n sm_bl = is + (js-2)*(Nrow) + 1;\n \n \n XX(sm) = 0.5 * XX(sm) + 0.5 * ((XX(sm_t).*t(sm)+XX(sm_b).*b(sm)+XX(sm_r).*r(sm)+XX(sm_l).*l(sm)+XX(sm_tr).*tr(sm)+XX(sm_br).*br(sm)+XX(sm_tl).*tl(sm)+XX(sm_bl).*bl(sm))./Nn(sm));\n \n YY(sm) = 0.5 * YY(sm) + 0.5 * ((YY(sm_t).*t(sm)+YY(sm_b).*b(sm)+YY(sm_r).*r(sm)+YY(sm_l).*l(sm)+YY(sm_tr).*tr(sm)+YY(sm_br).*br(sm)+YY(sm_tl).*tl(sm)+YY(sm_bl).*bl(sm))./Nn(sm));\n \n ZZ(sm) = 0.5 * ZZ(sm) + 0.5 * ((ZZ(sm_t).*t(sm)+ZZ(sm_b).*b(sm)+ZZ(sm_r).*r(sm)+ZZ(sm_l).*l(sm)+ZZ(sm_tr).*tr(sm)+ZZ(sm_br).*br(sm)+ZZ(sm_tl).*tl(sm)+ZZ(sm_bl).*bl(sm))./Nn(sm));\n \n Xmesh = XX(1:Nrow,1:Ncol);\n Ymesh = YY(1:Nrow,1:Ncol);\n Zmesh = ZZ(1:Nrow,1:Ncol);\n \n \n %%% reconnect after smoothing:\n \n % diagonal measure:\n \n Dm1 =( Xmesh(2:Nrow,1:(Ncol-1)) - Xmesh(1:(Nrow-1),2:Ncol)).^2 + (Ymesh(2:Nrow,1:(Ncol-1)) - Ymesh(1:(Nrow-1),2:Ncol)).^2 + (Zmesh(2:Nrow,1:(Ncol-1)) - Zmesh(1:(Nrow-1),2:Ncol)).^2;\n \n Dm2 = (Xmesh(1:(Nrow-1),1:(Ncol-1)) - Xmesh(2:Nrow,2:Ncol)).^2 + (Ymesh(1:(Nrow-1),1:(Ncol-1)) - Ymesh(2:Nrow,2:Ncol)).^2 + (Zmesh(1:(Nrow-1),1:(Ncol-1)) - Zmesh(2:Nrow,2:Ncol)).^2 ;\n \n \n Div1n = Div1 | ((Dm1 <= Dm2)&Ambi);\n Div2n = Div2 | ((Dm2 < Dm1)&Ambi);\n \n Div11 = Div1n & F1;\n Div12 = Div1n & F2;\n Div21 = Div2n & F3;\n Div22 = Div2n & F4;\n \n \n % look at local difference:\n \n dZ_r = abs(Zmesh(:,2:Ncol)-Zmesh(:,1:(Ncol-1)));\n dZ_c = abs(Zmesh(2:Nrow,:)-Zmesh(1:(Nrow-1),:));\n \n Div11 = Div11 & (dZ_r(1:(Nrow-1),:),\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\n% ------------------------------------------------------------------------------\n%% Check inputs, set defaults\n% ------------------------------------------------------------------------------\ndoPlot = false; % plot outputs to figure (e.g., for debugging)\n\n% (*) Prediction length, plen (the length of the output time series)\nif nargin < 2 || isempty(plen)\n plen = 1; % output the same length (proportion)\nend\n% (proportion set after embedding, as the embedding will lose points\n% according to the dimension of the space)\n\n% (*) number of neighest neighbours, NNR\nif nargin < 3 || isempty(NNR)\n NNR = 1; % use 1 nearest neighbour\nend\n\n% (*) stepSize (in samples)\nif nargin < 4 || isempty(stepSize)\n stepSize = 2;\nend\n\n% (*) prediction mode, pmode:\nif nargin < 5 || isempty(pmode)\n pmode = 0; % output vectors are means of the images of nearest neighbours\nend\n\n% (*) embedParams\nif nargin < 6 || isempty(embedParams)\n embedParams = {'ac','fnnmar'};\n fprintf(1,'Using default embedding using autocorrelation for tau and Cao''s method for m\\n');\nend\n\n\n% ------------------------------------------------------------------------------\n%% Embed the scalar time series by time-delay method\n% ------------------------------------------------------------------------------\n% embedpn = BF_Embed(y,embedParams{1},embedParams{2},2);\n% delay = embedpn(1);\n% dim = embedpn(2);\nif iscell(embedParams)\n s = BF_Embed(y,embedParams{1},embedParams{2},1); % last in\nelseif embedParams == 0\n s = signal(y);\nend\n\nif ~isa(s,'signal')\n out = NaN; return\nend\n\nNs = length(data(s));\nif Ns < 50\n error('This is a very short time series! :(');\nend\ny = y(1:Ns); % for statistical purposes...\nif plen > 0 && plen <= 1\n plen = floor(plen*Ns); % specify a proportion of the time series length\nend\n\n% ------------------------------------------------------------------------------\n%% Run the code\n% ------------------------------------------------------------------------------\ntry\n rs = predict(s, plen, NNR, stepSize, pmode);\ncatch\n error('TSTOOL''s predict function didn''t run correctly')\nend\n\ny_pred = data(rs);\ny_pred1 = y_pred(:,1); % for this embedding dimension (?)\n\nif doPlot\n figure('color','w'); box('on'); view(rs);\n\n figure('color','w'); box('on');\n hold off; plot(y,'k'), hold on; plot(y_pred1,'m'), hold off;\nend\n\n% ------------------------------------------------------------------------------\n%% Compare the output to the properties of the true time series\n% ------------------------------------------------------------------------------\n\n% actual basic statistical properties\nout.pred1mean = mean(y_pred1);\nout.pred1std = std(y_pred1);\nout.pred1maxc = abs(max(y_pred1)-max(y));\nout.pred1maxc = abs(max(y_pred(:))-max(y));\nout.pred1minc = abs(min(y_pred1)-min(y));\nout.predminc = abs(min(y_pred(:))-min(y));\nout.pred1rangec = abs(range(y_pred1)/range(y)-1);\n\n% look at structure in cross correlation function, xcf\n% (requires that prediction length the same as the time series itself)\n[xcf, lags] = xcorr(y,y_pred1,'coeff');\n% plot(lags,xcf);\n\nout.maxabsxcf = max(abs(xcf)); % maximum of cross-correlation function; where it occurs\nout.maxabsxcflag = lags(find(abs(xcf) == out.maxabsxcf,1,'first'));\nout.maxxcf = max(xcf); % maximum positive cross-correlation\nout.maxxcflag = lags(find(xcf == out.maxxcf,1,'first'));\nout.meanxcf = mean(xcf);\nout.minxcf = min(xcf);\nout.stdxcf = std(xcf);\n\n\nout.pred1_ac1 = CO_AutoCorr(y_pred1,1,'Fourier'); % autocorrelation at lag one of prediction\nout.pred1ac1diff = abs(out.pred1_ac1 - CO_AutoCorr(y,1,'Fourier')); % difference in autocorrelations of prediction and original\nout.pred1_ac2 = CO_AutoCorr(y_pred1,2,'Fourier'); % autocorrelation at lag one of prediction\nout.pred1ac2diff = abs(out.pred1_ac2 - CO_AutoCorr(y,2,'Fourier')); % difference in autocorrelations of prediction and original\nout.pred_tau_comp = CO_FirstCrossing(y_pred1,'ac',0,'continuous')/CO_FirstCrossing(y,'ac',0,'continuous'); % ratio of first zero crossings of autocorrelation function\n\n% Autocorrelation structure:\nacs_y = CO_AutoCorr(y,1:10,'Fourier');\nacs_y_pred1 = CO_AutoCorr(y_pred1,1:10,'Fourier');\nout.acs1_10_sumabsdiffpred1 = sum(abs(acs_y - acs_y_pred1));\n\n% mean square residuals: this will likely be a bad measure (as may be out\n% of sync)\nout.pred1rmsres = sqrt(mean((y-y_pred1).^2));\n\n% align at best positive cross-correlation and then look at residuals\nif out.maxxcflag > 0\n y_lagged = y(out.maxxcflag:end);\n Nlag = length(y_lagged);\n y_pred1_lagged = y_pred1(1:Nlag);\nelseif out.maxxcflag == 0\n y_lagged = y;\n y_pred1_lagged = y;\n Nlag = length(y);\nelse % negative\n y_pred1_lagged = y_pred1(-out.maxxcflag:end);\n Nlag = length(y_pred1_lagged);\n y_lagged = y(1:Nlag);\nend\n\n% hold off; plot(y_pred1_lagged);\n% hold on; plot(y_lagged,'r');\nout.Nlagxcorr = Nlag;\nres = y_lagged - y_pred1_lagged;\nout.bestpred1rmsres = sqrt(mean(res.^2)); % rms residuals\nout.ac1bestres = CO_AutoCorr(res,1,'Fourier'); % autocorrelation of residuals\n\n% now look at fraction of points that are within a threshold of each\n% other...\nfracresfn = @(x) sum(abs(res) < x)/Nlag;\nout.fracres005 = fracresfn(0.05); %sum(abs(res)<0.05)/Nlag;\nout.fracres01 = fracresfn(0.1); %sum(abs(res)<0.1)/Nlag;\nout.fracres02 = fracresfn(0.2); %sum(abs(res)<0.2)/Nlag;\nout.fracres03 = fracresfn(0.3); %sum(abs(res)<0.3)/Nlag;\nout.fracres05 = fracresfn(0.5); %sum(abs(res)<0.5)/Nlag;\n\n% now look at fraction of points within a circle of (time-measurement) radius\n% near a real point in the time series\n% this could be done using the closest neighbour of the simulation to the\n% real time series\n\n% Could compare different dimensions rather than just the first... find the\n% best... etc.\n\n% There are heaps of metrics you could use to compare... Ultimately may be\n% able to implement model outputs as rows so as to compare across many\n% measures...\n\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/TSTL_predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.36057122936576247}} {"text": "function [D1]=triSurfSetDist(F1,V1,F2,V2,distMetric)\n\n% function [D1]=triSurfSetDist(F1,V1,F2,V2,distMetric)\n% ------------------------------------------------------------------------\n%\n% Change log: \n% 2021/07/22 KMM Removed waitbar for ray-tracing method\n% ------------------------------------------------------------------------\n\n%%\n\nswitch distMetric\n case 'dist'\n D1=minDist(V1,V2);\n case 'ray'\n [~,~,N1]=patchNormal(F1,V1);\n \n %Ray trace 1 onto 2 \n optionStructRayTrace.tolEps = 1e-6;\n optionStructRayTrace.triSide = 0;\n optionStructRayTrace.rayType = 'ray'; % or line\n optionStructRayTrace.exclusionType = 'normal'; % or exclusive\n optionStructRayTrace.paired=0; % 1 for paired, 0 for non-paired\n\n [~,indIntersect,d1_all]=triSurfRayTrace(V1,N1,F2,V2,optionStructRayTrace);\n \n numIntersect=size(indIntersect,1);\n\n S=sparse(indIntersect(:,1),(1:numIntersect)',1,size(V1,1),numIntersect,numIntersect);\n d1_sparse=sparse(indIntersect(:,1),(1:numIntersect)',abs(d1_all),size(V1,1),numIntersect,numIntersect);\n \n D1=full(spmin(d1_sparse,[],2,'includenan',S~=0,1)); \n \n case 'dist-ray'\n [D1d]=triSurfSetDist(F1,V1,F2,V2,'dist');\n [D1r]=triSurfSetDist(F1,V1,F2,V2,'ray');\n D1=gnanmin([D1d D1r],[],2); \n case 'near-norm'\n [~,indMin]=minDist(V1,V2);\n [~,~,Nv]=patchNormal(F2,V2);\n N=Nv(indMin,:);\n W=V1-V2(indMin,:);\n D1=abs(dot(N,W,2));\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/triSurfSetDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.36054950565526306}} {"text": "function [mustLL, pos_mustLL, mustLL_linear, pos_mustLL_linear] = findMustLLWithGAMS(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% `MustLL` set.\n%\n% USAGE:\n%\n% [mustLL, pos_mustLL, mustLL_linear, pos_mustLL_linear] = findMustLLWithGAMS(model, minFluxesW, maxFluxesW, varargin)\n%\n% INPUTS:\n% model: (structure) a metabolic model with at least\n% 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 `FVA_optForce`. 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 have\n% the same value. Do not include here\n% reactions whose lower and upper bounds have\n% different values. Such contraints should be\n% defined in the lower and upper bounds of\n% the model. The structure has the following\n% 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 `MustLL` set. This could be used to avoid\n% finding transporters or exchange reactions\n% in the set. Default = empty.\n% mustSetFirstOrder: (cell array) Reactions that belong to `MustU`\n% and `MustL` (first order sets). 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% 'OutputsFindMustLL'.\n% outputFileName: (string) name for files in which\n% results will be stored. Default =\n% 'MustLLSet'.\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 file\n% 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 `findMustLL.gms`. 0 otherwise.\n% Default = 1\n% keepGamsOutputs: (double) 1 to mantain files returned by\n% `findMustLL.gms`. 0 otherwise. Default = 1\n% verbose: (double) 1 to print results in console.\n% 0 otherwise. Default = 0\n%\n% OUTPUTS:\n% mustLL: (cell array of size number of sets found X\n% 2). Cell array containing the reactions IDs\n% which belong to the `MustLL` set. Each row\n% contain a couple of reactions that must\n% decrease their flux.\n% pos_mustLL: (double array of size number of sets found\n% X 2). Double array containing the positions\n% of each reaction in `mustLL` with regard to\n% `model.rxns`\n% mustLL_linear: (cell array of size number of unique\n% reactions found X 1) Cell array containing\n% the unique reactions ID which belong to the\n% `MustLL` Set\n% pos_mustLL_linear: (double array of size number of unique\n% reactions found X 1) double array\n% containing positions for reactions in\n% `mustLL_linear`. with regard to `model.rxns`\n% outputFileName.xls: (file) File containing one column\n% array with identifiers for reactions in\n% `MustLL`. This file will only be generated if\n% the user entered `printExcel = 1`. Note that\n% the user can choose the name of this file\n% entering the input `outputFileName =\n% 'PutYourOwnFileNameHere';`\n% outputFileName.txt: (file) File containing one column\n% array with identifiers for reactions in\n% `MustLL`. This file will only be generated if\n% the user entered `printText = 1`. Note that\n% the user can choose the name of this file\n% entering the input `outputFileName =\n% '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% `FindMustLL.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% `FindMustLL.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% findMustLL.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 if the user\n% entered `keepGamsOutputs = 1`\n% GtoMLL.gdx: (file) file containing values for\n% variables, parameters, etc. which were\n% found by GAMS when solving `findMustLL.gms`.\n% This file only will be saved in the output\n% folder if 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', 'OutputsFindMustLL', @(x) ischar(x))\nparser.addParamValue('outputFileName', 'MustLLSet', @(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\ngamsMustLLFunction = 'findMustLL.gms';\n%path of that function\npathGamsFunction = which(gamsMustLLFunction);\nif isempty(pathGamsFunction); error(['OptForce: ' gamsMustLLFunction ' 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, ['findMustLLWithGAMS.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% MustLL Set\ninputFolder = 'InputsMustLL';\nexportInputsMustOrder2ToGAMS(model, 'LL', 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 ' gamsMustLLFunction ' lo=3 --myroot=' inputFolder '/ --solverName=' solverName ' gdx=GtoMLL']);\nelse\n run=system(['gams ' gamsMustLLFunction ' --myroot=' inputFolder '/ --solverName=' solverName ' gdx=GtoMLL']);\nend\n\nif printReport; fprintf(freport, '\\n------RESULTS------\\n'); end;\n\n%if user decide not to show inputs files for findMustLL.gms\nif ~keepInputs; rmdir(inputFolder, 's'); end;\n\n%if findMustLL.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 GtoMLL; end;\n try\n findMustLL.name = 'findMustLL';\n rgdx('GtoMLL', findMustLL); %if do not exist the variable findMustLL in GtoMLL, 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 findMustLL.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('GtoMLL', 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 MustLL set was found\\n'); end;\n if verbose; fprintf('a MustLL 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('GtoMLL', 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 mustLL = cell(n_mustSet, 2);\n pos_mustLL = zeros(size(mustLL));\n mustLL_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 mustLL(i,1) = rxn1;\n mustLL(i,2) = rxn2;\n pos_mustLL(i,1) = find(strcmp(model.rxns, rxn1));\n pos_mustLL(i,2) = find(strcmp(model.rxns, rxn2));\n mustLL_linear = union(mustLL_linear, [rxn1;rxn2]);\n end\n pos_mustLL_linear = cell2mat(arrayfun(@(x)find(strcmp(x, model.rxns)), mustLL_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 MustLL set was not found\\n'); end;\n if verbose; fprintf('a MustLL set was not found\\n'); end;\n\n %initialize arrays to be returned by this function\n mustLL = {};\n pos_mustLL = [];\n mustLL_linear = {};\n pos_mustLL_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(mustLL,1), 1);\n for i = 1:size(mustLL, 1)\n must{i} = strjoin(mustLL(i,:), ' or ');\n end\n xlswrite([outputFileName '_Info'],[{'Reactions'};must]);\n xlswrite(outputFileName, mustLL_linear);\n cd(currentFolder);\n if verbose\n fprintf(['MustLL set was printed in ' outputFileName '.xls \\n']);\n fprintf(['MustLL set was also printed in ' outputFileName '_Info.xls \\n']);\n end\n if printReport\n fprintf(freport, ['\\nMustLL set was printed in ' outputFileName '.xls \\n']);\n fprintf(freport, ['\\nMustLL set was printed in ' outputFileName '_Info.xls \\n']);\n end\n else\n if verbose; fprintf('No mustLL set was found. Therefore, no excel file was generated\\n'); end;\n if printReport; fprintf(freport, '\\nNo mustLL 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(mustLL,1)\n fprintf(f, '%s or %s\\n', mustLL{i,1}, mustLL{i,2});\n end\n fclose(f);\n\n f = fopen([outputFileName '.txt'], 'w');\n for i = 1:length(mustLL_linear)\n fprintf(f, '%s\\n', mustLL_linear{i});\n end\n fclose(f);\n\n cd(currentFolder);\n if verbose\n fprintf(['MustLL set was printed in ' outputFileName '.txt \\n']);\n fprintf(['MustLL set was also printed in ' outputFileName '_Info.txt \\n']);\n end\n if printReport\n fprintf(freport, ['\\nMustLL set was printed in ' outputFileName '.txt \\n']);\n fprintf(freport, ['\\nMustLL set was printed in ' outputFileName '_Info.txt \\n']);\n end\n\n else\n if verbose; fprintf('No mustLL set was found. Therefore, no plain text file was generated\\n'); end;\n if printReport; fprintf(freport, '\\nNo mustLL 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(gamsMustLLFunction);\n\n %remove or move additional files that were generated during running\n if keepGamsOutputs\n if ~isdir(outputFolder); mkdir(outputFolder); end;\n movefile('GtoMLL.gdx', outputFolder);\n movefile(regexprep(gamsMustLLFunction, 'gms', 'lst'), outputFolder);\n else\n delete('GtoMLL.gdx');\n delete(regexprep(gamsMustLLFunction, '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 findMustLL.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/findMustLLWithGAMS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.36053760626224673}} {"text": "function [y,O,X,S] = filterAdjust(O)\n% :Usage:\n% ::\n%\n% [y,O,X,S] = filterAdjust(OPTIONS)\n%\n% :O:\n%\n% **O.y:**\n% signal\n%\n% **O.HP:**\n% high pass freq. cutoff\n%\n% **O.TR:**\n% sampling rate in s\n%\n% **O.doHP:**\n% [0 or 1] - do HP filter (spm), default is 0\n%\n% **O.doLP:**\n% [0, 1, 2] - do LP filter (spm), default is 0\n% 2 = Gaussian filter with TR*2 s length\n%\n% **O.firstimg:**\n% sets values for first image in each run to mean of the\n% remaining values. Good for removing first-image artifacts present in\n% some scanner sequences. Default is 1.\n%\n% **O.cyclecorrection:**\n% checks for unimodal (normally distributed) data\n% within each session, because some bimodal data that cycles between two\n% mean scanner values has been observed in some data. if a high proportion\n% of outliers are found in non-normal data, subtracts mean of higher mode\n% to adjust data. Sorry-not clear. Check the code. Default is 0\n%\n% **O.cyclecorrection2:**\n% removes large transitions from data, as in\n% detransition.m. Default is 0. Artifacts may be acquisition or\n% motion-correction/resampling related.\n% \n% We do this after filtering, but if there's trouble, we re-do the\n% scanadjust and filtering, because 'cycling' can affect these.\n%\n% **O.scanadjust:**\n% [0 or 1] - adjust to scan means, default is 0\n% - If O.X is entered, assumes this is the session mean matrix,\n% instead of recomputing.\n%\n% **O.percent:**\n% [0 or 1] - adjust to percent change from baseline, default is 0\n%\n% **O.filtertype:**\n% filter style, default is 'none'\n% - 'spm', use spm's filtering\n% - if O.S is entered, uses this instead of recomputing\n% - 'fourier', Doug's fourier filter\n% - 'fouriernotch', Omit frequencies between HP(1) and HP(2)\n% - 'cheby', chebyshev\n% - 'Luis', Luis' custom filter\n% - 'none', no filtering (or leave field out).\n%\n% **O.HP:**\n% for SPM, the filter cutoff in s\n% for fourier, the HP value or the [HP LP] values\n% notches out everything slower than HP and faster than LP, in s\n% (1/s = Hz). \n%\n% **O.nruns:**\n% number of runs (scanadjust), default is 1\n%\n% **O.adjustmatrix:**\n% custom adjustment matrix to regress out (e.g., movement params)\n%\n% **O.plot [0 or 1]:**\n% plots intermediate products, default is 0\n%\n% **O.verbose [0 or 1]:**\n% verbose output\n%\n% **O.trimts [0 or std]:**\n% trim overall timseries values to std, 0 for no trimming \n%\n% **O.lindetrend:**\n% specify linear detrending of timeseries.\n% occurs after adjustment and filtering and windsorizing\n% - detrending option -> what to enter in this field:\n% - no detrending -> empty, missing field, or 0\n% - detrending every n elements -> single number (n)\n% - piecewise linear detrend -> ROW vector of breakpoints\n% (do not specify 1 as the start of the 1st segment.)\n%\n% ..\n% by Tor Wager, 09/24/01\n% modified 10/15/02 to add trial baseline adjustment and linear detrending.\n% ..\n\nif ~isfield(O,'verbose'), O.verbose = 0;,end\nif ~isfield(O,'trimts'), O.trimts = 0;,end\nif ~isfield(O,'lindetrend'), O.lindetrend = 0;, end\nif ~isfield(O,'percent'), O.percent = 0;, end\n\n% out = voistat('adjusty',y,HChoice,TR,nruns, [opt] adjustmatrix); \n% disp('*\tvoistat adjusty')\n\ny = O.y;\nTR = O.TR;\nnpoints = size(y,1);\n\nif size(y,2) > size(y,1), y = y';, end\n\nnruns = 1;\nif isfield(O,'scanadjust'), if O.scanadjust, nruns = O.nruns;,end,else, O.scanadjust = 0;,end\nif isfield(O,'adjustmatrix'), docustomadjust = 1;,adjustmatrix = O.adjustmatrix;,else, docustomadjust = 0;,adjustmatrix = [];,end\n\nscanlen = npoints./nruns;\nif scanlen ~= round(scanlen),warning(['Scan length is not an integer! scanlen = ' num2str(scanlen) ', rounded = ' num2str(round(scanlen))]),end\nscanlen = round(scanlen);\n\nwholeyavg = mean(y(~isnan(y)));\nX = [];\n\nif ~isfield(O,'doHP'), O.doHP = 0;,HChoice = [];,else, HChoice = O.HP;end\nif O.doHP,if isempty(HChoice),error('filterAdjust: specify HP filter length in input options!'),end,end\nif ~isfield(O,'doLP'), O.doLP = 0;,end\nif ~isfield(O,'filtertype'), O.filtertype = 'none';,end\nif ~isfield(O,'plot'), O.plot = 0;,end\nif ~isfield(O,'cyclecorrection'), O.cyclecorrection = 0;,end\nif ~isfield(O,'cyclecorrection2'), O.cyclecorrection2 = 0;,end\nif ~isfield(O,'firstimg'), O.firstimg = 1;,end\n\n% plot raw\nif O.plot, f1 = figure('Color','w'); hold on; set(gca,'FontSize',16); plot(scale(y),'k');,title('Raw timeseries (standardized for display)'); pause(1);,end\n\nif ((O.doHP | O.doLP) & strcmp(O.filtertype,'spm'))\n\t% MAKE FILTER - use_spm_filter.m\n\t% --------------------------------------------------------\n\t% Ran out of memory doing this with whole ts, so trying to make more efficient...do it scan by scan.\n if O.doHP | O.doLP\n if isfield(O,'S')\n if O.verbose, disp(\t'\t\t...voistat adjusty: Using input S filter: filter shape plot is final S matrix only'), end\n S = O.S; KL = O.S; KH = O.S;\n else\n \n \n if O.verbose, disp(\t'\t\t...voistat adjusty: making S filter'), end\n \n \n if O.doHP & O.doLP\n \n if O.doLP == 2\n \n [S,KL,KH] = use_spm_filter(TR,scanlen,'Gaussian','specify',HChoice,TR*2);\n \n else\n \n [S,KL,KH] = use_spm_filter(TR,scanlen,'hrf','specify',HChoice);\n \n end\n \n \n elseif O.doHP\n \n [S,KL,KH] = use_spm_filter(TR,scanlen,'none','specify',HChoice);\n \n elseif O.doLP == 2\n \n [S,KL,KH] = use_spm_filter(TR,scanlen,'Gaussian','none',[],TR*2);\n \n elseif O.doLP\n \n [S,KL,KH] = use_spm_filter(TR,scanlen,'hrf','none',[]);\n \n else error('Script bug. Check filterAdjust.m')\n \n end\n \n end % if S\n \n \n else warning('No filtering specified, though spm is filtertype.'), \n S = [];\n end\n\n\tif O.plot, figure;\n \t\tsubplot(1,3,1);imagesc(S); title('Smoothing matrix (spm) *used')\n \t\tsubplot(1,3,2);imagesc(KL); title('Low-pass filter(spm)')\n subplot(1,3,3);imagesc(KH); title('High-pass filter(spm)')\n pause(1)\n close\n end\n \nend\n\nif (O.doHP | O.doLP) & strcmp(O.filtertype,'none')\n error('For filtering to be used, enter ''spm'' ''cheby'' ''doug'', etc. in O.filtertype.')\nend\n\n \nif O.cyclecorrection2\n if O.verbose, disp('\t\t...removing large transitions from data (presumably artifacts).'),end\n\t\n for startimg = 1:scanlen:npoints\n tmp = y(startimg:startimg+scanlen-1);\n tmp = detransition(tmp,O.plot);\n y(startimg:startimg+scanlen-1) = tmp;\n end\n \n if O.plot, figure(f1); hold off; plot(scale(y),'k'); hold on; title('Raw (detransitioned, std for display)');,pause(1);end\nend\n\n \nif O.scanadjust\n\t% adjust scan means\n\t% --------------------------------------------------------\n\tif O.verbose, disp('\t\t...adjusting scan means to session mean.'),end\n\n if isfield(O,'X')\n X = O.X;\n else\n\t index = 1;\n\t for startimg = 1:scanlen:npoints\n\t\t X(startimg:startimg+scanlen-1,index) = 1;\n\t\t index = index + 1;\n\t end\n end\n \n\n\tif size(X,1) > size(y,1)\n\t\tdisp(['\t* * * voistat.m adjusty: WARNING: X is longer than y. truncating.'])\n\t\tX = X(1:length(y),:);\n\tend\n\n %y = y - (X * (X \\ y));\t% y-xB to adjust to mean.\n y = y - X * pinv(X) * y;\n \n if O.plot, figure;\n imagesc(X); title('Model matrix for effects to regress out.')\n pause(1),close\n \n figure(f1); hold off; plot(scale(y),'k'); hold on; title('Session means removed, std for display)');,pause(1);\n end\n \nend\n\nif O.firstimg\n if O.verbose, disp('\t\t...Setting values of first 2 images in each run to timeseries mean value.'),end\n tmp = 1:scanlen:length(y);\n tmp = [tmp 2:scanlen:length(y)];\n \n % first adjust to session means - rough estimate\n tmpn = 1:length(y); tmpn(tmp) = [];\n y(tmp) = mean(y(tmpn));\n \n % then adjust to expected \n tmpx = (1:length(y))';\n [P] = polyfit(tmpx,y,3);\n yy = polyval(P,tmpx);\n y(tmp) = yy(tmp);\n \n if O.plot, figure(f1); plot(scale(y),'m'); hold on; \n plot(scale(yy));\n title('Raw (1-2 removed, std for display)');,\n end\nend\n\nswitch O.filtertype\n\ncase 'spm'\n% filter each scan\n% --------------------------------------------------------\nif ~isempty(S)\n filty = [];\n\tif O.verbose, disp('\t\t...applying to each session: high-pass filtering.'),end\n\n\t% whos y\n\n\tfor startimg = 1:scanlen:npoints\n\t\ttry\n\t\t\tsessy = y(startimg:startimg+scanlen-1,:);\n\t\tcatch\n\t\t\tstartimg\n\t\t\twhos y\n\t\t\terror(['\tvoistat adjusty: ERROR. y is too short, npoints is wrong, or numscans is wrong? Check GUI values.'])\n\t\tend\n\n\t\ttry\n\t\t\tsessy = S * sessy;\n\t\tcatch\n\t\t\ttry\n\t\t\t\tsessy = (S * sessy')';\n\t\t\tcatch\n\t\t\t\tdisp('\t\tcan''t multiply S and sessy: matrix dimensions not correct. Try transposing y?')\n\t\t\t\twhos S\n\t\t\t\twhos sessy\n\t\t\t\tdisp(['Scanlength = ' num2str(scanlen)])\n\t\t\t\tdisp(['total time pts = ' num2str(npoints)])\n\t\t\t\tdisp(['Num Sessions = ' num2str(nruns)])\n\t\t\t\terror('Exiting now...')\n\t\t\tend\n\t\tend\n\n\t\tfilty = [filty; sessy];\n end\n\n% whos filty\n \n if O.plot\n figure(f1);hold off; plot(scale(y),'b','LineWidth',1);, hold on; plot(scale(filty),'r','LineWidth',1);\n legend({'Before filtering' 'After filtering'})\n\n %pause(1),close\n end\n \n y = filty;\n \nend \n \n % Old custom filter stuff.\n %Wn = .35;\n %[B,A] = cheby2(3,40,Wn);\n %y = filter(B,A,y); \n\n% Doug's custom fourier LP filter. \n%len = length(y) /2;\n%ind = [1:len] ./ len; \n%ff = 1./(1+exp((ind-.30)./0.05));\n%ff2 = [ff ff(len:-1:1)];\n%y = real(ifft(fft(y).*ff2'));\n\n\n\ncase 'cheby'\nif ~isempty(HChoice)\n\tnyquist = TR/2;\t% in seconds, not frequencies TR/nyquist = .5\n\tWn = [TR/HChoice .35];\n\tif O.verbose, disp([\t\t'voistat adjusty: Chebyshev filter freqency is ' num2str(Wn)]),end\n\tfor startimg = 1:scanlen:npoints\n\t\tsessy = y(startimg:startimg+scanlen-1);\n \t\t[B,A] = cheby2(1,20,Wn);\n\t\tsessy = filter(B,A,y); \n\tend\nend\n\ncase 'fourier'\nif ~isempty(HChoice)\n\tfilty = []; nyquist = (1/TR)/2; lowerlim = 1/HChoice(1);\n\thzfreqs = (1:scanlen) ./ (scanlen * TR);\n\tif length(HChoice) == 1\n ftopass = hzfreqs >= lowerlim & hzfreqs <= nyquist;\n else\n ftopass = hzfreqs >= lowerlim & hzfreqs <= 1./(HChoice(2));\n end\n\tif O.verbose, disp(['\t\t...applying to each session: notch filtering: ' num2str(lowerlim) ' to ' num2str(nyquist) ' Hz.']),end\n\tfor startimg = 1:scanlen:npoints\n\t\tmyfft = fft(y(startimg:startimg+scanlen-1));\n\t\tmypass = zeros(1,scanlen);\n\t\tmypass(ftopass) = myfft(ftopass);\n\t\t% plot(abs(myfft));hold on;plot(abs(mypass),'rx');\t\n\t\tsessy = real(ifft(mypass))';\n\t\tfilty = [filty; sessy];\n\tend\n\ty = filty;\n %hold on; plot(y,'r');\nend\n\ncase 'fouriernotch'\nif ~isempty(HChoice)\n\tfilty = []; nyquist = (1/TR)/2; lowerlim = 1/HChoice(1);\n\thzfreqs = (1:scanlen) ./ (scanlen * TR);\n ftopass = ones(size(hzfreqs));\n ftopass(hzfreqs > lowerlim & hzfreqs < 1./(HChoice(2))) = 0;\n ftopass = find(ftopass);\n \n\tif O.verbose, disp(['\t\t...applying to each session: notch filtering: ' num2str(lowerlim) ' to ' num2str(nyquist) ' Hz.']),end\n\tfor startimg = 1:scanlen:npoints\n\t\tmyfft = fft(y(startimg:startimg+scanlen-1));\n\t\tmypass = zeros(1,scanlen);\n\t\tmypass(ftopass) = myfft(ftopass);\n\t\t%figure; plot(abs(myfft));hold on;plot(abs(mypass),'rx');\t\n\t\tsessy = real(ifft(mypass))';\n\t\tfilty = [filty; sessy];\n\tend\n\ty = filty;\n %hold on; plot(y,'r');\nend\n\ncase 'bandpass'\nif ~isempty(HChoice)\n\tfilty = []; nyquist = (1/TR)/2; lowerlim = 1/HChoice(1);\n\thzfreqs = (1:scanlen) ./ (scanlen * TR);\n ftopass = zeros(size(hzfreqs));\n ftopass(hzfreqs > lowerlim & hzfreqs < 1./(HChoice(2))) = 1;\n ftopass = find(ftopass);\n \n\tif O.verbose, disp(['\t\t...applying to each session: band pass filtering: ' num2str(lowerlim) ' to ' num2str(1./(HChoice(2))) ' Hz.']),end\n\tfor startimg = 1:scanlen:npoints\n\t\tmyfft = fft(y(startimg:startimg+scanlen-1));\n\t\tmypass = zeros(1,scanlen);\n\t\tmypass(ftopass) = myfft(ftopass);\n\t\t%figure; plot(abs(myfft));hold on;plot(abs(mypass),'rx');\t\n\t\tsessy = real(ifft(mypass))';\n\t\tfilty = [filty; sessy];\n\tend\n\ty = filty;\n %hold on; plot(y,'r');\nend\n\n\ncase 'Luis'\n if O.plot\n y = luisFilter(y,O.TR,.35,'v');pause(1),close,pause(1),close\n else\n y = luisFilter(y,O.TR,.35);\n end\n \n \ncase 'none'\n \nend % end switch\n\n\n\nif O.cyclecorrection\n % check for bimodal 'cycling' of mean BOLD signal within sessions, and\n % correct if necessary, before removing scan means, etc.\n % if we find problems, then re-do session-centering\n\t% --------------------------------------------------------\n if O.verbose, disp('\t\t...checking for normally distributed data (to avoid bimodal cycling observed in some data).'),end\n\tcycor = []; ind = 1; classes = [];\n for startimg = 1:scanlen:npoints\n\t\t tmp = y(startimg:startimg+scanlen-1);\n\n [tmp,IDX] = mixture_model(tmp,O.plot);\n \n if max(IDX) > 1 & ~isempty(S)\n tmp = S * tmp;\n if O.plot, subplot(1,3,1),hold on;plot(tmp,'g'),end\n end\n \n y(startimg:startimg+scanlen-1) = tmp - mean(tmp);\n classes(ind) = max(IDX);\n \n ind = ind+1; \n end\n cycor = classes > 1;\n \n if O.verbose, \n \n fprintf(1,'\t\t...%3.0f Sessions were not normally distributed.\\n',sum(cycor)),\n if any(cycor), fprintf(1,['\\t\\t\\tClasses by session: ' num2str(classes) '\\n']),end\n else\n if any(cycor), fprintf(1,['\\t\\t\\tClasses by session: ' num2str(classes) '\\n']),end\n end\nend\n\n \n% do overall trimming here\n% --------------------------------------------------------\nif O.trimts\n [y,ntrimmed] = trimts(y,O.trimts,[],1);\n if O.verbose,fprintf(1,['\\t\\t...Windsorized ' num2str(ntrimmed) ' points from overall timeseries to ' num2str(O.trimts) ' std. deviations.\\n']), end\n \n if O.plot\n figure(f1); plot(scale(y),'k--');, legend({'Before filtering' 'After filtering' 'After filt+trimming'})\n end\n %tpts = abs(y) > O.trimts .* std(y);\n %y(tpts) = NaN;\nend\n\n\n\nif O.lindetrend\n % linear detrending at specified knot points\n \n if O.verbose, fprintf(1,['\\t\\t...piecewise linear detrending requested with ' num2str(length(O.lindetrend)) ' breakpoints.\\n']),end\n % set bp to [] for removal of one linear trend from the whole column\n if O.lindetrend == 1, O.lindetrend = [];, end \n % if a single number, interpret as knotpoints every n elements.\n \n if length(O.lindetrend) == 1, O.lindetrend = O.lindetrend:O.lindetrend:length(y);, end \n \n if O.plot, \n figure; plot(y);, \n set(gcf,'Position',[144 542 1306 504],'Color','w')\n disp([' Breakpoints: ' num2str(O.lindetrend)]) \n end\n hold on;\n y = detrend(y,'linear',O.lindetrend);\n y = y + wholeyavg; % preserve mean of the original timeseries\n \n if O.plot,\n figure(f1); hold on; plot(y,'m');\n plot([O.lindetrend' O.lindetrend']',[ones(length(O.lindetrend),1) * min(y) ones(length(O.lindetrend),1)*max(y)]','k')\n legend({'Original' 'Detrended'})\n \n mystd = std(y) * 3;\n plot([0 length(y)],[mean(y)+mystd mean(y)+mystd],'k--')\n plot([0 length(y)],[mean(y)-mystd mean(y)-mystd],'k--')\n text(length(y)-10,mean(y)+mystd,'3 std lines')\n \n drawnow\n pause(1)\n %close\n end\nend\n \n \n \n\nif O.percent\n \n\tif O.verbose, disp(['\t\t...converting to % change from overall mean: original mean is ' num2str(wholeyavg)]),end\n\ty = (y-mean(y))*100 / wholeyavg;\t\t% percent change from 0.\n\nend\n\nif docustomadjust\n\t\tif O.verbose, disp('\t\t...adjusting for user-entered covariates -e.g. movement params'),end\n \t\tif sum(sum(isnan(adjustmatrix))) > 0,\n\t\t\tdisp('\t\t...WARNING: NaN values in user covariates! Setting these to 0.')\t\n\t\t\tadjustmatrix(isnan(adjustmatrix)) = 0;\n\t\tend\n\t\ttry\n\t\t\tX = [adjustmatrix];\n X(:,end+1) = 1; % add intercept\n\t\tcatch\n\t\t\twarning('\t\tvoistat ''adjusty'': X and adjustmatrix are different sizes. no covariates entered.')\n\t\t\twhos X\n\t\t\twhos adjustmatrix\n end\n O.custombeta = pinv(X) * y;\n y = y - X * O.custombeta;\n end\n \n\n\n% figure; plot(abs(fft(y)),'ro');set(gca,'YLim',[0 1000])\n\n\nreturn\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Data_processing_tools/filterAdjust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266736, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.35993241539046467}} {"text": "function [minFlux, maxFlux, minFD, maxFD, GRvector, result, LP] = SteadyComFVA(modelCom, options, varargin)\n% Flux variability analysis for community model at community steady-state for a range of growth rates.\n% The function is capable of saving intermediate results and continuing from previous results\n% if the file path is given in `options.saveFVA`. It also allows switch from single thread to parallel\n% computation from intermediate results (but not the other way round).\n%\n% USAGE:\n% [minFlux, maxFlux, minFD, maxFD, GRvector, result, LP] = SteadyComFVA(modelCom, options, parameter, 'param1', value1, 'param2', value2, ...)\n%\n% INPUT:\n% modelCom: A community COBRA model structure with the following fields (created using `createMultipleSpeciesModel`)\n% (the first 5 fields are required, at least one of the last two is needed. Can be obtained using `getMultiSpecisModelId`):\n%\n% * S - Stoichiometric matrix\n% * b - Right hand side\n% * c - Objective coefficients\n% * lb - Lower bounds\n% * ub - Upper bounds\n% * infoCom - structure containing community reaction info\n% * indCom - the index structure corresponding to `infoCom`\n%\n% OPTIONAL INPUTS:\n% options: struct with the following possible fields:\n%\n% * optGRpercent - A vector of percentages. Perform FVA at these percents of max. growth rate (Default = [99.99])\n% * optBMpercent - Only consider solutions that yield at least a certain percentage of the optimal biomass (Default = 99.99)\n% * rxnNameList - List of reactions (index row vector or subset of `*.rxns`) for which FVA is performed.\n% (Default = biomass reaction of each species)\n% Or a :math:`(N_{rxns} + N_{organism}) x K` matrix for FVA of `K` linear combinations of fluxes and/or abundances\n% e.g., `[1; -2; 0]` for finding the max/min of :math:`1 v_1 - 2 v_2 + 0 v_3`\n% * rxnFluxList - List of reactions (index vector or subset of `*.rxns`) whose fluxes are\n% also returned along with the FVA result of each entry in `rxnNameList`\n% (Default = biomass reaction of each species)\n% * GRmax - maximum growth rate of the model (default to be found `SteadyCom.m`)\n% (the two parameters below are usually determined by solving the problem during the program.\n% Provide them only if you want to constrain the total biomass to a particular value)\n% * BMmaxLB - lower bound for the total biomass (default 1)\n% * BMmaxUB - upper bound for the total biomass (other parameters below)\n% * saveFVA - If non-empty, become the filename to save the FVA results\n% (default empty, not saving)\n% * saveFre - save frequency. Save every `(#rxns for FVA) * saveFre` (default 0.1)\n% * threads - for parallelization: > 1 for explicitly stating the no. of threads used,\n% 0 or -1 for using all available threads. Default 1.\n% (Requires Matlab parallel toolbox)\n% * verbFlag - Verbose output. 1 to have waitbar, >1 to have stepwise output (default 3)\n% * loadModel - (`ibm_cplex` only) String of filename to be loaded. If non-empty, load the cplex\n% model ('loadModel.mps'), basis ('loadModel.bas') and parameters ('loadModel.prm').\n% (May add also other parameters in `SteadyCom` for calculating the maximum growth rate.)\n%\n% parameter: structure for solver-specific parameters.\n% 'param1', value1, ... name-value pairs for `solveCobraLP` parameters. See `solveCobraLP` for details\n%\n% OUTPUTS:\n% minFlux: Minimum flux for each reaction\n% maxFlux: Maximum flux for each reaction\n%\n% OPTIONAL OUTPUTS:\n% minFD: :math:`rxnFluxList * rxnNameList` matrix containing the fluxes in `options.rxnFluxList`\n% corresponding to minimizing each reaction in `options.rxnNameList`\n% maxFD: :math:`rxnFluxList * rxnNameList` matrix containing the fluxes in `options.rxnFluxList`\n% corresponding to maximizing each reaction in `options.rxnNameList`\n% GRvector: a vector of growth rates at which FVA has been performed\n% result: result structure from `SteadyCom`\n% LP: `LP` problem structure (`Cplex LP` object for `ibm_cplex`)\n\n[modelCom, ibm_cplex, feasTol, solverParams, parameters] = SteadyComSubroutines('initialize', modelCom, varargin{:});\n% Initialization above\nif nargin < 2 || isempty(options)\n options = struct();\nend\n% handle solveCobraLP name-value arguments that are specially treated in SteadyCom functions\n[options, varargin] = SteadyComSubroutines('solveCobraLP_arg', options, parameters, varargin);\n\n% get SteadyCom paramters. If a required parameter is in options, get its value, else equal to the\n% default value in SteadyComSubroutines('getParams') if there is. Otherwise an empty matrix.\n[GRmax, optGRpercent, rxnNameList, rxnFluxList, ...\n GRfx, BMmaxLB, BMmaxUB, ...\n verbFlag, loadModel, saveFVA, threads] = SteadyComSubroutines('getParams', ...\n {'GRmax', 'optGRpercent', 'rxnNameList', 'rxnFluxList',...\n 'GRfx','BMmaxLB','BMmaxUB', ...\n 'verbFlag', 'loadModel','saveFVA','threads'}, ...\n options, modelCom);\n\n[m, n] = size(modelCom.S); % model size\nnSp = numel(modelCom.indCom.spBm); % number of organisms\nnRxnSp = sum(modelCom.indCom.rxnSps > 0); % number of organism-specific rxns\n\nif ischar(rxnNameList)\n rxnNameList = {rxnNameList};\nend\nif iscell(rxnNameList) || (min(size(rxnNameList)) == 1 && size(rxnNameList, 1) < n)\n nRxnFVA = numel(rxnNameList);\nelse\n nRxnFVA = size(rxnNameList, 2);\nend\nif ischar(rxnFluxList)\n rxnFluxList = {rxnFluxList};\nend\n\naddRow = false;\nGRgiven = false;\nif isempty(GRmax)\n % get maximum growth rate\n [sol, result, LP] = SteadyCom(modelCom, options, varargin{:});\n if strcmp(result.stat,'infeasible')\n % infeasible model\n warning('The model is infeasible.');\n [minFlux, maxFlux] = deal(NaN(nRxnFVA, 1));\n [minFD, maxFD] = deal(NaN(numel(rxnFluxList), nRxnFVA));\n GRvector = NaN(numel(optGRpercent), 1);\n return\n end\n GRmax = result.GRmax;\n if ibm_cplex\n idRow = size(LP.Model.A, 1); % row that constrains the total biomass\n else\n idRow = size(LP.A, 1); % row that constrains the total biomass\n end\nelse\n % if GRmax is given, BMmaxLB and BMmaxUB should be included in options in this case to ensure feasibility\n if ibm_cplex && ~isempty(loadModel)\n % load Cplex model if loadModel is given\n LP = Cplex('SteadyComFVA');\n LP.readModel([loadModel '.mps']);\n LP.readBasis([loadModel '.bas']);\n LP.readParam([loadModel '.prm']);\n LP.DisplayFunc = [];\n fprintf('Load model ''%s'' successfully.\\n', loadModel);\n addRow = true;\n if size(LP.Model.A, 1) > m + 2 * nRxnSp + nSp\n %try to find the row that constrains total biomass\n [ynRow, idRow] = ismember(sparse(ones(nSp, 1), (n + 1) : (n + nSp), ones(nSp, 1), 1, n + nSp),...\n LP.Model.A((m + 2 * nRxnSp + nSp + 1):end, 1:(n + nSp)),'rows');\n if ynRow\n idRow = m + 2 * nRxnSp + nSp + idRow;\n end\n addRow = ~ynRow;\n end\n else\n % get the LP structure using SteadyCom\n options2 = options;\n options2.LPonly = true;\n [~, ~, LP] = SteadyCom(modelCom, options2, varargin{:});\n addRow = true; % no constraint on total biomass using LPonly option\n end\n result = struct('GRmax',GRmax,'vBM',[],'BM',[],'Ut',[],'Ex',[],'flux',[],'iter0',[],'iter',[],'stat','optimal');\n GRgiven = true;\nend\nif addRow\n % add a row for constraining the sum of biomass if not exist\n if ibm_cplex\n LP.addRows(BMmaxLB, sparse(ones(1, nSp), (n + 1) : (n + nSp), ones(1, nSp), 1, size(LP.Model.A, 2)), BMmaxUB, 'UnityBiomass');\n idRow = size(LP.Model.A, 1);\n else\n LP.A = [LP.A; sparse([ones(nSp, 1); 2 * ones(nSp, 1)], repmat((n + 1):(n + nSp), 1, 2),...\n ones(nSp * 2, 1), 2, size(LP.A, 2))];\n LP.b = [LP.b; BMmaxUB; BMmaxLB];\n LP.csense = [LP.csense, 'LG'];\n idRow = size(LP.A, 1);\n end\nelse\n % using BMmaxLB and BMmaxUB stored in the LP if not given in options\n if ~isfield(options,'BMmaxLB') % take from LP if not supplied\n if ibm_cplex\n BMmaxLB = LP.Model.lhs(idRow);\n else\n BMmaxLB = LP.b(idRow);\n end\n end\n if ~isfield(options,'BMmaxUB') % take from LP if not supplied\n if ibm_cplex\n BMmaxUB = LP.Model.rhs(idRow);\n else\n BMmaxUB = LP.b(idRow - 1);\n end\n end\n % not allow the max. biomass to exceed the one at max growth rate,\n % can happen if optBMpercent < 100. May dismiss this constraint or\n % manually supply BMmaxUB in the options if sum of biomass should be variable\n if ibm_cplex\n LP.Model.lhs(idRow) = BMmaxLB;\n LP.Model.rhs(idRow) = BMmaxUB;\n else\n LP.b(idRow) = BMmaxLB;\n LP.b(idRow - 1) = BMmaxUB;\n end\nend\nif ibm_cplex\n LP = setCplexParam(LP, solverParams); % set Cplex parameters\n % update the LP to ensure the current growth rate is constrained\n LP.Model.A = SteadyComSubroutines('updateLPcom', modelCom, GRmax, GRfx, [], LP.Model.A, []);\n LP.Model.sense = 'minimize';\n LP.Model.obj(:) = 0;\n LP.solve();\n dev = checkSolFeas(LP);\nelse\n % update the LP to ensure the current growth rate is constrained\n LP.A = SteadyComSubroutines('updateLPcom', modelCom, GRmax, GRfx, [], LP.A, []);\n LP.c(:) = 0;\n LP.osense = 1;\n sol = solveCobraLP(LP, varargin{:});\n dev = checkSolFeas(LP, sol);\n if isfield(sol, 'basis')\n LP.basis = sol.basis; % reuse basis\n end\nend\n% check and adjust for feasibility\n% (LP from SteadyCom should pass this automatically as the row has been added in SteadyComCplex)\nkBMadjust = 0;\nwhile ~(dev <= feasTol) && kBMadjust < 10\n kBMadjust = kBMadjust + 1;\n % relax the required sum of biomass\n if ibm_cplex\n LP.Model.lhs(idRow) = BMmaxLB * (1 - feasTol/(11 - kBMadjust));\n LP.solve();\n dev = checkSolFeas(LP);\n else\n LP.b(idRow) = BMmaxLB * (1 - feasTol/(11 - kBMadjust));\n sol = solveCobraLP(LP, varargin{:});\n dev = checkSolFeas(LP, sol);\n if isfield(sol, 'basis')\n LP.basis = sol.basis; % reuse basis\n end\n end\n if verbFlag\n fprintf('BMmax adjustment: %d\\n', kBMadjust);\n end\nend\nif ~(dev <= feasTol) % dev can be NaN, which still means infeasibility. So use ~(dev <= feasTol) instead of dev > feasTol\n warning('Model not feasible.')\n [minFlux, maxFlux] = deal(NaN(nRxnFVA, numel(optGRpercent)));\n [minFD, maxFD] = deal(NaN(numel(rxnFluxList), nRxnFVA, numel(optGRpercent)));\n GRvector = NaN(numel(optGRpercent), 1);\n result.stat = 'infeasible';\n return\nend\nif GRgiven\n % assign result structure if in the rare case of given growth rate\n if ibm_cplex\n flux = LP.Solution.x;\n else\n flux = sol.full;\n end\n result.vBM = flux(modelCom.indCom.spBm);\n result.BM = flux(n+1:n+nSp);\n % two different types of indexing\n if size(modelCom.indCom.EXcom, 2) == 2\n % uptake and excretion reactions separated\n result.Ut = flux(modelCom.indCom.EXcom(:,1));\n result.Ex = flux(modelCom.indCom.EXcom(:,2));\n else\n % uptake and excretion in one exchange reaction\n [result.Ut, result.Ex] = deal(flux(modelCom.indCom.EXcom(:,1)));\n result.Ut(result.Ut > 0) = 0;\n result.Ut = -result.Ut;\n result.Ex(result.Ex < 0) = 0;\n end\n result.flux = flux(1:n);\nend\n% update BMmaxLB and BMmaxUB for FVA at each given growth rate\nif ~isfield(options, 'BMmaxLB')\n if ibm_cplex\n options.BMmaxLB = LP.Model.lhs(idRow);\n else\n options.BMmaxLB = LP.b(idRow);\n end\nend\nif ~isfield(options, 'BMmaxUB')\n if ibm_cplex\n options.BMmaxUB = LP.Model.rhs(idRow);\n else\n options.BMmaxUB = LP.b(idRow - 1);\n end\nend\n\nGRvector = GRmax * optGRpercent / 100;\nif ~isempty(saveFVA)\n % decide number of digits in the save name\n if numel(optGRpercent) == 1\n kDisp = 2;\n else\n d = min(GRvector(2:end) - GRvector(1:end-1));\n if d < 1\n kDisp = abs(floor(log10(abs(d))));\n else\n kDisp = 0;\n end\n end\n directory = strsplit(saveFVA,filesep);\n if numel(directory) > 1\n % not saving in the current directory. Create the directory.\n directory = strjoin([{pwd}, directory(1:end-1)],filesep);\n if ~exist(directory, 'dir')\n mkdir(directory);\n end\n end\n if ibm_cplex\n LPmodel = LP.Model; % the Cplex dynamic object is not good for saving\n LPstart = LP.Start;\n save([saveFVA '_model.mat'], 'LPmodel', 'LPstart', 'options', 'solverParams', 'parameters');\n clear LPmodel LPstart\n else\n save([saveFVA '_model.mat'], 'LP', 'options', 'solverParams', 'parameters');\n end\nend\n\n[minFlux, maxFlux] = deal(zeros(nRxnFVA, numel(GRvector)));\n[minFD, maxFD] = deal(zeros(numel(rxnFluxList), nRxnFVA, numel(GRvector)));\n\n%parallel computation\ntry\n p = gcp('nocreate');\n if isempty(p)\n if threads > 1\n %given explicit no. of threads\n parpool(ceil(threads));\n elseif threads ~= 1\n %default max no. of threads (input 0 or -1 etc)\n parpool;\n end\n end\ncatch\n %No parallel pool existent\nend\n%perform FVA at each growth rate\nfor j = 1:numel(GRvector)\n optionsJ = options;\n optionsJ.GR = GRvector(j);\n if ~isempty(saveFVA)\n optionsJ.saveFVA = sprintf(['%s_GR%.' num2str(kDisp) 'f'], saveFVA, GRvector(j));\n end\n [minFluxJ,maxFluxJ,minFDj,maxFDj,LP] = SteadyComFVAgr(modelCom,optionsJ, LP, varargin{:});\n minFlux(:, j) = minFluxJ;\n maxFlux(:, j) = maxFluxJ;\n minFD(:,:, j) = minFDj;\n maxFD(:,:, j) = maxFDj;\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/analysis/multiSpecies/SteadyCom/SteadyComFVA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.35982509249137146}} {"text": "% Function to estimate the glottal parameters: NAQ, QOQ, H1-H2, HRF and PSP\n%\n% Octave compatible\n%\n% Description\n% This function can be used to estimate a range of conventional glottal\n% source parameters often used in the literature. This includes: the\n% normalised amplitude quotient (NAQ), the quasi-open quotient (QOQ), the\n% difference in amplitude of the first two harmonics of the differentiated\n% glottal source spectrum (H1-H2), the harmonic richness factor (HRF) and\n% the parabolic spectral parameter (PSP)\n%\n% Inputs\n% gf : [samples] [Nx1] Glottal flow estimation\n% gfd : [samples] [Nx1] Glottal flow derivative estimation\n% fs : [Hz] [1x1] sampling frequency\n% GCI : [s] [Mx1] Glottal closure instants \n%\n% Outputs\n% NAQ : [s,samples] [Mx2] Normalised amplitude quotient\n% QOQ : [s,samples] [Mx2] Quasi-open quotient\n% H1H2 : [s,dB] [Mx2] Difference in glottal harmonic amplitude\n% HRF : [s,samples] [Mx2] Harmonic richness factor\n% PSP : [s,samples] [Mx2] Parabolic spectral parameter\n%\n% Example\n% Please see the HOWTO_glottalsource.m example file.\n%\n% References\n% [1] Alku, P., B ackstrom, T., and Vilkman, E. Normalized amplitude quotient \n% for parameterization of the glottal flow. Journal of the Acoustical \n% Society of America, 112(2):701–710, 2002.\n% [2] Hacki, T. Klassifizierung von glottisdysfunktionen mit hilfe der \n% elektroglottographie. Folia Phoniatrica, pages 43–48, 1989.\n% [3] Alku, P., Strik, H., and Vilkman, E. Parabolic spectral parameter - \n% A new method for quantification of the glottal flow. Speech \n% Communication, 22(1):67–79, 1997.\n% [4] Hanson, H. M. Glottal characteristics of female speakers: Acoustic \n% correlates. Journal of the Acoustical Society of America, \n% 10(1):466–481, 1997.\n% [5] Childers, D. G. and Lee, C. K. Voice quality factors: Analysis, \n% synthesis and perception. Journal of the Acoustical Society of \n% America, 90(5):2394–2410, 1991.\n%\n% Copyright (c) 2013 Trinity College Dublin\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% 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 \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n% \n% Author \n% John Kane kanejo@tcd.ie\n\nfunction [NAQ,QOQ,H1H2,HRF,PSP] = get_vq_params(gf,gfd,fs,GCI)\n\nGCI = round(GCI*fs)+1;\n\n%% Initial settings\nF0min=20;\nF0max=500;\nNAQ=zeros(1,length(GCI));\nQOQ=zeros(1,length(GCI));\nH1H2=zeros(1,length(GCI));\nHRF=zeros(1,length(GCI));\nPSP=zeros(1,length(GCI));\n\nglot_shift=round(0.5/1000*fs);\nqoq_level=0.5; % Threshold for QOQ estimation\nT0_num=3; % Number of local glottal pulses to be used for harmonic spectrum\nmin_harm_num=5;\nHRF_freq_max=5000; % Maximum frequency used for harmonic measurement\nPSP_fft_size=2048; % As per Alku et al (1997)\n\n%% Do processing\nfor n=1:length(GCI)\n \n % Get glottal pulse compensated for zero-line drift\n if n==1\n start=1;\n stop=GCI(n);\n T0=GCI(n+1)-GCI(n);\n else start=GCI(n-1);\n stop=GCI(n);\n T0=GCI(n)-GCI(n-1);\n end\n F0=fs/T0; \n \n if isinf(F0)==0 && T0~=0 && F0 > F0min && F01\n line=interp1(linspace(1,stop-start+1,2),gf_comb, ...\n 1:stop-start+1);\n else line=gf_comb;\n end\n else line=0;\n end\n gf_seg=gf(start:stop);\n gf_seg_comp=gf_seg(:)-line(:);\n \n if stop+glot_shift <= length(gfd)\n stop2=stop+glot_shift;\n else\n stop2=stop;\n end\n gfd_seg=gfd(start:stop2);\n \n % Get NAQ and QOQ \n d_peak = max(abs(gfd_seg));\n [f_ac,max_idx] = max(gf_seg_comp);\n Amid=f_ac*qoq_level;\n [T1,T2] = findAmid_t(gf_seg_comp,Amid,max_idx);\n \n NAQ(n) = (f_ac/d_peak)/T0;\n QOQ(n)=(T2-T1)/(fs/F0);\n \n % Get frame positions for H1-H2 parameter\n if GCI(n)-round((T0*T0_num)/2) > 0\n f_start = GCI(n)-round((T0*T0_num)/2);\n else f_start=1;\n end\n if GCI(n)+round((T0*T0_num)/2) <= length(gfd)\n f_stop = GCI(n)+round((T0*T0_num)/2);\n else f_stop=length(gfd);\n end\n f_frame=gfd(f_start:f_stop);\n f_frame=f_frame.*(2^15);\n f_win=f_frame(:).*hamming(length(f_frame));\n f_spec = mag2db(abs(fft(f_win,fs)));\n \n % Get H1-H2/HRF measurements\n [h_idx,h_amp]=v_findpeaks(f_spec,[],F0/2);\n HRF_harm_num=floor(HRF_freq_max/F0);\n if length(h_idx) >= min_harm_num\n [~,f0_idx] = min(abs(bsxfun(@minus,h_idx,(1:HRF_harm_num)*F0)),[],1);\n H1H2(n)=h_amp(f0_idx(1))-h_amp(f0_idx(2));\n HRF(n) = sum(h_amp(f0_idx(2:end)))/h_amp(f0_idx(1));\n end\n \n % Get PSP\n if n>1\n start=GCI(n-1);\n stop=GCI(n);\n gf_seg=gf(start:stop);\n gf_seg=gf_seg-min(gf_seg); % Adjust minimum to zero\n gf_seg=gf_seg/max(gf_seg); % Scale to unity\n gf_seg(PSP_fft_size)=0; % Zero-pad\n X = mag2db(abs(fft(gf_seg))); % Spectrum\n X = X(linspace(1,fs,length(X))<=fs/2); % Use up to the nyquist\n a = psp_get_a(X);\n \n % Estimate measure of maximal spectral decay\n a_max_sig=1/round(fs/F0)*ones(1,round(fs/F0));\n a_max_sig(PSP_fft_size)=0; % Zero-pad\n X_a_max = mag2db(abs(fft(a_max_sig))); % Spectrum\n X_a_max = X_a_max(linspace(1,fs,length(X_a_max))<=fs/2); % Use up to the nyquist\n a_max = psp_get_a(X_a_max);\n \n PSP(n)=a/a_max;\n end\n \n end\n \n \nend\n\n%% Add in time to parameters\nNAQ=[GCI(:)/fs NAQ(:)];\nQOQ=[GCI(:)/fs QOQ(:)];\nH1H2=[GCI(:)/fs H1H2(:)];\nHRF=[GCI(:)/fs HRF(:)];\nPSP=[GCI(:)/fs PSP(:)];\n\n\nfunction [T1,T2] = findAmid_t(glot_adj,Amid,Tz)\n\n% Function to find the start and stop positions of the quasi-open phase.\n\nT1=0;\nT2=0;\nif Tz~=0\n n=Tz;\n\n while glot_adj(n) > Amid && n > 3\n n=n-1;\n end\n T1=n;\n n=Tz;\n\n while glot_adj(n) > Amid && n < length(glot_adj)-2\n n=n+1;\n end\n T2=n;\nend\n\nfunction a = psp_get_a(X)\n\n% Function to calculate a coefficient, as per section 3.2.1 in Alku et al\n% (1997)\n\n%% Initial settings\nNE_min = 0.01;\nflag = 0;\nN = 3; % An set to an initial value of 3, as per Alku et al (1997)\nX=X(:);\n\n% pre-allocate&compute\nX2=X.^2;\nk2 = ((0:100).^2)';\n\n% init sum\nk2_sum=sum(k2(1:N-1));\nk4_sum=sum(k2(1:N-1).^2);\nX_k1_sum = sum(X(1:N-1));\nX_k1_k2_sum = sum(X((1:N-1)).*k2(1:N-1));\nX2_k1_sum = sum(X2((1:N-1)));\n\n%% Do processing\nwhile flag == 0\n\n % re-allocate if necessary\n if N>numel(k2)\n k2 = ((0:numel(k2)*2).^2)';\n end\n \n % iteratively built sum\n k2_sum= k2_sum + k2(N);\n k4_sum= k4_sum + k2(N)*k2(N);\n X_k1_sum = X_k1_sum + X(N);\n X_k1_k2_sum = X_k1_k2_sum + X(N)*k2(N);\n X2_k1_sum = X2_k1_sum + X2(N);\n \n % Equation 5 \n a = (N*X_k1_k2_sum-X_k1_sum.*k2_sum)/(N*k4_sum-k2_sum.^2); \n \n X_k1_a_k2 = X(1:N)-a*k2(1:N);\n \n % Equation 4\n b = 1/N*sum(X_k1_a_k2);\n NE = (sum((X_k1_a_k2-b).^2))/X2_k1_sum;\n\n % Increment or stop\n if NE < NE_min\n N = N+1;\n else\n flag = 1;\n end \nend\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/glottalsource/get_vq_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.359546995001102}} {"text": "function featureS = calcRadiomicsForImgType(volOrig3M,maskBoundingBox3M,paramS,gridS)\n%calcRadiomicsForImgType.m\n%Derive user-defined image type and extract radiomics features.\n%\n%AI 3/28/19\n%AI 5/1/19 Turned off flag for diffAvg since this is equivalent to dissimilarity. \n\n% Voxel volume for Total Energy calculation\nxValsV = gridS.xValsV;\nyValsV = gridS.yValsV;\nzValsV = gridS.zValsV;\nPixelSpacingX = gridS.PixelSpacingV(1);\nPixelSpacingY = gridS.PixelSpacingV(2);\nPixelSpacingZ = gridS.PixelSpacingV(3);\nVoxelVol = PixelSpacingX*PixelSpacingY*PixelSpacingZ*1000; % convert cm to mm\n\n\nwhichFeatS = paramS.whichFeatS;\nfeatureS = struct;\n\n% Get image types with various parameters\nfieldNamC = fieldnames(paramS.imageType);\nimageTypeC = {};\nfor iImg = 1:length(fieldNamC)\n for iFilt = 1:length(paramS.imageType.(fieldNamC{iImg}))\n filtParamS = struct();\n filtParamS.imageType = fieldNamC{iImg};\n filtParamS.paramS = paramS.imageType.(fieldNamC{iImg})(iFilt);\n imageTypeC{end+1} = filtParamS;\n end\nend\n\n% ---- Calc. shape features (same across img. types) ----\ntic\nif whichFeatS.shape.flag\n rcsV = [];\n if isfield(paramS,'shapeParamS') && isfield(paramS.shapeParamS,'rcs')\n rcsV = paramS.shapeParamS.rcs.';\n end\n featureS.shapeS = getShapeParams(maskBoundingBox3M, ...\n {xValsV, yValsV, zValsV},rcsV);\nend\ntoc\n\n\n%% Loop over image types\nmaskOrig3M = maskBoundingBox3M;\nfor k = 1:length(imageTypeC)\n \n %Generate volume based on original/derived imageType\n if strcmpi(imageTypeC{k}.imageType,'original')\n if isfield(paramS,'toQuantizeFlag')\n quantizeFlag = paramS.toQuantizeFlag;\n else\n quantizeFlag = 0;\n end\n minClipIntensity = []; \n maxClipIntensity = [];\n if isfield(paramS,'textureParamS') && ...\n isfield(paramS.textureParamS,'minClipIntensity')\n minClipIntensity = paramS.textureParamS.minClipIntensity;\n end\n if isfield(paramS,'textureParamS') && ...\n isfield(paramS.textureParamS,'maxClipIntensity')\n maxClipIntensity = paramS.textureParamS.maxClipIntensity;\n end\n volToEval = volOrig3M;\n [minr, maxr, minc, maxc, mins, maxs] = compute_boundingbox(maskBoundingBox3M);\n maskBoundingBox3M = maskOrig3M(minr:maxr, minc:maxc, mins:maxs);\n volToEval = volToEval(minr:maxr, minc:maxc, mins:maxs);\n else\n %Add voxel size in mm to paramS\n voxSizV = [PixelSpacingX, PixelSpacingY, PixelSpacingZ]*10; %convert cm to mm\n imageTypeC{k}.paramS.VoxelSize_mm.val = voxSizV;\n if paramS.whichFeatS.padding.flag && ...\n ~strcmpi(whichFeatS.padding.method,'none')\n paddingSizeV = paramS.whichFeatS.padding.size;\n if length(paddingSizeV)==2\n paddingSizeV(end+1) = 0;\n end\n imageTypeC{k}.paramS.padding.size = paddingSizeV;\n else\n imageTypeC{k}.paramS.padding.size = [0,0,0];\n end\n\n outS = processImage(imageTypeC{k}.imageType,volOrig3M,maskOrig3M,...\n imageTypeC{k}.paramS);\n [minr, maxr, minc, maxc, mins, maxs] = compute_boundingbox(maskOrig3M);\n maskBoundingBox3M = maskOrig3M(minr:maxr, minc:maxc, mins:maxs);\n derivedImgName = fieldnames(outS);\n volToEval = outS.(derivedImgName{1});\n volToEval = volToEval(minr:maxr, minc:maxc, mins:maxs);\n if whichFeatS.texture.flag\n % always quantize the derived image for texture calc.\n quantizeFlag = true;\n else\n if isfield(paramS,'toQuantizeFlag')\n quantizeFlag = paramS.toQuantizeFlag;\n else\n quantizeFlag = false;\n end\n end\n minClipIntensity = []; % no clipping imposed for derived images\n maxClipIntensity = []; \n if isfield(paramS,'textureParamS') && ...\n isfield(paramS.textureParamS,'minClipIntensity')\n minClipIntensity = paramS.textureParamS.minClipIntensity;\n end\n if isfield(paramS,'textureParamS') && ...\n isfield(paramS.textureParamS,'maxClipIntensity')\n maxClipIntensity = paramS.textureParamS.maxClipIntensity;\n end\n end\n \n % Volume without NaNs for Peak/Valley computation\n volToEvalOrigM = volToEval;\n\n % Quantize the volume of interest\n if quantizeFlag \n numGrLevels = [];\n binwidth = [];\n \n if isfield(paramS,'textureParamS')\n if isfield(paramS.textureParamS,'numGrLevels')\n numGrLevels = paramS.textureParamS.numGrLevels;\n end\n if isfield(imageTypeC{k}.paramS,'textureParamS') && ...\n isfield(imageTypeC{k}.paramS.textureParamS,'numGrLevels')\n numGrLevels = imageTypeC{k}.paramS.textureParamS.numGrLevels;\n end\n if isfield(paramS.textureParamS,'binwidth')\n binwidth = paramS.textureParamS.binwidth;\n end\n if isfield(imageTypeC{k}.paramS,'textureParamS') &&...\n isfield(imageTypeC{k}.paramS.textureParamS,'binwidth')\n binwidth = imageTypeC{k}.paramS.textureParamS.binwidth;\n end\n end\n \n % Don't use intensities outside the ROI in discretization\n volToEval(~maskBoundingBox3M) = NaN;\n quantizedM = imquantize_cerr(volToEval,numGrLevels,...\n minClipIntensity,maxClipIntensity,binwidth);\n % Reassign the number of gray levels in case they were computed for the\n % passed binwidth\n numGrLevels = max(quantizedM(:));\n %paramS.textureParamS.numGrLevels = numGrLevels;\n \n else\n quantizedM = volToEval;\n end\n \n quantizedM(~maskBoundingBox3M) = NaN;\n numVoxels = sum(~isnan(quantizedM(:)));\n \n \n %Feature calculation\n outFieldName = createFieldNameFromParameters...\n (imageTypeC{k}.imageType,imageTypeC{k}.paramS);\n\n % --- 1. First-order features ---\n if whichFeatS.firstOrder.flag\n binWidthEntropy = [];\n binNumEntropy = [];\n offsetForEnergy = 0;\n if isfield(paramS.firstOrderParamS,'offsetForEnergy')\n offsetForEnergy = paramS.firstOrderParamS.offsetForEnergy;\n end\n if isfield(paramS.firstOrderParamS,'binWidthEntropy') && ...\n ~isempty(paramS.firstOrderParamS.offsetForEnergy)\n binWidthEntropy = paramS.firstOrderParamS.binWidthEntropy;\n end\n if isfield(paramS.firstOrderParamS,'binNumEntropy') && ...\n ~isempty(paramS.firstOrderParamS.binNumEntropy)\n binNumEntropy = paramS.firstOrderParamS.binNumEntropy;\n end\n if isfield(imageTypeC{k}.paramS,'firstOrderParamS') && ...\n isfield(imageTypeC{k}.paramS.firstOrderParamS,'offsetForEnergy')\n offsetForEnergy = imageTypeC{k}.paramS.firstOrderParamS.offsetForEnergy;\n end\n if isfield(imageTypeC{k}.paramS,'binWidthEntropy') && ...\n isfield(imageTypeC{k}.paramS.firstOrderParamS,'binWidthEntropy')\n binWidthEntropy = imageTypeC{k}.paramS.firstOrderParamS.binWidthEntropy;\n end\n if isfield(imageTypeC{k}.paramS,'binNumEntropy') && ...\n isfield(imageTypeC{k}.paramS.firstOrderParamS,'binNumEntropy')\n binNumEntropy = imageTypeC{k}.paramS.firstOrderParamS.binNumEntropy;\n end\n volV = volToEval(logical(maskBoundingBox3M));\n volV = volV(:);\n featureS.(outFieldName).firstOrderS = radiomics_first_order_stats...\n (volV, VoxelVol,offsetForEnergy,binWidthEntropy,binNumEntropy);\n end\n \n %---2. Higher-order (texture) features ----\n \n %Get directionality and avg type\n if any([whichFeatS.glcm.flag,whichFeatS.glrlm.flag,whichFeatS.gtdm.flag,...\n whichFeatS.gldm.flag,whichFeatS.glszm.flag])\n \n directionality = paramS.textureParamS.directionality;\n avgType = paramS.textureParamS.avgType;\n switch lower(directionality)\n case '2d'\n dirctn = 2;\n case '3d'\n dirctn = 1;\n otherwise\n error('Invalid input. Directionality must be \"2D\" or \"3D\"');\n end\n \n switch lower(avgType)\n case 'texturematrix'\n %Haralick features with combined cooccurrence matrix\n cooccurType = 1;\n case 'feature'\n %'Haralick features from separate cooccurrence matrix per direction, averaged'\n cooccurType = 2;\n otherwise\n error('Invalid input. Directionality must be \"2D\" or \"3D\"');\n end\n \n %numGrLevels = paramS.textureParamS.numGrLevels;\n voxelOffset = paramS.textureParamS.voxelOffset;\n \n % a. GLCM\n if whichFeatS.glcm.flag\n \n featC = whichFeatS.glcm.featureList;\n glcmFlagS = getHaralickFlags(featC);\n featureS.(outFieldName).glcmFeatS = get_haralick(dirctn, voxelOffset, cooccurType, quantizedM, ...\n numGrLevels, glcmFlagS);\n \n end\n \n % b. GLRLM\n if whichFeatS.glrlm.flag\n featC = whichFeatS.glrlm.featureList;\n rlmFlagS = getRunLengthFlags(featC);\n rlmType = cooccurType;\n featureS.(outFieldName).rlmFeatS = get_rlm(dirctn, rlmType, quantizedM, ...\n numGrLevels, numVoxels, rlmFlagS);\n end\n \n %c. GTDM\n if whichFeatS.gldm.flag\n patchRadiusV = paramS.textureParamS.patchRadiusVox;\n [s,p] = calcNGTDM(quantizedM, patchRadiusV, ...\n numGrLevels);\n featureS.(outFieldName).ngtdmFeatS = ngtdmToScalarFeatures(s,p,numVoxels);\n end\n \n \n %d. GLDM\n if whichFeatS.gldm.flag\n patchRadiusV = paramS.textureParamS.patchRadiusVox;\n imgDiffThresh = paramS.textureParamS.imgDiffThresh;\n ngldM = calcNGLDM(quantizedM, patchRadiusV,numGrLevels,imgDiffThresh);\n featureS.(outFieldName).ngldmFeatS = ngldmToScalarFeatures(ngldM,numVoxels);\n end\n \n \n %e. GLSZM\n if whichFeatS.glszm.flag\n featC = whichFeatS.glszm.featureList;\n szmFlagS = getSizeZoneFlags(featC);\n szmType = dirctn; % 1: 3d, 2: 2d\n szmM = calcSZM(quantizedM, numGrLevels, szmType);\n numVoxels = sum(~isnan(quantizedM(:)));\n featureS.(outFieldName).szmFeatS = szmToScalarFeatures(szmM,numVoxels, szmFlagS);\n end\n \n \n \n %f. Peak-valley\n if whichFeatS.peakValley.flag\n radiusV = paramS.peakValleyParamS.peakRadius;\n units = paramS.peakValleyParamS.units; %'cm' or 'vox'\n featureS.(outFieldName).peakValleyFeatureS = getImPeakValley(maskBoundingBox3M,...\n volToEvalOrigM, radiusV, units);\n end\n \n %g. IVH\n if whichFeatS.ivh.flag\n IVHBinWidth = paramS.ivhParamS.binwidth; %IVH binwidth\n xForIxV = paramS.ivhParamS.xForIxPct; % percentage volume\n xAbsForIxV = paramS.ivhParamS.xForIxCc; % absolute volume [cc]\n xForVxV = paramS.ivhParamS.xForVxPct; % percent intensity cutoff\n xAbsForVxV = paramS.ivhParamS.xForVxAbs; % absolute intensity cutoff [HU]\n scanV = double(volToEval(maskBoundingBox3M));\n volV = repmat(VoxelVol,numel(scanV),1);\n featureS.(outFieldName).ivhFeaturesS = getIvhParams(scanV, volV, IVHBinWidth,...\n xForIxV, xAbsForIxV, xForVxV, xAbsForVxV);\n \n end\n end\n \nend\n\n%% -------------- Sub-functions ----------------------------\n function glcmFlagS = getHaralickFlags(varargin)\n \n %Default: all features\n glcmFlagS.energy = 1;\n glcmFlagS.jointEntropy = 1;\n glcmFlagS.jointMax = 1;\n glcmFlagS.jointAvg = 1;\n glcmFlagS.jointVar = 1;\n glcmFlagS.contrast = 1;\n glcmFlagS.invDiffMoment = 1;\n glcmFlagS.sumAvg = 1;\n glcmFlagS.corr = 1;\n glcmFlagS.clustShade = 1;\n glcmFlagS.clustProm = 1;\n glcmFlagS.haralickCorr = 1;\n glcmFlagS.invDiffMomNorm = 1;\n glcmFlagS.invDiff = 1;\n glcmFlagS.invDiffNorm = 1;\n glcmFlagS.invVar = 1;\n glcmFlagS.dissimilarity = 1;\n glcmFlagS.diffEntropy = 1;\n glcmFlagS.diffVar = 1;\n glcmFlagS.diffAvg = 0; %Equivalent to dissimilarity\n glcmFlagS.sumVar = 1;\n glcmFlagS.sumEntropy = 1;\n glcmFlagS.clustTendency = 1;\n glcmFlagS.autoCorr = 1;\n glcmFlagS.invDiffMomNorm = 1;\n glcmFlagS.firstInfCorr = 1;\n glcmFlagS.secondInfCorr = 1;\n \n if nargin==1 && ~strcmpi(varargin{1},'all')\n featureC = varargin{1};\n allFeatC = fieldnames(glcmFlagS);\n idxV = find(~ismember(allFeatC,featureC));\n for n = 1:length(idxV)\n glcmFlagS.(allFeatC{idxV(n)}) = 0;\n end\n end\n \n end\n\n function rlmFlagS = getRunLengthFlags(varargin)\n \n rlmFlagS.shortRunEmphasis = 1;\n rlmFlagS.longRunEmphasis = 1;\n rlmFlagS.grayLevelNonUniformity = 1;\n rlmFlagS.grayLevelNonUniformityNorm = 1;\n rlmFlagS.runLengthNonUniformity = 1;\n rlmFlagS.runLengthNonUniformityNorm = 1;\n rlmFlagS.runPercentage = 1;\n rlmFlagS.lowGrayLevelRunEmphasis = 1;\n rlmFlagS.highGrayLevelRunEmphasis = 1;\n rlmFlagS.shortRunLowGrayLevelEmphasis = 1;\n rlmFlagS.shortRunHighGrayLevelEmphasis = 1;\n rlmFlagS.longRunLowGrayLevelEmphasis = 1;\n rlmFlagS.longRunHighGrayLevelEmphasis = 1;\n rlmFlagS.grayLevelVariance = 1;\n rlmFlagS.runLengthVariance = 1;\n rlmFlagS.runEntropy = 1;\n \n if nargin==1 && ~strcmpi(varargin{1},'all')\n featureC = lower(varargin{1});\n allFeatC = lower(fieldnames(rlmFlagS));\n idxV = find(~ismember(allFeatC,featureC));\n for n = 1:length(idxV)\n rlmFlagS.(allFeatC{idxV(n)}) = 0;\n end\n end\n \n end\n\nfunction szmFlagS = getSizeZoneFlags(varargin)\n \n szmFlagS.grayLevelNonUniformity = 1;\n szmFlagS.grayLevelNonUniformityNorm = 1;\n szmFlagS.grayLevelVariance = 1;\n szmFlagS.highGrayLevelZoneEmphasis = 1;\n szmFlagS.lowGrayLevelZoneEmphasis = 1;\n szmFlagS.largeAreaEmphasis = 1;\n szmFlagS.largeAreaHighGrayLevelEmphasis = 1;\n szmFlagS.largeAreaLowGrayLevelEmphasis = 1;\n szmFlagS.sizeZoneNonUniformity = 1;\n szmFlagS.sizeZoneNonUniformityNorm = 1;\n szmFlagS.sizeZoneVariance = 1;\n szmFlagS.zonePercentage = 1;\n szmFlagS.smallAreaEmphasis = 1; \n szmFlagS.smallAreaLowGrayLevelEmphasis = 1;\n szmFlagS.smallAreaHighGrayLevelEmphasis = 1;\n szmFlagS.zoneEntropy = 1;\n \n \n if nargin==1 && ~strcmpi(varargin{1},'all')\n featureC = lower(varargin{1});\n allFeatC = fieldnames(szmFlagS);\n idxV = find(~ismember(allFeatC,featureC));\n for n = 1:length(idxV)\n szmFlagS.(allFeatC{idxV(n)}) = 0;\n end\n end\n \n end\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/calcRadiomicsForImgType.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300449389327, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.35949628929881533}} {"text": "function [y,swp]=tt_wround(W, x, eps, varargin)\n%Approximates a vector in the weighted norm using DMRG iterations\n% [Y,SWP]=TT_WROUND(W,X,EPS,OPTIONS). Approximate the TT-vector X in the\n% norm ||W(y-x)|| via the DMRG iterations. If W is not specified, it is\n% assumed to be equal to the identity matrix. \n% Options are provided in form 'PropertyName1',PropertyValue1,\n% 'PropertyName2',PropertyValue2 and so on. The parameters are set to \n% default (in brackets in the following) The list of option names and \n% default values are:\n% o kickrank -- the additional ranks, the larger the more robust the\n% method is, but the complexity increases [5]\n% o rmax - maximal TT-rank during the iterations [1000]\n% o nswp - maximal number of DMRG sweeps [25]\n% o y0 - initial appoximation [random rank-2 tensor]\n% o verb - verbosity level, 0-silent, 1-sweep info, 2-block info [1]\n% o d_pow_check - d-power for checking the convergence [0]\n% o bot_conv - bottom convergence factor [0.1]\n% o top_conv - top convergence factor [0.99]\n\n\n% @bydlocode parameters\nkickrank = 5;\ndropsweeps = 1; % garbage - for quasi-wedderburn\n% dropsweeps2 = 10; % garbage\n% d_pow_trunc = 1.5; % garbage\nddpow = 0.1; % stepsize for d-power in truncations\nddrank = 1; % stepsize for additional rank\nd_pow_check = 0; % d-power for checking the convergence\nbot_conv = 0.1; % bottom convergence factor - if better, we can decrease dpow and drank\ntop_conv = 0.99; % top convergence factor - if worse, we have to increase dpow and drank\nverb = 1; % 0 - silent, 1 - sweep information, 2 - block information\n\nd = size(x,1);\n\n\ny = tt_ones(d, tt_size(x));\ny = tt_scal2(y, -tt_dot2(y,y)/2, 1);\n\nrmax=1000;\nnswp=25;\n\nfor i=1:2:length(varargin)-1\n if (~isempty(varargin{i+1}))\n switch lower(varargin{i})\n case 'nswp'\n nswp=varargin{i+1};\n case 'rmax'\n rmax=lower(varargin{i+1});\n case 'y0'\n y=varargin{i+1};\n case 'verb'\n verb=varargin{i+1};\n case 'kickrank'\n kickrank=varargin{i+1};\n case 'ddpow'\n ddpow=varargin{i+1};\n case 'ddrank'\n ddrank=varargin{i+1};\n case 'd_pow_check'\n d_pow_check=varargin{i+1};\n case 'bot_conv'\n bot_conv=varargin{i+1};\n case 'top_conv'\n top_conv=varargin{i+1};\n otherwise\n error('Unrecognized option: %s\\n',varargin{i});\n end\n end;\nend\n\n% if (isempty(W))\n% W = tt_eye(tt_size(x),d);\n% end;\n\nx{1}=reshape(x{1}, size(x{1},1),1,size(x{1},2));\ny{1}=reshape(y{1}, size(y{1},1),1,size(y{1},2));\nif (~isempty(W))\n W{1}=reshape(W{1}, size(W{1},1), size(W{1},2), 1,size(W{1},3));\nend;\n\nif (~isempty(W))\n phiywy = cell(d+1,1); phiywy{1}=1; phiywy{d+1}=1;\n phiywx = cell(d+1,1); phiywx{1}=1; phiywx{d+1}=1;\nend;\nphiyx = cell(d+1,1); phiyx{1}=1; phiyx{d+1}=1;\n\nlast_sweep = false;\ndy_old = ones(d-1,1);\ndy = zeros(d-1,1);\n% artificial rank additions\ndrank = ones(d-1,1);\n% d-power for stronger compression eps./(d.^dpows)\ndpows = ones(d-1,1);\n\nfor swp=1:nswp\n % QR and Phi\n for i=d:-1:2\n y1 = y{i}; n1 = size(y1,1); r1 = size(y1,2); r2 = size(y1,3);\n y1 = permute(y1, [1 3 2]);\n y1 = reshape(y1, n1*r2, r1);\n [y1,rv]=qr(y1,0); % size n1*r2,rnew - rnew,r1\n y2 = y{i-1}; n2 = size(y2,1); r0 = size(y2,2);\n y2 = reshape(y2, n2*r0, r1);\n y2 = y2*(rv.'); % size n2*r0, rnew\n r1 = size(y1,2);\n y1 = reshape(y1, n1, r2, r1);\n y1 = permute(y1, [1 3 2]);\n y{i}=y1;\n y{i-1}=reshape(y2, n2,r0,r1);\n \n % Update phi. phiywy = y^T W y, phiywx = y^T W x, phiyx = y^T x\n y1 = permute(y1, [3 1 2]);\n y1 = reshape(y1, r2*n1, r1);\n x1 = x{i}; rx1 = size(x1,2); rx2 = size(x1,3);\n x1 = reshape(x1, n1*rx1, rx2);\n phiyx{i} = phiyx{i+1}*(x1.'); % size r2, n1*rx1\n phiyx{i} = reshape(phiyx{i}, r2*n1, rx1);\n phiyx{i}=(y1')*phiyx{i}; % size r1, rx1\n \n if (~isempty(W))\n w1 = W{i}; rw1 = size(w1,3); rw2 = size(w1,4);\n phiywx{i}=reshape(phiywx{i+1}, r2*rw2, rx2)*(x1.'); % size r2*rw2,n1*rx1\n phiywx{i}=reshape(phiywx{i}, r2, rw2, n1, rx1);\n phiywx{i}=permute(phiywx{i}, [3 2 4 1]);\n phiywx{i}=reshape(phiywx{i}, n1*rw2, rx1*r2);\n w1 = permute(w1, [1 3 2 4]);\n w1 = reshape(w1, n1*rw1, n1*rw2);\n phiywx{i}=w1*phiywx{i}; % size n1*rw1, rx1*r2\n phiywx{i}=reshape(phiywx{i}, n1, rw1, rx1, r2);\n phiywx{i}=permute(phiywx{i}, [4 1 2 3]);\n phiywx{i}=reshape(phiywx{i}, r2*n1, rw1*rx1);\n phiywx{i}=(y1')*phiywx{i}; % size r1, rw1*rx1;\n phiywx{i}=reshape(phiywx{i}, r1, rw1, rx1);\n \n y1 = reshape(y1, r2, n1*r1);\n phiywy{i}=reshape(phiywy{i+1}, r2*rw2, r2)*y1; % size r2*rw2,n1*r1\n phiywy{i}=reshape(phiywy{i}, r2, rw2, n1, r1);\n phiywy{i}=permute(phiywy{i}, [3 2 4 1]);\n phiywy{i}=reshape(phiywy{i}, n1*rw2, r1*r2);\n phiywy{i}=w1*phiywy{i}; % size n1*rw1, r1*r2\n phiywy{i}=reshape(phiywy{i}, n1, rw1, r1, r2);\n phiywy{i}=permute(phiywy{i}, [4 1 2 3]);\n phiywy{i}=reshape(phiywy{i}, r2*n1, rw1*r1);\n y1 = reshape(y1, r2*n1, r1);\n phiywy{i}=(y1')*phiywy{i}; % size r1, rw1*r1;\n phiywy{i}=reshape(phiywy{i}, r1, rw1, r1);\n end;\n end;\n \n % DMRG sweep\n for i=1:d-1\n x1 = x{i}; n1 = size(x1,1); rx1 = size(x1,2); rx2 = size(x1,3);\n x2 = x{i+1}; n2 = size(x2,1); rx3 = size(x2,3);\n if (~isempty(W))\n w1 = W{i}; rw1 = size(w1,3); rw2 = size(w1,4);\n w2 = W{i+1}; rw3 = size(w2,4); \n end;\n y1 = y{i}; ry1 = size(y1,2); ry2 = size(y1,3);\n y2 = y{i+1}; ry3 = size(y2,3); \n ryold = ry2;\n \n x1 = permute(x1, [2 1 3]);\n x1 = reshape(x1, rx1, n1*rx2);\n ynew = phiyx{i}*x1; % size ry1, n1*rx2\n ynew = reshape(ynew, ry1*n1, rx2);\n x2 = permute(x2, [2 1 3]);\n x2 = reshape(x2, rx2, n2*rx3);\n ynew = ynew*x2; % size ry1*n1,n2*rx3\n ynew = reshape(ynew, ry1*n1*n2, rx3);\n ynew = ynew*(phiyx{i+2}.'); % size ry1*n1*n2, ry3\n ynew = reshape(ynew, ry1*n1, n2*ry3);\n \n if (~isempty(W))\n rhs = reshape(phiywx{i}, ry1*rw1, rx1)*x1; % size ry1*rw1, n1*rx2\n rhs = reshape(rhs, ry1, rw1, n1, rx2);\n rhs = permute(rhs, [3 2 1 4]);\n rhs = reshape(rhs, n1*rw1, ry1*rx2);\n w1 = permute(w1, [1 4 2 3]);\n w1 = reshape(w1, n1*rw2, n1*rw1);\n rhs = w1*rhs; % size n1*rw2, ry1*rx2\n rhs = reshape(rhs, n1,rw2,ry1, rx2);\n rhs = permute(rhs, [3 1 2 4]);\n rhs = reshape(rhs, ry1*n1, rw2*rx2);\n \n rhs2 = reshape(phiywx{i+2}, ry3*rw3, rx3);\n x2 = reshape(x2, rx2*n2, rx3);\n rhs2 = rhs2*(x2.'); % size ry3*rw3, rx2*n2\n rhs2 = reshape(rhs2, ry3, rw3, rx2, n2);\n rhs2 = permute(rhs2, [4 2 3 1]);\n rhs2 = reshape(rhs2, n2*rw3, rx2*ry3);\n w2 = permute(w2, [1 3 2 4]);\n w2 = reshape(w2, n2*rw2, n2*rw3);\n rhs2 = w2*rhs2; % size n2*rw2, rx2*ry3\n rhs2 = reshape(rhs2, n2, rw2*rx2, ry3);\n rhs2 = permute(rhs2, [1 3 2]);\n rhs2 = reshape(rhs2, n2*ry3, rw2*rx2);\n rhs = rhs*(rhs2.'); % size ry1*n1, n2*ry3\n rhs = reshape(rhs, ry1*n1*n2*ry3, 1);\n \n mtx = cell(2,1);\n mtx{1} = permute(phiywy{i}, [1 3 2]);\n mtx{1} = reshape(mtx{1}, ry1*ry1, rw1);\n w1 = reshape(w1, n1*rw2*n1, rw1);\n mtx{1} = mtx{1}*(w1.'); % size ry1*ry1, n1*rw2*n1\n mtx{1} = reshape(mtx{1}, ry1, ry1, n1, rw2, n1);\n mtx{1} = permute(mtx{1}, [1 3 2 5 4]);\n mtx{1} = reshape(mtx{1}, ry1*n1, ry1*n1, rw2);\n \n mtx{2} = permute(phiywy{i+2}, [1 3 2]);\n mtx{2} = reshape(mtx{2}, ry3*ry3, rw3);\n w2 = reshape(w2, n2*rw2*n2, rw3);\n mtx{2}= mtx{2}*(w2.'); % size ry3*ry3, n2*rw2*n2\n mtx{2} = reshape(mtx{2}, ry3, ry3, n2, rw2, n2);\n mtx{2} = permute(mtx{2}, [3 1 5 2 4]);\n mtx{2} = reshape(mtx{2}, n2*ry3, n2*ry3, rw2);\n end;\n \n y1 = permute(y1, [2 1 3]);\n y1 = reshape(y1, ry1*n1, ry2);\n y2 = permute(y2, [2 1 3]);\n y2 = reshape(y2, ry2, n2*ry3); \n yprev = y1*y2; % ry1*n1, n2*ry3\n \n vdy = ynew-yprev;\n if (~isempty(W))\n vdy = bfun2(W, vdy, ry1, n1, n2, ry3, ry1, n1, n2, ry3);\n else\n rhs = ynew;\n end;\n dy(i) = norm(vdy, 'fro')/norm(rhs, 'fro');\n if (norm(rhs, 'fro')==0)\n dy(i)=0;\n end;\n if (swp==1)\n dy_old(i)=dy(i);\n end;\n \n % The new core does not converge - increase rank\n if (dy(i)/dy_old(i)>top_conv)&&(dy(i)>eps/(d^d_pow_check))\n drank(i)=drank(i)+ddrank;\n dpows(i)=dpows(i)+ddpow;\n end;\n % The new core converges well - try to decrease rank\n if (dy(i)/dy_old(i)1)&&(~last_sweep)\n % for quasi-wedderburn\n [u,s,v]=svd(ynew-yprev,'econ');\n else\n [u,s,v]=svd(ynew, 'econ');\n end;\n if (~isempty(W))\n % Bin search\n r0 = 1; rM = min(size(s,1),rmax); r = round((r0+rM)/2); \n while (rM-r0>1)\n cur_err = norm(s(r+1:end,r+1:end), 'fro')/norm(s,'fro');\n cur_sol = reshape(u(:,1:r)*s(1:r,1:r)*v(:,1:r)', ry1*n1*n2*ry3, 1);\n cur_res = norm(bfun2(mtx,cur_sol,ry1,n1,n2,ry3,ry1,n1,n2,ry3) - rhs)/norm(rhs);\n if (verb>1)\n fprintf('sweep %d, block %d, rank: %d, resid: %3.3e, L2-err: %3.3e\\n', swp, i, r, cur_res, cur_err);\n end;\n if (cur_res1)\n fprintf('sweep %d, block %d, rank: %d, resid: %3.3e, L2-err: %3.3e\\n', swp, i, r, cur_res, cur_err);\n end;\n if (cur_res1)\n fprintf('sweep %d, block %d, rank: %d, dy: %3.3e, dy_old: %3.3e, drank: %g, dpow: %g\\n', swp, i, r, dy(i), dy_old(i), drank(i), dpows(i));\n end;\n% if (dropflag==1)&&(i==d-1)\n% dropflag=0;\n% end;\n \n u = u(:,1:r);\n v = conj(v(:,1:r))*s(1:r,1:r);\n if (mod(swp,dropsweeps)~=0)&&(swp>1)&&(~last_sweep)\n % Add new vectors to a basis\n u = [y1, u]; % ry1*n1, ry2+r\n v = [y2.', v]; % n2*ry3, ry2+r\n [u,rv]=qr(u,0);\n ry2 = size(u,2);\n v = v*(rv.'); \n else\n % kick\n if (~last_sweep)\n u = reort(u, randn(size(u,1),kickrank));\n r = size(u,2);\n v = [v, zeros(size(v,1),r-size(v,2))];\n end;\n ry2 = size(u,2);\n end;\n \n% [u,rv]=qr(u,0); \n% r = size(u,2);\n% v = v*(rv.');\n% u = reshape(u, ry1*n1,r);\n% v = reshape(v, n2,ry3, r);\n y{i}=permute(reshape(u, ry1, n1, ry2), [2 1 3]);\n y{i+1}=permute(reshape(v, n2, ry3, ry2), [1 3 2]);\n\n % Update phi. phiywy = y^T W y, phiywx = y^T W x, phiyx = y^T x\n x1 = x{i}; rx1 = size(x1,2); rx2 = size(x1,3);\n x1 = reshape(permute(x1, [2 1 3]), rx1, n1*rx2);\n phiyx{i+1} = phiyx{i}*x1; % size ry1, n1*rx2\n phiyx{i+1} = reshape(phiyx{i+1}, ry1*n1, rx2);\n phiyx{i+1}=(u')*phiyx{i+1}; % size ry2, rx2\n \n if (~isempty(W))\n w1 = W{i}; rw1 = size(w1,3); rw2 = size(w1,4);\n phiywx{i+1}=reshape(phiywx{i}, ry1*rw1, rx1)*x1; % size ry1*rw1,n1*rx2\n phiywx{i+1}=reshape(phiywx{i+1}, ry1, rw1, n1, rx2);\n phiywx{i+1}=permute(phiywx{i+1}, [3 2 4 1]);\n phiywx{i+1}=reshape(phiywx{i+1}, n1*rw1, rx2*ry1);\n w1 = permute(w1, [2 3 1 4]);\n w1 = reshape(w1, n1*rw1, n1*rw2);\n phiywx{i+1}=(w1.')*phiywx{i+1}; % size n1*rw2, rx2*ry1\n phiywx{i+1}=reshape(phiywx{i+1}, n1, rw2, rx2, ry1);\n phiywx{i+1}=permute(phiywx{i+1}, [4 1 2 3]);\n phiywx{i+1}=reshape(phiywx{i+1}, ry1*n1, rw2*rx2);\n phiywx{i+1}=(u')*phiywx{i+1}; % size ry2, rw2*rx2;\n phiywx{i+1}=reshape(phiywx{i+1}, ry2, rw2, rx2);\n \n u = reshape(u, ry1, n1*ry2);\n phiywy{i+1}=reshape(phiywy{i}, ry1*rw1, ry1)*u; % size ry1*rw1,n1*ry2\n phiywy{i+1}=reshape(phiywy{i+1}, ry1, rw1, n1, ry2);\n phiywy{i+1}=permute(phiywy{i+1}, [3 2 4 1]);\n phiywy{i+1}=reshape(phiywy{i+1}, n1*rw1, ry2*ry1);\n phiywy{i+1}=(w1.')*phiywy{i+1}; % size n1*rw2, ry2*ry1\n phiywy{i+1}=reshape(phiywy{i+1}, n1, rw2, ry2, ry1);\n phiywy{i+1}=permute(phiywy{i+1}, [4 1 2 3]);\n phiywy{i+1}=reshape(phiywy{i+1}, ry1*n1, rw2*ry2);\n u = reshape(u, ry1*n1, ry2);\n phiywy{i+1}=(u')*phiywy{i+1}; % size ry2, rw2*ry2;\n phiywy{i+1}=reshape(phiywy{i+1}, ry2, rw2, ry2);\n end;\n end;\n% if (mod(swp,chksweeps)==0)||(swp==1)\n% y{1}=reshape(y{1}, size(y{1},1), size(y{1},3));\n% reschk = norm(tt_tensor(y)-tt_tensor(y_prev))/sqrt(tt_dot(y,y));\n% y_prev = y;\n% y{1}=reshape(y{1}, size(y{1},1),1, size(y{1},2));\n% end; \n if (verb>0)\n fprintf('=wround= Sweep %d, dy_max: %3.3e, conv_max: %1.5f\\n', swp, max(dy), max(dy)/max(dy_old));\n end;\n if (last_sweep)\n break;\n end;\n% if (reschkeps/(d^d_pow_check))\n fprintf('tt_wround warning: error is not fixed for maximal number of sweeps %d, err_max: %3.3e\\n', swp, max(dy)); \nend;\n\nend\n\n\nfunction [y]=bfun2(B, x, rxm1, m1, m2, rxm3, rxn1, k1, k2, rxn3)\n% Computes (B{1} \\otimes B{2})x\n% B{1} is of sizes rxn1*k1, rxm1*m1, rB\n% B{2} is of sizes k2*rxn3, m2*rxm3, rB\nrB=size(B{1},3);\nx = reshape(x, rxm1*m1, m2*rxm3);\nB1 = permute(B{1}, [3 1 2]);\nB1 = reshape(B1, rB*rxn1*k1, rxm1*m1);\ny = B1*x; % size rB*rxn1*k1,m2*rxm3\ny = reshape(y, rB, rxn1*k1, m2*rxm3);\ny = permute(y, [3 1 2]);\ny = reshape(y, m2*rxm3*rB, rxn1*k1);\nB2 = reshape(B{2}, k2*rxn3, m2*rxm3*rB);\ny = B2*y; % size k2*rxn3,rxn1*k1\ny = reshape(y.', rxn1*k1*k2*rxn3, 1);\nend\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/core/tt_wround.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3588787298227148}} {"text": "function STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, varargin)\n%STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, varargin)\n%\n% PCA-Lasso based prediction on a set of brain images\n% Tor Wager, Sept. 2009\n%\n% Inputs:\n% my_outcomes: a cell array of outcomes for each dataset\n% imgs: a cell array of image names for each dataset\n% \n% Alternative: \"Object-oriented\" mode\n% my_outcomes = [];\n% imgs = an fmri_data object, with imgs.Y = outcomes\n%\n% Optional inputs:\n% 'reversecolors', reversecolors = 1;\n% 'skipnonparam', dononparam = 0;\n% 'skipsurface', dosurface = 0;\n% {'cov', 'covs', 'covariates'}, covs = varargin{i+1};\n% 'mask', mask = varargin{i+1}; varargin{i + 1} = [];\n% 'niter', niter = varargin{i+1};\n% 'more_imgs', followed by 2nd (or nth) set of\n% images in cell array {}\n% 'outcome_name', outcome_name = varargin{i+1}; varargin{i + 1} = [];\n% 'covnames', covnames = varargin{i+1}; varargin{i + 1} = [];\n% 'save', dosave = 1;\n% 'ndims', ndims = varargin{i+1}; varargin{i + 1} = [];\n% 'pca', plsstr = 'pca'; % default...\n% 'pls', plsstr = 'pls';\n% {'choose_regparams', 'dochoose_regparams', 'optimize_regularization'}, dochoose_regparams_str = 'optimize_regularization';\n% {'holdout_method'} followed by string e.g., 'balanced4'\n% or custom holdout set of integers for each test set; see\n% xval_regression_multisubject\n%\n% Examples\n% -----------------------------------------------------------------------\n% mkdir LASSO_xvalidation_frontal\n% cd LASSO_xvalidation_frontal/\n% mask = '/Users/tor/Documents/Tor_Documents/CurrentExperiments/Combined_sample_2007/newmask_mapped.img';\n% load('/Users/tor/Documents/Tor_Documents/CurrentExperiments/Combined_sample_2007/robust0004/robust0001/SETUP.mat')\n% imgs = {SETUP.files};\n% my_outcomes = {SETUP.X(:, 2)};\n% covs = {SETUP.X(:, [3 4 5])};\n% outcome_name = 'Placebo Analgesia (C-P)';\n% covnames = {'Order' 'Study' 'Study x Placebo'};\n% STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, 'mask', mask, 'covs', covs, 'reversecolors', 'skipsurface', 'skipnonparam');\n%\n% or\n%\n% STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, 'mask', mask, 'covs', covs, 'reversecolors');\n%\n% STATS_FINAL = xval_lasso_brain({img_dat_cat_masked.Y}, {imgs}, 'mask', maskname, 'outcome_name', img_dat_cat_masked.Y_names, 'niter', 1000, 'holdout_method', id_numbers, 'save');\n%\n% For fmri_data object inputs:\n% STATS_FINAL = xval_lasso_brain([], img_dat_cat_masked, 'mask', maskname, 'niter', 1000, 'holdout_method', id_numbers, 'save');\n\n% Programmers' notes\n% Updated 3/7/2013 tor wager\n% - changed rng to rng from 'twister' (legacy)\n% - documentation\n% - updated to take object-oriented fmri_data file as input\n\n\n % -----------------------------------------------------------------------\n % Optional inputs\n % -----------------------------------------------------------------------\n spm_defaults\n covs = [];\n mask = which('brainmask.nii');\n reversecolors = 0;\n dononparam = 1;\n dosurface = 1;\n niter = 200;\n covnames = {'Unknown'};\n outcome_name = 'Unknown';\n verbose = 1;\n imgs2 = {};\n dosave = 0;\n ndims = 'variable';\n plsstr = 'pca';\n dochoose_regparams_str = 'verbose'; % switch to 'optimize_regularization' to do inner xval\n holdout_method = 'loo'; % see xval_regression_multisubject\n \n if isa(imgs, 'image_vector')\n outcome_name = imgs.Y_names;\n my_outcomes = {imgs.Y};\n end\n \n inputOptions.all_optional_inputs = varargin;\n \n for i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n % Process control\n case 'reversecolors', reversecolors = 1;\n case 'skipnonparam', dononparam = 0;\n case 'skipsurface', dosurface = 0;\n\n % Covariates and Masking\n case {'cov', 'covs', 'covariates'}, covs = varargin{i+1};\n case 'mask', mask = varargin{i+1}; varargin{i + 1} = [];\n case 'niter', niter = varargin{i+1};\n\n % Input images\n case 'more_imgs', imgs2{end+1} = varargin{i+1};\n fprintf('Found additional image set %3.0f\\n', length(imgs2));\n\n\n % Naming output and saving\n case 'outcome_name', outcome_name = varargin{i+1}; varargin{i + 1} = [];\n case 'covnames', covnames = varargin{i+1}; varargin{i + 1} = [];\n case 'save', dosave = 1;\n\n % Dimension reduction\n case 'ndims', ndims = varargin{i+1}; varargin{i + 1} = [];\n if strcmp(ndims, 'all')\n ndims = size(imgs{1}, 1) - 2;\n fprintf('Choosing %3.0f dims for PCA/PLS\\n', ndims);\n end\n\n case 'pca', plsstr = 'pca'; % default...\n case 'pls', plsstr = 'pls';\n\n % Shrinkage/regularization parameters\n\n case {'choose_regparams', 'dochoose_regparams', 'optimize_regularization'}, dochoose_regparams_str = 'optimize_regularization';\n\n % Holdout set selection\n\n case {'holdout_method'}, holdout_method = varargin{i+1}; varargin{i + 1} = [];\n\n\n case {'variable', 'verbose'} % do nothing; needed later\n\n otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\n end\n\n \n inputOptions.all_outcomes = my_outcomes;\n inputOptions.outcome_name = outcome_name;\n inputOptions.imgs = imgs;\n inputOptions.covs = covs;\n inputOptions.covnames = covnames;\n inputOptions.mask = mask;\n inputOptions.ndims = ndims;\n inputOptions.plsstr = plsstr;\n inputOptions.reversecolors = reversecolors;\n inputOptions.dochoose_regparams_str = dochoose_regparams_str;\n inputOptions.holdout_method = holdout_method;\n\n % set up the mask\n % -------------------------------------------------------------------------\n if isempty(mask), error('Mask is empty and/or default mask ''brainmask.nii'' cannot be found on path.'); end\n \n if isa(imgs, 'image_vector')\n if isa(mask, 'image_vector')\n \n mask = resample_space(mask, imgs);\n \n else % mask is string\n \n mask = fmri_data(mask);\n end\n maskInfo = mask.volInfo;\n \n else\n \n if exist(fullfile(pwd, 'mask.img')) && verbose, disp('''mask.img'' already exists in this directory. Replacing.'); else disp('Creating mask.img'); end\n scn_map_image(mask, deblank(imgs{1}(1,:)), 'write', 'mask.img');\n maskInfo = iimg_read_img(fullfile(pwd, 'mask.img'), 2);\n end\n \n inputOptions.maskInfo = maskInfo;\n\n datasets = length(imgs); % each Subject would constitute a \"dataset\" for a multi-level/within-subjects analysis\n \n % load image data and apply mask\n % -------------------------------------------------------------------------\n % Object-oriented input\n if isa(imgs, 'image_vector')\n fprintf('Loading all datasets and applying mask ');\n imgs = apply_mask(imgs, mask);\n dat{1} = imgs.dat';\n size_orig{1} = [1 imgs.volInfo.n_inmask]; % for reconstruction\n \n if ~isempty(imgs2) && isa(imgs, 'image_vector')\n imgs2 = apply_mask(imgs2, mask);\n dat{1} = [dat{1} imgs2.dat'];\n elseif ~isempty(imgs2)\n error('imags and imgs2 must both be objects or neither can be an object.');\n end\n \n else\n % load from image names\n \n fprintf('Loading all datasets (may be memory-intensive for multi-subject fMRI): ');\n for i = 1:datasets\n fprintf('%02d', i);\n dat{i} = iimg_get_data(maskInfo, imgs{i});\n size_orig{i} = size(dat{i});\n \n if ~isempty(imgs2)\n for imgset = 1:length(imgs2)\n dat{i} = [dat{i} iimg_get_data(maskInfo, imgs2{imgset}{i})];\n end\n \n end\n \n end\n fprintf('\\n');\n end\n \n %%\n\n STATS_FINAL = struct('inputOptions', inputOptions);\n\n % Run it: covs only\n % -------------------------------------------------------------------------\n STATS_FINAL.covs = [];\n if ~isempty(covs)\n disp('==================================')\n disp('Covariates only: OLS')\n STATS_FINAL.covs = xval_regression_multisubject('ols', my_outcomes, covs, 'holdout_method', holdout_method);\n end\n\n % Run it: data only\n % -------------------------------------------------------------------------\n if ~isempty(covs)\n disp('==================================')\n disp('Data only: lasso')\n STATS_FINAL.data = xval_regression_multisubject('lasso', my_outcomes, dat, 'pca', 'ndims', ndims, plsstr, dochoose_regparams_str, 'holdout_method', holdout_method);\n else\n STATS_FINAL.data = 'see .full_model';\n end\n\n % Run it: combined\n % -------------------------------------------------------------------------\n\n % My best guess about what will work: Lasso, with as many dims retained as possible\n % * NOTE: all of the main inputs should be cell arrays\n STATS_FINAL.full_model = [];\n if ~isempty(covs)\n disp('==================================')\n disp('Data plus covariates full model: lasso')\n STATS_FINAL.full_model = xval_regression_multisubject('lasso', my_outcomes, dat, 'pca', 'ndims', ndims, 'cov', covs, plsstr, dochoose_regparams_str, 'holdout_method', holdout_method);\n else\n disp('Data only full model: lasso')\n disp('==================================')\n STATS_FINAL.full_model = xval_regression_multisubject('lasso', my_outcomes, dat, 'pca', 'ndims', ndims, plsstr, dochoose_regparams_str, 'holdout_method', holdout_method);\n end\n\n if dosave\n save STATS_xval_output STATS_FINAL\n end\n\n %% Figures: Scatterplot plus bars\n % -------------------------------------------------------------------------\n\n create_figure('Scatterplot: Full model', 1, 2);\n [r,istr,sig,h] = plot_correlation_samefig(STATS_FINAL.full_model.subjfit{1}, STATS_FINAL.inputOptions.all_outcomes{1});\n set(gca,'FontSize', 24)\n xlabel('Cross-validated prediction');\n ylabel('Outcome');\n title('Lasso cross-validation');\n set(h, 'MarkerSize', 10, 'MarkerFaceColor', [.0 .4 .8], 'LineWidth', 2);\n h = findobj(gca, 'Type', 'Text');\n set(h, 'FontSize', 24)\n\n % bars\n subplot(1, 2, 2)\n set(gca,'FontSize', 24)\n\n if ~isempty(covs)\n pevals = [std(STATS_FINAL.inputOptions.all_outcomes{1}) ...\n STATS_FINAL.full_model.pred_err_null STATS_FINAL.covs.pred_err ...\n STATS_FINAL.data.pred_err STATS_FINAL.full_model.pred_err];\n penames = {'Var(Y)' 'Mean' 'Covs' 'Brain' 'Full'};\n else\n pevals = [std(STATS_FINAL.inputOptions.all_outcomes{1}) ...\n STATS_FINAL.full_model.pred_err_null STATS_FINAL.full_model.pred_err];\n penames = {'Var(Y)' 'Mean' 'Brain'};\n end\n\n han = bar(pevals); set(han, 'FaceColor', [.5 .5 .5]);\n set(gca, 'XTick', 1:length(penames), 'XTickLabel', penames);\n axis tight\n ylabel('Prediction error');\n\n if dosave\n scn_export_papersetup(500); saveas(gcf, 'Pred_Outcome_Scatter', 'png');\n end\n\n % is accuracy predicted by Y and/or covariates?\n % ****\n \n \n \n %% Get mean Lasso betas\n % -------------------------------------------------------------------------\n\n bonf_thresh = norminv(1 - .025 ./ size(dat{1}, 2));\n\n mystd = std(STATS_FINAL.full_model.vox_weights'); % not actual valid threshold because training sets are not independent\n\n [my_ste,t,n_in_column,p,m] = ste(STATS_FINAL.full_model.vox_weights');\n Z = (m ./ mystd)';\n \n if isa(mask, 'image_vector')\n not_in_mask = mask.dat == 0;\n my_ste = zeroinsert(not_in_mask, my_ste')';\n t = zeroinsert(not_in_mask, t')';\n n_in_column = zeroinsert(not_in_mask, n_in_column')';\n p = zeroinsert(not_in_mask, p')';\n m = zeroinsert(not_in_mask, m')';\n Z = zeroinsert(not_in_mask, Z);\n end\n \n i = 1;\n iimg_reconstruct_vols(m(1: size_orig{i}(2))', maskInfo, 'outname', 'xval_lasso_wts_mean.img');\n iimg_reconstruct_vols(Z(1: size_orig{i}(2)), maskInfo, 'outname', 'xval_lasso_Z.img');\n \n if length(m) > size_orig{i}\n iimg_reconstruct_vols(m(size_orig{i}(2)+1:end)', maskInfo, 'outname', 'xval_lasso_wts_mean_imageset2.img');\n iimg_reconstruct_vols(Z(size_orig{i}(2)+1:end), maskInfo, 'outname', 'xval_lasso_Z_imageset2.img');\n end\n \n sig_vox = abs(Z) > bonf_thresh;\n Z_thresh = Z;\n Z_thresh(~sig_vox) = 0;\n iimg_reconstruct_vols(Z_thresh(1: size_orig{i}(2)), maskInfo, 'outname', 'xval_lasso_Z_bonf_thresh.img');\n \n if length(m) > size_orig{i}\n iimg_reconstruct_vols(Z_thresh(size_orig{i}(2)+1:end), maskInfo, 'outname', 'xval_lasso_Z_bonf_thresh.img');\n end\n\n %% Orthviews\n % -------------------------------------------------------------------------\n\n if any(Z_thresh)\n cl = mask2clusters('xval_lasso_Z_bonf_thresh.img');\n else\n disp('No significant voxel weights at bonferroni corrected threshold.')\n cl = [];\n end\n\n poscm2 = colormap_tor([1 .5 0], [1 1 0]);\n negcm2 = colormap_tor([.5 0 1], [0 0 1]);\n\n cluster_orthviews(cl);\n\n\n if reversecolors\n cm = spm_orthviews_change_colormap([1 1 0], [0 0 1], [1 0 .4], [.4 .6 1] );\n else\n cm = spm_orthviews_change_colormap([0 0 1], [1 1 0], [.4 .6 1], [1 0 .4]);\n end\n\n STATS_FINAL.full_model.cl = cl;\n\n %cm = spm_orthviews_change_colormap([0 0 1], [1 1 0], [0 0 1], [0 0 1], [0\n %.5 1], [0 .5 1], [.5 .5 .5], [.5 .5 .5], [.7 0 0], [1 .5 0], [1 .5 0], [1 1 0]);\n\n % cm = spm_orthviews_change_colormap([0 0 1], [1 1 0], [0 0 1], [0 0 1], [0 .5 1], [0 .5 1], [.5 .5 .5], [.5 .5 .5], [.7 0 0], [1 .5 0], [1 .5 0], [1 1 0]);\n\n %% Brain Surface Plot\n % -------------------------------------------------------------------------\n\n if dosurface\n\n create_figure('Brain_Surface', 2, 2);\n\n if reversecolors\n negcm = colormap_tor([1 0 .4], [1 1 0]);\n poscm = colormap_tor([.4 .6 1], [0 0 1]);\n else\n poscm = colormap_tor([1 0 .4], [1 1 0]);\n negcm = colormap_tor([.4 .6 1], [0 0 1]);\n end\n\n han1 = addbrain('hires');\n cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han1);\n\n %replace with 'hires' and re-run to do whole cortical surface\n create_figure('Brain_Surface', 2, 2, 1);\n subplot(2, 2, 2);\n han = addbrain('hires right'); set(han, 'FaceAlpha', 1);\n\n drawnow\n cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);\n set(han, 'FaceAlpha', 1);\n axis image; lightRestoreSingle;\n lighting gouraud\n\n create_figure('Brain_Surface', 2, 2, 1);\n subplot(2, 2, 3);\n han = addbrain('hires left'); set(han, 'FaceAlpha', 1);\n axis image; lightRestoreSingle;\n lighting gouraud\n drawnow\n cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);\n\n create_figure('Brain_Surface', 2, 2, 1);\n subplot(2, 2, 4);\n han = addbrain('limbic'); set(han, 'FaceAlpha', 1);\n axis image; lightRestoreSingle;\n lighting gouraud\n drawnow\n cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);\n\n set(han(end), 'FaceAlpha', .2)\n han2 = addbrain('brainstem');\n cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);\n view(135, 15)\n\n create_figure('Brain_Surface', 2, 2, 1);\n subplot(2, 2, 1)\n han = findobj(gca,'Type','patch'); set(han, 'FaceAlpha',1)\n axis image\n\n if dosave\n scn_export_papersetup(600); saveas(gcf, 'Surface1', 'png');\n subplot(2, 2, 1);\n view(135, 20); lightRestoreSingle;\n saveas(gcf, 'Surface2', 'png');\n view(225, 20); lightRestoreSingle;\n saveas(gcf, 'Surface3', 'png');\n view(90, 3); lightRestoreSingle;\n saveas(gcf, 'Surface4', 'png');\n view(270, 3); lightRestoreSingle;\n saveas(gcf, 'Surface5', 'png');\n end\n\n end\n\n %% NONPARAMETRIC TEST\n\n if dononparam\n\n disp('PERMUTATION TEST FOR NULL HYPOTHESIS');\n\n\n % Permute : covariates only\n % ==============================================\n if ~isempty(covs)\n clear my_outcomesp all_r pe\n ndims = min(size(covs{1}, 2) - 1, size(covs{1}, 1) - 2); % will not work for multilevel with diff. dimensions per dataset\n\n fprintf('Covariates only: Running %3.0f iterations\\n', niter);\n\n for i = 1:niter\n\n %rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...\n try\n rng('shuffle');\n catch\n rand('twister',sum(100*clock)) ; % was getting wacky results suggesting randperm is not producing indep. perms...\n end\n \n my_outcomes = STATS_FINAL.inputOptions.all_outcomes;\n\n % permute\n for s = 1:datasets\n ix = randperm(length(my_outcomes{s}));\n my_outcomesp{s} = my_outcomes{s}(ix);\n end\n\n %% Do the prediction\n % ------------------------------------------------------------------\n if size(covs, 2) > 1\n STATSpcovs = xval_regression_multisubject('lasso', my_outcomesp, covs, 'noverbose', 'holdout_method', holdout_method); %,'pca', 'ndims', ndims);\n else\n STATSpcovs = xval_regression_multisubject('ols', my_outcomesp, covs, 'noverbose', 'holdout_method', holdout_method); %,'pca', 'ndims', ndims);\n end\n\n fprintf('%3.2f ', STATSpcovs.r_each_subject);\n\n all_r(i) = STATSpcovs.r_each_subject;\n pe(i) = STATSpcovs.pred_err;\n\n end\n\n STATS_FINAL.covs.permuted.pe_values = pe;\n STATS_FINAL.covs.permuted.pe_mean = mean(pe);\n STATS_FINAL.covs.permuted.pe_ci = [prctile(pe, 5) prctile(pe, 95)];\n STATS_FINAL.covs.permuted.r_values = all_r;\n STATS_FINAL.covs.permuted.r_mean = mean(all_r);\n STATS_FINAL.covs.permuted.r_ci = [prctile(all_r, 5) prctile(all_r, 95)];\n if dosave\n save STATS_xval_output -append STATS_FINAL\n end\n\n fprintf('\\n')\n\n end\n\n % Permute : random subset of 1000 voxels\n % ==============================================\n n_vox = 1000;\n if size(dat{1}, 2) > n_vox\n clear my_outcomesp my_datp all_r pe\n ndims = size(dat{1}, 1) - 2;\n\n fprintf('1000 vox subsets: %3.0f iterations: %3.0f', niter, 0);\n\n for i = 1:niter\n\n fprintf('\\b\\b\\b%3.0f', i);\n\n try\n rng('shuffle');\n catch\n rand('twister',sum(100*clock)) ; % was getting wacky results suggesting randperm is not producing indep. perms...\n end\n \n my_outcomes = STATS_FINAL.inputOptions.all_outcomes;\n\n % permute\n for s = 1:datasets\n ix = randperm(length(my_outcomes{s}));\n ix2 = randperm(size(dat{s}, 2));\n\n my_outcomesp{s} = my_outcomes{s}(ix);\n my_datp{s} = dat{s}(:, ix2(1:n_vox));\n\n end\n\n %% Do the prediction\n % ------------------------------------------------------------------\n STATSpv= xval_regression_multisubject('lasso', my_outcomesp, my_datp, 'pca', plsstr, 'ndims', ndims, dochoose_regparams_str, 'holdout_method', holdout_method, 'noverbose');\n\n all_r(i) = STATSpv.r_each_subject;\n pe(i) = STATSpv.pred_err;\n\n end\n\n fprintf('%3.2f ', all_r);\n fprintf('\\n')\n\n STATS_FINAL.full_model.permuted.v1000_pe_values = pe;\n STATS_FINAL.full_model.permuted.v1000_pe_mean = mean(pe);\n STATS_FINAL.full_model.permuted.v1000_pe_ci = [prctile(pe, 5) prctile(pe, 95)];\n STATS_FINAL.full_model.permuted.v1000_r_values = all_r;\n STATS_FINAL.full_model.permuted.v1000_r_mean = mean(all_r);\n STATS_FINAL.full_model.permuted.v1000_r_ci = [prctile(all_r, 5) prctile(all_r, 95)];\n if dosave\n save STATS_xval_output -append STATS_FINAL\n end\n end\n\n % Permute : Full data\n % ==============================================\n clear my_outcomesp all_r pe\n ndims = size(dat{1}, 1) - 2;\n\n fprintf('1000 vox subsets: %3.0f iterations\\n', niter);\n\n for i = 1:niter\n\n %rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...\n try\n rng('shuffle');\n catch\n rand('twister',sum(100*clock)) ; % was getting wacky results suggesting randperm is not producing indep. perms...\n end\n \n my_outcomes = STATS_FINAL.inputOptions.all_outcomes;\n\n % permute\n for s = 1:datasets\n ix = randperm(length(my_outcomes{s}));\n my_outcomesp{s} = my_outcomes{s}(ix);\n end\n\n %% Do the prediction\n % ------------------------------------------------------------------\n STATSp = xval_regression_multisubject('lasso', my_outcomesp, dat, 'pca', plsstr, 'ndims', ndims, dochoose_regparams_str, 'holdout_method', holdout_method);\n\n fprintf('Iteration %3.0f : r = %3.2f\\n', STATSp.r_each_subject);\n\n all_r(i) = STATSp.r_each_subject;\n pe(i) = STATSp.pred_err;\n\n end\n\n STATS_FINAL.full_model.permuted.pe_values = pe;\n STATS_FINAL.full_model.permuted.pe_mean = mean(pe);\n STATS_FINAL.full_model.permuted.pe_ci = [prctile(pe, 5) prctile(pe, 95)];\n\n STATS_FINAL.full_model.permuted.r_values = all_r;\n STATS_FINAL.full_model.permuted.r_mean = mean(all_r);\n STATS_FINAL.full_model.permuted.r_ci = [prctile(all_r, 5) prctile(all_r, 95)];\n if dosave\n save STATS_xval_output -append STATS_FINAL\n end\n\n end % if do nonparam\n\nend % main function\n\n\n\n% - Extra stuff -\n\n% % %% Bootstrap the covariates\n% % %\n% % % This is the \"Leave one out bootstrap\" of Efron and Tibshirani, JASA, 1997\n% % % Err(1)\n% % % They show that this can be done by taking the error on each point from\n% % % bootstrap samples that do not happen to contain that point\n% % %\n% % % they say that for continuous outcomes and predictors (our case), they\n% % % expect the cross-val estimate and the 632+ bootstrap estimate to be more\n% % % similar. the benefit is mainly for discontinuous outcomes (1/0)\n% % %\n% % % they say that Err(1) is biased upwards compared to the nearly unbiased\n% % % CV(1) (leave-one-out cross-validation)\n% % % it estimates \"half-sample\" xval\n% %\n% % bootfun = @(Y, X) xval_regression_boostrap_wrapper(Y, X);\n% % STATS_FINAL.bootstrap.covs_only_r_rsq = bootstrp(200, bootfun, my_outcomes_orig{1}, covs{1});\n% % STATS_FINAL.bootstrap.covs_only_summary = [mean(STATS_FINAL.bootstrap.covs_only_r_rsq) std(STATS_FINAL.bootstrap.covs_only_r_rsq) ];\n% % STATS_FINAL.bootstrap.covs_only_summary_descrip = 'mean std of bootstrapped values'\n% %\n% % STATS_FINAL.bootstrap.dat_only_r_rsq = bootstrp(20, bootfun, my_outcomes_orig{1}, dat{1});\n% %\n% % STATS_FINAL.bootstrap.dat_only_r_rsq = [STATS_FINAL.bootstrap.dat_only_r_rsq; bootstrp(80, bootfun, my_outcomes_orig{1}, dat{1})];\n% %\n% % STATS_FINAL.bootstrap.dat_only_summary = [mean(STATS_FINAL.bootstrap.dat_only_r_rsq) std(STATS_FINAL.bootstrap.dat_only_r_rsq) ];\n% % STATS_FINAL.bootstrap.dat_only_summary_descrip = 'mean std of bootstrapped values'\n% %\n% % %% Nonparametric test with N variables (voxels) selected at random\n% %\n% % s = 1;\n% %\n% %\n% % n_vox = [1000:2000:50000];\n% % niter = [1 50];\n% %\n% % if niter(1) == 1, all_r_perm = zeros(niter(2), length(n_vox + 1)); end\n% %\n% % for i = 1:length(n_vox)\n% % for j = niter(1):niter(2)\n% %\n% % rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...\n% %\n% % ix = randperm(length(my_outcomes{s}));\n% % ix2 = randperm(size(dat{s}, 2));\n% %\n% % STATSperm= xval_regression_multisubject('lasso', {my_outcomes{1}(ix)}, {dat{1}(:, ix2(1:n_vox(i)))}, 'pca', 'ndims', ndims);\n% %\n% % all_r_perm(j, i) = STATSperm.r_each_subject;\n% %\n% % end\n% %\n% % create_figure('permuted');\n% % plot(n_vox(1:size(all_r_perm, 2)), mean(all_r_perm), 'ko-', 'Linewidth', 3);\n% % xlabel('Number of voxels'); ylabel('Average predicted/actual correlation');\n% % drawnow\n% % end\n% %\n% % % with full sample\n% % n_vox(end+1) = size(dat{s}, 2);\n% % i = length(n_vox);\n% %\n% % for j = niter(1):niter(2)\n% %\n% % rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...\n% %\n% % ix = randperm(length(my_outcomes{s}));\n% % %ix2 = randperm(size(dat{s}, 2));\n% %\n% % STATSperm= xval_regression_multisubject('lasso', {my_outcomes{1}(ix)}, dat(1), 'pca', 'ndims', ndims);\n% %\n% % all_r_perm(j, i) = STATSperm.r_each_subject;\n% %\n% % end\n% %\n% % create_figure('permuted');\n% % plot(n_vox(1:size(all_r_perm, 2)), mean(all_r_perm), 'ko-', 'Linewidth', 3);\n% % xlabel('Number of voxels'); ylabel('Average predicted/actual correlation');\n% % drawnow\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Cross_validated_Regression/xval_lasso_brain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.35884996639729444}} {"text": "function r = mtimes(p,q)\n% MEAS/MTIMES Implement p * q for meas.\n\n% make a meas called r\nr = meas();\n\n% give it the right entries\nr.value = p.value * q.value;\nr.error = r.value * sqrt((p.error/p.value)^2 + (q.error/q.value)^2);", "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/16606-error-propagation-class/@meas/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.3585257198641218}} {"text": "function [s, cfg] = ft_statfun_depsamplesFmultivariate(cfg, dat, design)\n\n% FT_STATFUN_DEPSAMPLESFMULTIVARIATE calculates the MANOVA dependent samples\n% F-statistic on the biological data in dat (the dependent variable), using the\n% information on the independent variable (ivar) in design.\n%\n% Use this function by calling one of the high-level statistics functions as\n% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)\n% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)\n% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)\n% with the following configuration option\n% cfg.statistic = 'ft_statfun_depsamplesFmultivariate'\n%\n% Configuration options\n% cfg.contrastcoefs = matrix of contrast coefficients determining the\n% effect being tested. The number of columns of this\n% matrix has to be equal to the number of conditions. \n% The default is a matrix that specifies the\n% main effect of the independent variable. This matrix\n% has size [(ncond-1),ncond]. \n% cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes')\n% cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no')\n% cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no')\n%\n% The following options are relevant if cfg.computecritval='yes' and/or\n% cfg.computeprob='yes'.\n% cfg.alpha = critical alpha-level of the statistical test (default=0.05)\n% cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1)\n% cfg.tail in combination with cfg.computecritval='yes'\n% determines whether the critical value is computed at\n% quantile cfg.alpha (with cfg.tail=-1), at quantiles\n% cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at\n% quantile (1-cfg.alpha) (with cfg.tail=1).\n%\n% Design specification\n% cfg.ivar = row number of the design that contains the labels of the conditions that must be \n% compared (default=1). The labels range from 1 to the number of conditions.\n% cfg.uvar = row number of design that contains the labels of the units-of-observation (subjects or trials)\n% (default=2). The labels are assumed to be integers ranging from 1 to \n% the number of units-of-observation.\n%\n% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS\n\n% Copyright (C) 2006, Eric Maris\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\n% set defaults\nif ~isfield(cfg, 'computestat'), cfg.computestat='yes'; end\nif ~isfield(cfg, 'computecritval'), cfg.computecritval='no'; end\nif ~isfield(cfg, 'computeprob'), cfg.computeprob='no'; end\nif ~isfield(cfg, 'alpha'), cfg.alpha=0.05; end\nif ~isfield(cfg, 'tail'), cfg.tail=1; end\n\nnconds=length(unique(design(cfg.ivar,:)));\nif ~isfield(cfg,'contrastcoefs')\n % specify the default contrast coefficient matrix.\n ncontrasts = nconds-1;\n cfg.contrastcoefs = zeros(ncontrasts,nconds);\n cfg.contrastcoefs(:,1) = 1;\n for contrastindx=1:ncontrasts\n cfg.contrastcoefs(contrastindx,contrastindx+1)=-1;\n end\nelse\n ncontrasts = size(cfg.contrastcoefs,1);\nend\n\n% perform some checks on the configuration\nif strcmp(cfg.computeprob,'yes') && strcmp(cfg.computestat,'no')\n ft_error('P-values can only be calculated if the test statistics are calculated.');\nend\nif ~isfield(cfg,'uvar') || isempty(cfg.uvar)\n ft_error('uvar must be specified for dependent samples statistics');\nend\n\n% perform some checks on the design\nnuospercond=zeros(nconds,1);\nfor condindx=1:nconds\n nuospercond(condindx)=length(find(design(cfg.ivar,:)==condindx));\nend\nif sum(nuospercond) 1\n if prnt > 0\n fprintf('PLB and/or PUB not specified. Estimating plausible bounds from starting set X0...\\n');\n end\n width = max(x0) - min(x0);\n if isempty(PLB)\n PLB = min(x0) - width/N0;\n PLB = max(PLB,LB);\n end\n if isempty(PUB)\n PUB = max(x0) + width/N0;\n PUB = min(PUB,UB);\n end\n \n idx = any(PLB == PUB);\n if any(idx)\n PLB(idx) = LB(idx);\n PUB(idx) = UB(idx);\n warning('vbmc:pbInitFailed', ...\n 'Some plausible bounds could not be determined from starting set. Using hard upper/lower bounds for those instead.')\n end\n else\n warning('vbmc:pbUnspecified', ...\n 'Plausible lower/upper bounds PLB and/or PUB not specified and X0 is not a valid starting set. Using hard upper/lower bounds instead.');\n if isempty(PLB); PLB = LB; end\n if isempty(PUB); PUB = UB; end\n end\nend\n\n% Test that all vectors have the same length\nif any([numel(LB),numel(UB),numel(PLB),numel(PUB)] ~= nvars)\n error('All input vectors (X0, LB, UB, PLB, PUB), if specified, need to have the same size.');\nend\n\n% Test that all vectors are row vectors\nif ~isvector(LB) || ~isvector(UB) || ~isvector(PLB) || ~isvector(PUB) ...\n || size(LB,1) ~= 1 || size(UB,1) ~= 1 || size(PLB,1) ~= 1 || size(PUB,1) ~= 1\n error('All input vectors LB, UB, PLB, PUB, if specified, should be row vectors.');\nend\n\n% Test that plausible bounds are finite\nif ~all(isfinite(([PLB, PUB]))) \n error('Plausible interval bounds PLB and PUB need to be finite.');\nend\n\n% Test that all vectors are real-valued\nif ~isreal([x0(:)', LB, UB, PLB, PUB])\n error('All input vectors should be real-valued.');\nend\n\n% Fixed variables (all bounds equal) are not supported\nfixidx = (LB == UB) & (UB == PLB) & (PLB == PUB);\nif any(fixidx)\n error('vbmc:FixedVariables', ...\n 'VBMC does not support fixed variables. Lower and upper bounds should be different.');\nend\n\n% Test that plausible bounds are different\nif any(PLB == PUB)\n error('vbmc:MatchingPB', ...\n 'For all variables, plausible lower and upper bounds need to be distinct.')\nend\n\n% Check that all X0 are inside the bounds\nif any(any(bsxfun(@lt,x0,LB))) || any(any(bsxfun(@gt,x0,UB)))\n error('vbmc:InitialPointsNotInsideBounds', ...\n 'The starting points X0 are not inside the provided hard bounds LB and UB.');\nend\n\n% Compute \"effective\" bounds (slightly inside provided hard bounds)\nbounds_range = UB - LB;\nbounds_range(isinf(bounds_range)) = 1e3;\nscale_factor = 1e-3;\nLB_eff = LB + scale_factor*bounds_range;\nLB_eff(abs(LB) <= realmin) = scale_factor*bounds_range(abs(LB) <= realmin);\nUB_eff = UB - scale_factor*bounds_range;\nUB_eff(abs(UB) <= realmin) = -scale_factor*bounds_range(abs(UB) <= realmin);\nLB_eff(isinf(LB)) = LB(isinf(LB)); % Infinities stay the same\nUB_eff(isinf(UB)) = UB(isinf(UB));\n\nif any(LB_eff >= UB_eff)\n error('vbmc:StrictBoundsTooClose', ...\n 'Hard bounds LB and UB are numerically too close. Make them more separate.');\nend\n\n% Fix when provided X0 are almost on the bounds -- move them inside\nif any(any(bsxfun(@le,x0,LB_eff))) || any(any(bsxfun(@ge,x0,UB_eff)))\n warning('vbmc:InitialPointsTooClosePB', ...\n 'The starting points X0 are on or numerically too close to the hard bounds LB and UB. Moving the initial points more inside...');\n x0 = bsxfun(@max, bsxfun(@min,x0,UB_eff), LB_eff);\nend\n\n% Test order of bounds (permissive)\nordidx = LB <= PLB & PLB < PUB & PUB <= UB;\nif any(~ordidx)\n error('vbmc:StrictBounds', ...\n 'For each variable, hard and plausible bounds should respect the ordering LB < PLB < PUB < UB.');\nend\n\n% Test that plausible bounds are reasonably separated from hard bounds\nordidx = LB_eff < PLB & PUB < UB_eff;\nif any(~ordidx)\n warning('vbmc:TooCloseBounds', ...\n 'For each variable, hard and plausible bounds should not be too close. Moving plausible bounds.');\n PLB = max(PLB,LB_eff);\n PUB = min(PUB,UB_eff); \nend\n\n% Check that all X0 are inside the plausible bounds, move bounds otherwise\nif any(any(bsxfun(@le,x0,PLB))) || any(any(bsxfun(@ge,x0,PUB)))\n warning('vbmc:InitialPointsOutsidePB', ...\n 'The starting points X0 are not inside the provided plausible bounds PLB and PUB. Expanding the plausible bounds...');\n PLB = min(PLB,min(x0,[],1));\n PUB = max(PUB,max(x0,[],1));\nend\n\n% Test order of bounds\nordidx = LB < PLB & PLB < PUB & PUB < UB;\nif any(~ordidx)\n error('vbmc:StrictBounds', ...\n 'For each variable, hard and plausible bounds should respect the ordering LB < PLB < PUB < UB.');\nend\n\n\n\n% Test that variables are either bounded or unbounded (not half-bounded)\nhalfbnd = (isinf(LB) & isfinite(UB)) | (isfinite(LB) & isinf(UB));\nif any(halfbnd)\n error('vbmc:HalfBounds', ...\n 'Each variable needs to be unbounded or bounded. Variables bounded only below/above are not supported.'); \nend", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/misc/boundscheck_vbmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3571489075956567}} {"text": "% dbn - training a DBN with up-down algorithm\n% Copyright (C) 2011 KyungHyun Cho, Tapani Raiko, Alexander Ilin\n%\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (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 Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n%\nfunction [D] = dbn(D, patches);\n\nactual_lrate = D.learning.lrate;\n\nn_samples = size(patches, 1);\n\nlayers = D.structure.layers;\nn_layers = length(layers);\n\nif layers(1) ~= size(patches, 2)\n error('Data is not properly aligned');\nend\n\nminibatch_sz = D.learning.minibatch_sz;\nn_minibatches = ceil(n_samples / minibatch_sz);\n\nn_epochs = D.iteration.n_epochs;\n\nmomentum = D.learning.momentum;\nweight_decay = D.learning.weight_decay;\n\nrec.biases_grad = cell(n_layers-1, 1);\nrec.W_grad = cell(n_layers-1, 1);\nrec.biases_grad_old = cell(n_layers-1, 1);\nrec.W_grad_old = cell(n_layers-1, 1);\nfor l = 1:n_layers-1\n rec.biases_grad{l} = zeros(size(D.rec.biases{l}))';\n if l < n_layers\n rec.W_grad{l} = zeros(size(D.rec.W{l}));\n end\n rec.biases_grad_old{l} = zeros(size(D.rec.biases{l}))';\n if l < n_layers\n rec.W_grad_old{l} = zeros(size(D.rec.W{l}));\n end\nend\n\ngen.biases_grad = cell(n_layers-1, 1);\ngen.W_grad = cell(n_layers-1, 1);\ngen.biases_grad_old = cell(n_layers-1, 1);\ngen.W_grad_old = cell(n_layers-1, 1);\nfor l = 1:n_layers-1\n gen.biases_grad{l} = zeros(size(D.gen.biases{l}))';\n if l < n_layers\n gen.W_grad{l} = zeros(size(D.gen.W{l}));\n end\n gen.biases_grad_old{l} = zeros(size(D.gen.biases{l}))';\n if l < n_layers\n gen.W_grad_old{l} = zeros(size(D.gen.W{l}));\n end\nend\n\ntop.W_grad = zeros(size(D.top.W));\ntop.vbias_grad = zeros(size(D.top.vbias));\ntop.hbias_grad = zeros(size(D.top.hbias));\n\ntop.W_grad_old = zeros(size(D.top.W));\ntop.vbias_grad_old = zeros(size(D.top.vbias));\ntop.hbias_grad_old = zeros(size(D.top.hbias));\n\nmin_recon_error = Inf;\nmin_recon_error_update_idx = 0;\nstopping = 0;\n\nanneal_counter = 0;\nactual_lrate0 = actual_lrate;\n\nif D.debug.do_display == 1\n figure(D.debug.display_fid);\nend\n\ntry\n use_gpu = gpuDeviceCount;\ncatch errgpu\n use_gpu = false;\n disp(['Could not use CUDA. Error: ' errgpu.identifier])\nend\n\nfor step=1:n_epochs\n if D.verbose\n fprintf(2, 'Epoch %d/%d: ', step, n_epochs)\n end\n if use_gpu\n % push\n for l = 1:n_layers-1\n if l < n_layers-1\n D.rec.W{l} = gpuArray(single(D.rec.W{l}));\n D.gen.W{l} = gpuArray(single(D.gen.W{l}));\n end\n D.rec.biases{l} = gpuArray(single(D.rec.biases{l}));\n D.gen.biases{l} = gpuArray(single(D.gen.biases{l}));\n end\n\n D.top.W = gpuArray(single(D.top.W));\n D.top.vbias = gpuArray(single(D.top.vbias));\n D.top.hbias = gpuArray(single(D.top.hbias));\n end\n\n for mb=1:n_minibatches\n D.iteration.n_updates = D.iteration.n_updates + 1;\n\n v0 = patches((mb-1) * minibatch_sz + 1:min(mb * minibatch_sz, n_samples), :);\n mb_sz = size(v0,1);\n\n if use_gpu > 0\n v0 = gpuArray(single(v0));\n end\n\n % learning rate\n if D.learning.lrate_anneal > 0 && (step >= D.learning.lrate_anneal * n_epochs)\n anneal_counter = anneal_counter + 1;\n actual_lrate = actual_lrate0 / anneal_counter;\n else\n if D.learning.lrate0 > 0\n actual_lrate = D.learning.lrate / (1 + D.iteration.n_updates / D.learning.lrate0);\n else\n actual_lrate = D.learning.lrate;\n end\n actual_lrate0 = actual_lrate;\n end\n\n D.signals.lrates = [D.signals.lrates actual_lrate];\n\n % recognition (wake)\n h0r = cell(n_layers-1, 1);\n h0r{1} = v0;\n if D.learning.ffactored == 0\n h0r{1} = binornd(1, h0r{1});\n end\n\n for l = 2:(n_layers-1)\n h0r{l} = sigmoid(bsxfun(@plus, h0r{l-1} * D.rec.W{l-1}, D.rec.biases{l}'));\n if D.learning.ffactored == 0\n h0r{l} = binornd(1, h0r{l});\n end\n end\n\n r0 = cell(n_layers-1, 1);\n for l = 1:(n_layers-2)\n r0{l} = sigmoid(bsxfun(@plus, h0r{l+1} * D.gen.W{l}', D.gen.biases{l}'));\n end\n\n % update generative weight\n for l = 1:(n_layers-2)\n gen.W_grad{l} = ((h0r{l} - r0{l})' * h0r{l+1}) / size(v0, 1);\n gen.W_grad_old{l} = (1 - momentum) * gen.W_grad{l} + momentum * gen.W_grad_old{l};\n D.gen.W{l} = D.gen.W{l} + actual_lrate * (gen.W_grad_old{l} - D.learning.weight_decay * D.gen.W{l});\n\n gen.biases_grad{l} = mean(h0r{l} - r0{l}, 1);\n gen.biases_grad_old{l} = (1 - momentum) * gen.biases_grad{l} + momentum * gen.biases_grad_old{l};\n D.gen.biases{l} = D.gen.biases{l} + actual_lrate * (gen.biases_grad_old{l}' - D.learning.weight_decay * D.gen.biases{l});\n end\n\n % contrastive steps\n if D.learning.persistent_cd == 0 || D.iteration.n_updates == 1\n vtop = h0r{end};\n end\n for cs = 1:D.learning.contrastive_step\n htop = sigmoid(bsxfun(@plus, vtop * D.top.W, D.top.hbias'));\n htop = binornd(1, htop);\n vtop = sigmoid(bsxfun(@plus, htop * D.top.W', D.top.vbias'));\n vtop = binornd(1, vtop);\n end\n\n tv0 = h0r{end}; \n th0 = sigmoid(bsxfun(@plus, tv0 * D.top.W, D.top.hbias'));\n tv1 = vtop;\n th1 = sigmoid(bsxfun(@plus, tv1 * D.top.W, D.top.hbias'));\n\n top.W_grad = (tv0' * th0)/size(tv0,1) - (tv1' * th1)/size(tv1,1);\n top.vbias_grad = mean(tv0, 1) - mean(tv1, 1);\n top.hbias_grad = mean(th0, 1) - mean(th1, 1);\n\n top.W_grad_old = (1 - momentum) * top.W_grad + momentum * top.W_grad_old;\n top.vbias_grad_old = (1 - momentum) * top.vbias_grad' + momentum * top.vbias_grad_old;\n top.hbias_grad_old = (1 - momentum) * top.hbias_grad' + momentum * top.hbias_grad_old;\n\n D.top.W = D.top.W + actual_lrate * (top.W_grad_old - D.learning.weight_decay * D.top.W);\n D.top.vbias = D.top.vbias + actual_lrate * (top.vbias_grad_old - D.learning.weight_decay * D.top.vbias);\n D.top.hbias = D.top.hbias + actual_lrate * (top.hbias_grad_old - D.learning.weight_decay * D.top.hbias);\n \n % generation (sleep)\n h0r{n_layers-1} = tv1;\n for l = (n_layers-2):-1:1\n h0r{l} = sigmoid(bsxfun(@plus, h0r{l+1} * D.gen.W{l}', D.gen.biases{l}'));\n if D.learning.ffactored == 0\n h0r{l} = binornd(1, h0r{l});\n end\n end\n\n for l = 2:(n_layers - 1)\n r0{l} = sigmoid(bsxfun(@plus, h0r{l-1} * D.rec.W{l-1}, D.rec.biases{l}'));\n end\n\n % update recognition weight\n for l = 1:(n_layers-1)\n if l < n_layers - 1\n rec.W_grad{l} = (h0r{l}' * (h0r{l+1} - r0{l+1})) / size(h0r{1}, 1);\n rec.W_grad_old{l} = (1 - momentum) * rec.W_grad{l} + momentum * rec.W_grad_old{l};\n D.rec.W{l} = D.rec.W{l} + actual_lrate * (rec.W_grad_old{l} - D.learning.weight_decay * D.rec.W{l});\n end\n\n if l > 1\n rec.biases_grad{l} = mean(h0r{l} - r0{l}, 1);\n rec.biases_grad_old{l} = (1 - momentum) * rec.biases_grad{l} + momentum * rec.biases_grad_old{l};\n D.rec.biases{l} = D.rec.biases{l} + actual_lrate * (rec.biases_grad_old{l}' - D.learning.weight_decay * D.rec.biases{l});\n end\n end\n\n clear h0r r0 htop tv0 th0 tv1 th1; \n if D.learning.persistent_cd == 0\n clear vtop;\n end\n\n % compute reconstruction error\n hr = v0;\n for l = 2:n_layers-1\n hr = sigmoid(bsxfun(@plus, hr * D.rec.W{l-1}, D.rec.biases{l}'));\n end\n hr = sigmoid(bsxfun(@plus, hr * D.top.W, D.top.hbias'));\n hr = sigmoid(bsxfun(@plus, hr * D.top.W', D.top.vbias'));\n for l = n_layers-1:-1:2\n hr = sigmoid(bsxfun(@plus, hr * D.gen.W{l-1}', D.gen.biases{l-1}'));\n end\n \n rerr = mean(sum((v0 - hr).^2,2));\n if use_gpu > 0\n rerr = gather(rerr);\n end\n D.signals.recon_errors = [D.signals.recon_errors rerr];\n\n if D.verbose == 1\n fprintf(2, '.');\n end\n\n if use_gpu > 0\n clear v0 h0d h0e v0_clean vr hr deltae deltad \n end\n\n if D.stop.criterion > 0\n if D.stop.criterion == 1\n if min_recon_error > D.signals.recon_errors(end)\n min_recon_error = D.signals.recon_errors(end);\n min_recon_error_update_idx = D.iteration.n_updates;\n else\n if D.iteration.n_updates > min_recon_error_update_idx + D.stop.recon_error.tolerate_count \n fprintf(2, '\\nStopping criterion reached (recon error) %f > %f\\n', ...\n D.signals.recon_errors(end), min_recon_error);\n stopping = 1;\n break;\n end\n end\n else\n error ('Unknown stopping criterion %d', D.stop.criterion);\n end\n end\n\n if length(D.hook.per_update) > 1\n err = D.hook.per_update{1}(D, D.hook.per_update{2});\n\n if err == -1\n stopping = 1;\n break;\n end\n end\n \n if D.debug.do_display == 1 && mod(D.iteration.n_updates, D.debug.display_interval) == 0\n D.debug.display_function (D.debug.display_fid, D, v0, v1, h0, h1, W_grad, vbias_grad, hbias_grad);\n drawnow;\n end\n end\n\n if use_gpu > 0\n % pull\n for l = 1:n_layers-1\n if l < n_layers-1\n D.rec.W{l} = gather(D.rec.W{l});\n D.gen.W{l} = gather(D.gen.W{l});\n end\n D.rec.biases{l} = gather(D.rec.biases{l});\n D.gen.biases{l} = gather(D.gen.biases{l});\n end\n\n D.top.W = gather(D.top.W);\n D.top.vbias = gather(D.top.vbias);\n D.top.hbias = gather(D.top.hbias);\n end\n\n if length(D.hook.per_epoch) > 1\n err = D.hook.per_epoch{1}(D, D.hook.per_epoch{2});\n\n if err == -1\n stopping = 1;\n end\n end\n\n if stopping == 1\n break;\n end\n \n if D.verbose == 1\n fprintf(2, '\\n');\n end\n \n fprintf(2, 'Epoch %d/%d - recon_error: %f\\n', step, n_epochs, ...\n D.signals.recon_errors(end));\nend\n\nif use_gpu > 0\n % pull\n for l = 1:n_layers-1\n if l < n_layers-1\n D.rec.W{l} = gather(D.rec.W{l});\n D.gen.W{l} = gather(D.gen.W{l});\n end\n D.rec.biases{l} = gather(D.rec.biases{l});\n D.gen.biases{l} = gather(D.gen.biases{l});\n end\n\n D.top.W = gather(D.top.W);\n D.top.vbias = gather(D.top.vbias);\n D.top.hbias = gather(D.top.hbias);\nend\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/dbn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3568358405454589}} {"text": "function gammaM = gammaScan3d(doseArray1, doseArray2, deltaXYZv, doseAgreement, distAgreement, maxDistance)\n% function gammaM = gammaScan3d(doseArray1, doseArray2, deltaXYZv, doseAgreement, distAgreement, maxDistance)\n%\n% APA, 04/27/2012\n\ndeltaX = deltaXYZv(1);\ndeltaY = deltaXYZv(1);\ndeltaZ = deltaXYZv(1);\nincrementRadius = min([deltaX deltaY deltaZ]);\n\n% Initial gamma\ngammaM = ((doseArray1-doseArray2).^2).^0.5/doseAgreement;\nconvergedM = false(size(gammaM));\n\n% Calculate until 4 times the permissible distance to agreement.\nif ~exist('maxDistance', 'var')\n maxDistance = distAgreement*1.5;\nend\nouterRadiusV = incrementRadius:incrementRadius:maxDistance;\nnumIters = length(outerRadiusV);\n\nsiz = size(gammaM);\nminDoseDiffM = zeros(siz,'single');\nmaxDoseDiffM = minDoseDiffM;\n\n% convergenceCountM = zeros(siz,'uint8');\n\n% Update waitbar on gamma GUI\ngammaGUIFig = findobj('tag','CERRgammaInputGUI');\nif ~isempty(gammaGUIFig)\n ud = get(gammaGUIFig,'userdata');\n set(ud.wb.patch,'xData',[0 0 0 0])\nend\n\nfor radNum = 1:numIters\n \n disp(['--- Gamma Calculation Iteraion ', num2str(radNum), ' ----']) \n \n % Create an ellipsoid ring neighborhood\n outerRadius = outerRadiusV(radNum); \n \n rowOutV = floor(outerRadius/deltaY);\n colOutV = floor(outerRadius/deltaX);\n slcOutV = floor(outerRadius/deltaZ);\n \n NHOOD_outer = createEllipsoidNHOOD(1:rowOutV,1:colOutV,1:slcOutV);\n \n % Compute Min and Max for the ellipsoid neighborhood\n [minLocalM, maxLocalM] = getMinMaxIM(doseArray2,NHOOD_outer);\n \n % Compute difference between dose1 and (min,max) for dose2\n minDoseDiffM(~convergedM) = doseArray1(~convergedM) - minLocalM(~convergedM) + doseAgreement; % D1-(min(D2)-5)\n maxDoseDiffM(~convergedM) = maxLocalM(~convergedM) + doseAgreement - doseArray1(~convergedM); % (max(D2)+5)-D1\n \n % If dose1 is contained within (min,max) for dose2, then it converged!\n newConvergedM = ~convergedM & minDoseDiffM >= 0 & maxDoseDiffM >= 0;\n \n % Compute gamma for voxels that converged\n %gammaM(newConvergedM) = min(gammaM(newConvergedM), outerRadius/distAgreement);\n gammaM(newConvergedM) = outerRadius;\n \n % Add newly converged voxels to the list\n convergedM = convergedM | newConvergedM; \n \n % Compute gamma for voxels that have not yet converged\n %gammaForNotConvergedM = (min((minDoseDiffM(~convergedM)-doseAgreement).^2, (maxDoseDiffM(~convergedM)-doseAgreement).^2)./doseAgreement^2 + (outerRadius/distAgreement)^2).^0.5;\n %gammaM(~convergedM) = min(gammaM(~convergedM), gammaForNotConvergedM);\n \n % If gamma is less or equal to outerRadius/distAgreement, then the voxel conveged!\n %convergedM(~convergedM) = gammaM(~convergedM) <= outerRadius/distAgreement;\n \n \n if ~isempty(gammaGUIFig)\n set(ud.wb.patch,'xData',[0 0 radNum/numIters radNum/numIters])\n drawnow\n end\n \n if all(convergedM(:))\n disp('All converged!!!')\n if ~isempty(gammaGUIFig)\n set(ud.wb.patch,'xData',[0 0 1 1])\n end\n break\n end\n \nend\n\ngammaM(~convergedM) = NaN;\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/Utilities/gammaScan3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.35677255572160593}} {"text": "function [beta_gibbs, sigma_gibbs, theta_gibbs, ss_record,indH,beta_theta_gibbs]=TVEmagibbs(data_endo,It,Bu,beta0,omega0,psi0,lambda0,Y,X,n,T,k1,q1,p,regimeperiods,names,TVEH)\n\n\n% function [beta_gibbs psi_gibbs sigma_gibbs ss_record delta_gibbs]=magibbs(data_endo,data_exo,It,Bu,beta0,omega0,psi0,lambda0,Y,X,Z,n,m,T,k1,k3,q1,q2,q3,p)\n% performs the Gibbs algortihm 3.5.1 for a MABVAR model, and returns draws from posterior distribution\n% inputs: - matrix 'data_endo': the matrix storing the endogenous time series data used to estimate the model\n% - matrix 'data_exo': the matrix storing the exogenous time series data used to estimate the model \n% - integer 'It': the total number of iterations run by the Gibbs sampler\n% - integer 'Bu': the number of initial iterations discared as burn-in sample\n% - vector 'beta0': the vector containing the mean of the prior distribution for beta, defined in (3.5.17)\n% - matrix 'omega0': the variance-covariance matrix for the prior distribution of beta, defined in (3.5.17)\n% - vector 'psi0': the vector containing the mean of the prior distribution for psi, defined in (3.5.19)\n% - matrix 'lambda0': the variance-covariance matrix for the prior distribution of psi, defined in (3.5.19)\n% - matrix 'Y': the matrix of endogenous variables, defined in (3.5.10)\n% - matrix 'X': the matrix of endogenous regressors, defined in (3.5.10)\n% - matrix 'Z': the matrix of exogenous regressors, defined in (3.5.10)\n% - integer 'n': the number of endogenous variables in the model\n% - integer 'm': the number of exogenous variables in the model\n% - integer 'T': the sample size, i.e. the number of time periods used to estimate the model\n% - integer 'k1': the number of coefficients related to the endogenous variables for each equation in the model\n% - integer 'k3': the number of coefficients related to the exogenous variables for each equation, in the reformulated model (3.5.5)\n% - integer 'q1': the total number of VAR coefficients related to the endogenous variables\n% - integer 'q2': the total number of VAR coefficients related to the exogenous variables\n% - integer 'q3': the total number of VAR coefficients related to the exogenous variables, in the reformulated model (3.5.5)\n% - integer 'p': the number of lags in the model\n% outputs: - matrix 'beta_gibbs': the matrix recording the post-burn draws of beta\n% - matrix 'psi_gibbs': the matrix recording the post-burn draws of psi\n% - matrix 'sigma_gibbs': the matrix recording the post-burn draws of sigma\n% - matrix 'delta_gibbs': the matrix recording the post-burn draws of delta\n% - cell 'ss_record': the cell storing the post-burn steady-state values\n\n\n\n% this function implements algorithm...\n\n\n% preliminary tasks\n\n% take the alternative exogenous regime\nif isempty(regimeperiods)\n data_exo=[ones(size(data_endo,1),1)];\nelse\ndata_exo=[ones(size(data_endo,1),1) zeros(size(data_endo,1),1)];\ndata_exo(find(strcmp(names(2:end,1),regimeperiods(1))):find(strcmp(names(2:end,1),regimeperiods(2))),2)=1;\ndata_exo(find(strcmp(names(2:end,1),regimeperiods(1))):find(strcmp(names(2:end,1),regimeperiods(2))),1)=0;\nend\n\nindH=zeros(T+p,1);\nfor iR=1:size(data_exo,2)\n indH(data_exo(:,iR)==1)=iR;\nend\n\n% create the cell that will store the records for the steady-state\nss_record=cell(n,1); %change\n\n% invert omega0\ninvomega0=diag(1./diag(omega0));\n\n% invert lambda0\ninvlambda0=lambda0\\eye(length(lambda0));\n\n% step 2: set initial values\n% set initial values for B, beta and sigma; as no OLS estimates are available, simply set the value as zeros for B and beta, and identity for sigma\nB=zeros(k1,n);\n\n% define the initial value for the inverse of sigma: beacause sigma is identity, this is also identity\ninvsigma=eye(n);\n\n% preallocate space for the matrix with the equilibrium values\neq=zeros(T+p,n);\n\nq2=length(psi0);\n\nhbar = bear.parfor_progressbar(It,'Progress of the Gibbs sampler'); %create the progress bar\n\n\n% start iterations\nfor ii=1:It\n\nhbar.iterate(1); % update progress by one iteration\n\n\n% step 3: at iteration ii, draw psi from N, conditional on beta and sigma\n% obtain the lambdabar matrix\nYbar=Y-X*B;\nYpsi=bear.vec(Ybar');\n\nt=1;\nFsimple=TVEH(:,:,indH(t+p),t+p);\nfor k=2:p+1\n Fsimple=Fsimple-B((k-2)*n+1:(k-1)*n,:)'*TVEH(:,:,indH(t+p-(k-1)),t+p-(k-1));\nend\n\nfor t=2:T\n Ftemp=TVEH(:,:,indH(t+p),t+p);\n for k=2:p+1\n Ftemp=Ftemp-B((k-2)*n+1:(k-1)*n,:)'*TVEH(:,:,indH(t+p-(k-1)),t+p-(k-1));\n end\n Fsimple=cat(1,Fsimple,Ftemp);\nend\n\ninvOmega=kron(eye(T),invsigma);\n\n\nCT=(invlambda0+Fsimple'*invOmega*Fsimple)\\eye(length(lambda0));\nmT=CT*(Fsimple'*invOmega*Ypsi++invlambda0*psi0);\n\n% draw from N(psibar,lambdabar);\ntheta=mT+chol(bear.nspd(CT),'lower')*randn(q2,1);\n\n% recover equilibrium values from psi\nfor it=1:T+p\n eq(it,:)=(squeeze(TVEH(:,:,indH(it),it))*theta)'; % compute the equilibrium values given theta\nend\n\n% step 4: now that psi/F has been drawn, it is possible to generate Yhat, Xhat and yhat\ntemp2=data_endo-eq;\ntemp3=bear.lagx(temp2,p);\nYhat=temp3(:,1:n);\nyhat=Yhat(:);\nXhat=temp3(:,n+1:end);\n\n\n% step 5: next, at iteration ii, draw sigma from IW, conditional on most recent draw for psi and beta\n% obtain first Stilde\nStilde=(Yhat-Xhat*B)'*(Yhat-Xhat*B);\n% next draw from IW(Stilde,T)\nsigma=bear.iwdraw(Stilde,T);\n% invert sigma\nC=bear.trns(chol(bear.nspd(sigma),'Lower'));\ninvC=C\\speye(n);\ninvsigma=invC*invC';\n\n\n\n% step 6: finally, at iteration ii, draw beta from a N, conditional on most recent draw for psi and sigma\n% first obtain the omegabar matrix\ninvomegabar=invomega0+kron(invsigma,Xhat'*Xhat);\nC=bear.trns(chol(bear.nspd(invomegabar),'Lower'));\ninvC=C\\speye(q1);\nomegabar=invC*invC';\n% following, obtain betabar\nbetabar=omegabar*(invomega0*beta0+kron(invsigma,Xhat')*yhat);\n% draw from N(betabar,omegabar);\nbeta=betabar+chol(bear.nspd(omegabar),'lower')*randn(q1,1);\n% reshape to obtain B\nB=reshape(beta,k1,n);\n% update U, using the draw obtained for B\n\n % record the values if the number of burn-in iterations is exceeded\n if ii>Bu\n % record the value of beta\n beta_gibbs(:,ii-Bu)=beta;\n % record the value of sigma (in vectorized form)\n sigma_gibbs(:,ii-Bu)=sigma(:);\n \n % compute and record the steady-state \n ss=eq;\n % trim p initial conditions to be consistent with the sample\n ss=ss(p+1:end,:);\n % then record in the corresponding cell\n for jj=1:n\n ss_record{jj,1}(ii-Bu,:)=ss(:,jj)';\n end\n % finally, record theta\n theta_gibbs(:,ii-Bu)=theta;\n \n beta_theta_gibbs(:,ii-Bu)=[beta;theta];\n % if current iteration is still a burn iteration, do not record the result\n else\n end\n\n% step 7: go for next iteration\nend\n\nclose(hbar); %close progress bar\n\n", "meta": {"author": "european-central-bank", "repo": "BEAR-toolbox", "sha": "f33aae80c40f7a2e78a54de99b2ce3663f59aa75", "save_path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox", "path": "github-repos/MATLAB/european-central-bank-BEAR-toolbox/BEAR-toolbox-f33aae80c40f7a2e78a54de99b2ce3663f59aa75/tbx/bear/+bear/TVEmagibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.35676532347248396}} {"text": "function T=findDartboardSubarrays(aperFracs,subarraysPerRing,angShifts,xyPoints)\n%%FINDDARTBOARDSUBARRAYS When designing subarrays for a circular aperture,\n% it is noted in [1] that a dartboard pattern tends to work pretty\n% well. It is also suggested that a subarray pattern returned by\n% findBaylissSubarrays be used as a rule of thumb for choosing how\n% many rings and the number of subarrays per ring in the\n% dartboard. When given the positions of elements in a \n%\n%INPUTS: aperFracs A numRingsX1 or 1XnumRings vector sorted in increasing\n% order where aperFrac(i) is the fraction of the aperture\n% size where the ring specified ends. aperFrac(end) must\n% equal 1 (100% of the aperture size). The aperture width\n% is taken to be the maximum distance of a point in\n% xyPoints from the origin.\n% subarraysPerRing A numRingsX1 or 1XnumRings vector indicating the number\n% of subarrays in each ring. These must be positive\n% integers.\n% angShifts A numRingsX1 or 1XnumRings vector giving angular offsets\n% in radians by which the first subarray in each ring\n% begins. This is here to keep the rings from all lining\n% up, which should improve how the grating lobes of the\n% subarrays line up. If an empty matrix is passed, then\n% angular shifts of zero are used.\n% xyPoints A 2XnumPoints set of numPoints points in the aperture\n% plane corresponding to element positions. The points\n% should be shifted such that the center of the aperture\n% is the origin. The width of the aperture is the maximum\n% distance of any point from the center.\n%\n%OUTPUTS: T A numSubarraysXnumPoints boolean matrix (a matrix such that\n% T(i,:) is a set of boolean values indicating which elements are\n% in each subarray). The subarrays do not overlap.\n%\n%EXAMPLE:\n%Here, we lay out the elements for a circular array and then we break them\n%into a dartboard configuration. We then display the elements with\n%different symbols and colors for the subarrays.\n% %First, we create a circular array. The element locations are given in\n% %terms of the wavelength lambda, so lambda will not appear in the\n% %equations for the sum beam.\n% xyVals=getShaped2DLattice([49;49],'circular');\n% \n% aperFracs=[1/5;2/5;3/5;4/5;1];\n% subarraysPerRing=[4;4;8;8;8];\n% degShifts=[0;2*pi/(2*4);0;2*pi/(2*8);0];\n% T=findDartboardSubarrays(aperFracs,subarraysPerRing,degShifts,xyVals);\n% \n% figure()\n% clf\n% hold on\n% axis square\n% numSubarrays=size(T,1);\n% dispOpts={'.b','.g','.m','.c','.y','.k','.b','.r',...\n% 'xm','xc','xy','xk','xb','xr','xb','xg',...\n% 'ob','og','om','oc','oy','ok','ob','or'...\n% '+m','+c','+m','+y','+k','+r','+b','+g'...\n% 'sb','sg','sm','sc','sm','sy','sk','sr'};\n% for curSubarray=1:numSubarrays\n% points=xyVals(:,T(curSubarray,:)==1);\n% optVal=mod(curSubarray,length(dispOpts))+1;\n% scatter(points(1,:),points(2,:),dispOpts{optVal},'linewidth',2);\n% end\n% h1=xlabel('x');\n% h2=ylabel('y');\n% title('Coloring Represents Subarrays')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] U. Nickel, \"Subarray configurations for digital beamforming with\n% low sidelobes, adaptive interference suppression and superresolution,\"\n% 1995, FFM-Report (available from Fraunhofer FKIE, Wachtberg, Germany).\n%\n%September 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumRings=length(aperFracs);\nnumSubarrays=sum(subarraysPerRing);\nnumEls=size(xyPoints,2);\n\nif(aperFracs(numRings)~=1)\n error('The last element in aperFracs must be one');\nend\n\nif(isempty(angShifts))\n angShifts=zeros(numRings,1);\nend\n\n%The maximum squared distance from the origin to a point is taken to be the\n%radius of the aperture squared.\na=sqrt(max(sum(xyPoints.^2,1)));\n\ntemp=cumsum(subarraysPerRing(:));\nnumSubsInPriorRings=[0;temp(1:(numRings-1))];\n\nT=false(numSubarrays,numEls);\nfor curEl=1:numEls\n %The fractional distance from the outer edge of the aperture where the\n %element is located.\n fracCur=norm(xyPoints(:,curEl))/a;\n \n %Determine which ring the element is in.\n [~, ringIdx]=binSearch(aperFracs,fracCur,2);\n \n %Each ring can have multiple subarrays. The subarrays are uniformly\n %spaced in angle, but the starting angle is not taken to be zero but\n %rather degShifts(ringIdx) radians.\n angle=atan2(xyPoints(2,curEl),xyPoints(1,curEl));\n \n subArrayWidth=2*pi/subarraysPerRing(ringIdx);\n \n subArrayInRing=fix(wrapRange(angle+angShifts(ringIdx),0,2*pi)/subArrayWidth)+1;\n subArrayIdx=numSubsInPriorRings(ringIdx)+subArrayInRing;\n T(subArrayIdx,curEl)=1;\nend\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/Mathematical_Functions/Signal_Processing/Array_Processing/Subarrays/findDartboardSubarrays.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3563418469189839}} {"text": "function [result]=sv_NodeCalc(mCatalog, fSplitTime, bTimePeriod, fTimePeriod, nCalculateMC, vCluster, bDecluster, fMcOrg, fBValueOrg, bSeisModel)\n% function [result]=sv_NodeCalc(mCatalog, fSplitTime, bTimeperiod, fTimePeriod, nCalculateMC, vCluster, bDecluster, fMcOrg, fBValueOrg, bSeisModel)\n% -------------------------------------------------------------------------------------------------------------------------------------------------\n% Function to calculate absolute difference of number of events between\n% to time periods of an earthquake catalog normalized to a year\n% Incoming variables:\n% mCatalog : current earthquake catalog\n% fSplitTime : Splitting time\n% bTimePeriod : Use specific time period to compare (1) or from beginning till end of catalog (0)\n% fTimePeriod : Time period in days to be compared before and after fSplitTime\n% nCalculateMC : Number for Method of Mc determination\n% vCluster : Vector of cluster numbers\n% bDecluster : Decluster catalog or not\n% fMcOrg : Mc of entire catalog\n% fBValueOrg : b-value of entire catalog\n% bSeisModel : Method to model seismicity varation: 0 - b-value fittng, 1 - grid search\n%\n% Outgoing variable:\n% result.dNdiffsum : total difference of number of events in the two time periods\n% result.fMc : magnitude of completeness for entire catalog\n% result.fMcFirstPeriod : magnitude of completeness for first period defined\n% result.fMcSecondPeriod : magnitude of completeness for second period defined\n% result.fdMc : Difference in Mc: Mc(Per1)-Mc(Per2)\n% result.fMshift : Simple magnitude shift\n% result.fMshiftFit : Goodness of fit in percent to modeling second period with simple magnitude shift of first period\n% result.fMshiftSig : Simple magnitude shift at 99% significance level of z-statistic\n% result.fFactorHi : Mean rate factor for EQ >= Mc(Per1) between two periods\n% result.fPerHi : Percental seismicity change\n% result.fFactorLow : Mean rate factor for EQ < Mc(Per1) between two periods\n% result.fPerLow : Percental seismicity change\n% result.fMRateFit : Goodness of fit by modeling second period with rate factor multiplication of first period\n% result.fMshiftCom : Magnitude shift combined with stretch\n% result.fStretch : Magnitude stretch\n% result.fMTransFit : Goodness of fit by modeling second period manipulating the first period\n% result.fdMag : Magnitude shift for a M=1 EQ using result.fMshiftCom and result.fStretch\n% result.mModelCat : Magnitude alternation for a magnitude M=1 EQ\n%\n% Author: J. Woessner\n% woessner@seismo.ifg.ethz.ch\n% last update: 01.11.02\n% Changes:\n% 19.08.02: Replaced fcumulsum.m with calc_cumulsum.m\n% 08.10.02: Deleted return at the end.\n\n\n% Changes:\n% 19.08.02: Replaced fcumulsum.m with calc_cumulsum.m\n% 08.10.02: Deleted return at the end.\n\n% Init variable\nresult=[];\nfTimePeriod =fTimePeriod/365;\n\nif bDecluster == 1\n % Determine degree of Poissonian distribution using Chi^2-Test\n [result.fChi2 result.fChi2_sig90 result.fChi2_sig95 result.Chi2_sig99 result.nPoissDeg]= calc_Chi2(mCatalog);\n vSel = (vCluster(:,1) > 0);\n mCatalogDecl = mCatalog(~vSel,:);\n [result.fChi2_Dec result.fChi2_sig90_Dec result.fChi2_sig95_Dec result.Chi2_sig99_Dec...\n result.nPoissDeg_Dec]= calc_Chi2(mCatalogDecl);\n % Determine degree of Clustering\n [result.fClusterDeg] = calc_ClusterDeg(mCatalog, vCluster);\nelseif (bSeisModel == 1)\n % Create the catalogs for the two time peiods\n [result.mFirstCatalog, result.mSecondCatalog, result.fFirstPeriodExact, result.fSecondPeriodExact, result.fFirstPeriod,...\n result.fSecondPeriod] = ex_SplitCatalog(mCatalog, fSplitTime, bTimePeriod, fTimePeriod, bTimePeriod, fTimePeriod);\n\n %% Determination of difference between two time periods normalized to year\n [dEv_val dMags dEv_valsum dEv_valsum_rev, dMags_rev] = calc_cumulsum(result.mFirstCatalog);\n [dEv_val2 dMags2 dEv_valsum2 dEv_valsum_rev2, dMags_rev2] = calc_cumulsum(result.mSecondCatalog);\n result.dNdiff = max(dEv_val2)/result.fSecondPeriodExact-max(dEv_val)/result.fFirstPeriodExact; % Normalization\n result.dNdiffsum = cumsum(result.dNdiff');\n %result.dNdiffsumVal = result.dNdiffsum(length(result.dNdiffsum));\n\n % Determine Mc for entire catalog, two time periods and difference in Mc\n result.fMc = calc_Mc(mCatalog, nCalculateMC);\n if isempty(result.fMc)\n result.fMc = NaN;\n end\n result.fMcFirstPeriod = calc_Mc(result.mFirstCatalog, nCalculateMC);\n if isempty(result.fMcFirstPeriod)\n result.fMcFirstPeriod = NaN;\n end\n result.fMcSecondPeriod = calc_Mc(result.mSecondCatalog, nCalculateMC);\n if isempty(result.fMcSecondPeriod)\n result.fMcSecondPeriod = NaN;\n end\n result.fdMc = result.fMcSecondPeriod - result.fMcFirstPeriod;\n\n % Determine simple magnitude shift and Goodness of Fit\n [result.fMshift result.fMshiftFit] = calc_Magshift(mCatalog, fSplitTime, bTimePeriod, fTimePeriod, nCalculateMC);\n if isempty(result.fMshift)\n result.fMshift = NaN;\n result.fMshiftFit = NaN;\n end\n % Determine significant Mshift at 99% level\n [mLMagsig mHMagsig fLZmax fLZmean fLZmin fHZmax fHZmean, fHZmin] =...\n calc_Magsig(result.mFirstCatalog, result.mSecondCatalog , result.fFirstPeriodExact, result.fSecondPeriodExact, 0.1);\n if ((fLZmax >= 2.57 & fHZmin <= -2.57) | fLZmin <= -2.57 & fHZmax >= 2.57)\n result.fMshiftSig = result.fMshift;\n else\n result.fMshiftSig = NaN;\n end\n % Determine rate factors and percentage change of EQ for M=Mc\n [result.fFactorHi fStdHi fResHi result.fPerHi result.fFactorLow fStdLow fResLow result.fPerLow result.fMRateFit]...\n = calc_ratefac(result.mFirstCatalog, result.mSecondCatalog, fTimePeriod, fTimePeriod,...\n result.fMcFirstPeriod, result.fMcSecondPeriod);\n [result.fMshiftCom result.fStretch result.fMTransFit result.fARate] = calc_Shiftstretch(mCatalog, fSplitTime, bTimePeriod,...\n fTimePeriod, nCalculateMC, fMcOrg, fBValueOrg);\n %% Magnitude fit for a magnitude M=1 EQ\n result.fdMag = 1+((result.fStretch-1)+result.fMshiftCom); % Theoretical map\n result.mModelCat = result.mFirstCatalog;\n result.mModelCat(:,6) = result.fStretch.*result.mModelCat(:,6)+result.fMshiftCom;\nelse\n % Create the catalogs for the two time peiods\n [result.mFirstCatalog, result.mSecondCatalog, result.fFirstPeriodExact, result.fSecondPeriodExact, result.fFirstPeriod,...\n result.fSecondPeriod] = ex_SplitCatalog(mCatalog, fSplitTime, bTimePeriod, fTimePeriod, bTimePeriod, fTimePeriod);\n\n %% Determination of difference between two time periods normalized to year\n [dEv_val dMags dEv_valsum dEv_valsum_rev, dMags_rev] = calc_cumulsum(result.mFirstCatalog);\n [dEv_val2 dMags2 dEv_valsum2 dEv_valsum_rev2, dMags_rev2] = calc_cumulsum(result.mSecondCatalog);\n% result.dNdiff = max(dEv_val2)/result.fSecondPeriodExact-max(dEv_val)/result.fFirstPeriodExact; % Normalization\n result.dNdiff = max(dEv_valsum2)/result.fSecondPeriodExact-max(dEv_valsum)/result.fFirstPeriodExact;\n result.dNdiffsum = max(cumsum(result.dNdiff'));\n %result.dNdiffsumVal = result.dNdiffsum(length(result.dNdiffsum));\n if isempty(result.dNdiff)\n result.dNdiff = NaN;\n end\n if isempty(result.dNdiffsum)\n result.dNdiffsum = NaN;\n end\n % Determine Mc for entire catalog, two time periods and difference in Mc\n result.fMc = calc_Mc(mCatalog, nCalculateMC);\n if isempty(result.fMc)\n result.fMc = NaN;\n end\n result.fMcFirstPeriod = calc_Mc(result.mFirstCatalog, nCalculateMC);\n if isempty(result.fMcFirstPeriod)\n result.fMcFirstPeriod = NaN;\n end\n result.fMcSecondPeriod = calc_Mc(result.mSecondCatalog, nCalculateMC);\n if isempty(result.fMcSecondPeriod)\n result.fMcSecondPeriod = NaN;\n end\n result.fdMc = result.fMcSecondPeriod - result.fMcFirstPeriod;\n\n % Mc determination by grid search\n %[result.fProbMcGrid result.fMcGrid] = calc_McGridN(mCatalog,0.1);\n [result.fProbMcGrid result.fMcGrid] = calc_McCdf2(mCatalog,0.1)\n if (isempty(result.fProbMcGrid) | isempty(result.fMcGrid))\n result.fProbMcGrid = NaN;\n result.fMcGrid = NaN;\n end\n %% Use data only above completeness\n %fMinMc = min([result.fMcFirstPeriod result.fMcSecondPeriod]);\n % vSel1 = (result.mFirstCatalog(:,6) >= result.fMcFirstPeriod);\n % vSel2 = (result.mSecondCatalog(:,6) >= result.fMcFirstPeriod);\n % result.mFirstCatalog = result.mFirstCatalog(vSel1,:);\n % result.mSecondCatalog = result.mSecondCatalog(vSel2,:);\n\n %% Seismicity variation modelling\n %!!!!! NO MODELS WITH STRETCH ALLOWED !!!!!!!!!!!!!!!!!!!!!!!!!\n %%% Maximum likelihood scores and BICs\n [fProb_nochange, fBic_nochange] = calc_loglikelihood_nochange2(result.mFirstCatalog, result.mSecondCatalog);\n [fdM, fProb_dM, fBic_dM, mLikeli_dM] = calc_loglikelihood_dM2(result.mFirstCatalog, result.mSecondCatalog);\n %[fS, fProb_stretch, fBic_stretch, mLikeli_dS] = calc_loglikelihood_stretch(result.mFirstCatalog, result.mSecondCatalog);\n [fFac, fProb_Rate, fBic_Rate, mLikeli_Rate] = calc_loglikelihood_rate2(result.mFirstCatalog, result.mSecondCatalog);\n [fdM_rate, fdM_Fac, fProb_dMrate, fBic_dMrate, mLikeli_dMrate] = calc_loglikelihood_dM_rate2(result.mFirstCatalog, result.mSecondCatalog);\n %[fdS_rate, fdS_Fac, fProb_dSrate, fBic_dSrate mLikeli_dSrate] = calc_loglikelihood_stretch_rate(result.mFirstCatalog, result.mSecondCatalog);\n %[fdM_st, fStretch, fProb_Trans, fBic_Trans, mLikeli_Trans] = calc_loglikelihood_Trans(result.mFirstCatalog, result.mSecondCatalog);\n %[fdM_all, fdS_all, fFac_all, fProb_all, fBic_all, mLikeli_all] = calc_loglikelihood_dMdSrate(result.mFirstCatalog, result.mSecondCatalog);\n\n\n %vBic = [fBic_nochange; fBic_dM; fBic_stretch; fBic_Rate; fBic_dMrate; fBic_Trans; fBic_dSrate; fBic_all];\n vBic = [fBic_nochange; fBic_dM; fBic_Rate; fBic_dMrate];\n [result.nType] = find(vBic == min(vBic));\n %% Initialize result\n result.fdM = nan; % Shift\n result.fdS = nan; % Stretch\n result.fRf = nan; % rate factor\n if length(result.nType) > 1\n vBic;\n result.nModelChoice = NaN;\n elseif length(result.nType) == 0\n result.nModelChoice = nan;\n else\n switch result.nType\n case 1\n result.nModelChoice = 1;\n % result.fdM = 0; % Shift\n % result.fdS = 1; % Stretch\n % result.fRf = 1; % rate factor\n case 2\n result.nModelChoice = 2;\n result.fdM = fdM;\n% case 3\n% result.nModelChoice = 3;\n% result.fdS = fS;\n case 3\n result.nModelChoice = 3;\n result.fRf = fFac;\n case 4\n result.nModelChoice = 4;\n result.fdM = fdM_rate;\n result.fRf = fdM_Fac;\n% case 6\n% result.nModelChoice = 6;\n% result.fdM = fdM_st;\n% result.fdS = fStretch;\n% case 7\n% result.nModelChoice = 7;\n% result.fdS = fdS_rate;\n% result.fRf = fdS_Fac;\n% case 8\n% result.nModelChoice = 8;\n% result.fdM = fdM_all;\n% result.fdS = fdS_all;\n% result.fRf = fFac_all;\n otherwise\n disp('Something is equal');\n end; % END of Switch result.Type\n end;% END of IF result.Type\nend; % END of IF bSeismodel\nend % End of IF bDecluster\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_NodeCalc3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.35625111880410126}} {"text": "function p_data = p01_data ( dim_num, data_num )\n\n%*****************************************************************************80\n%\n%% P01_DATA returns the data for problem p01.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension of the dependent\n% variables.\n%\n% Input, integer DATA_NUM, the number of data points.\n%\n% Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n%\n p_data = [ ...\n 0.0, 4.0; ...\n 1.0, 5.0; ...\n 2.0, 6.0; ...\n 4.0, 6.0; ...\n 5.0, 5.0; ...\n 6.0, 3.0; ...\n 7.0, 1.0; ...\n 8.0, 1.0; ...\n 9.0, 1.0; ...\n 10.0, 3.0; ...\n 11.0, 4.0; ...\n 12.0, 4.0; ...\n 13.0, 3.0; ...\n 14.0, 3.0; ...\n 15.0, 4.0; ...\n 16.0, 4.0; ...\n 17.0, 3.0; ...\n 18.0, 0.0 ]';\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/test_interp/p01_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.35612055869395415}} {"text": "function [energy3M,entropy3M,sumAvg3M,corr3M,invDiffMom3M,contrast3M,...\n clustShade3M,clustPromin3M,haralCorr3M] = textureByPatchAllOffsFromCtr(scanArray3M, nL, ...\n patchSizeV, flagv, hWait, minIntensity, maxIntensity)\n% function [energy3M,entropy3M,sumAvg3M,corr3M,invDiffMom3M,contrast3M,...\n% clustShade3M,clustPromin3M,haralCorr3M] = textureByPatchAllOffsFromCtr(scanArray3M, nL, ...\n% patchSizeV, flagv, hWait, minIntensity, maxIntensity)\n%\n% This function calculates GLCM texture from patches w.r.t. their centers.\n%\n% INPUTS:\n% scanArray3M - Scan matrix with NaN values for voxels that are not to be\n% included in texture calculation.\n% nL - Number of gray levels\n% patchSizeV - 3-element vector for the patch radius. For example, [3 3 0]\n% flagv - 9-element vector of booleans to toggle calculation of texture features.\n% hWait - (optional) waitbar handle. Use NaN to turn off waitbar.\n% minIntensity - (optional) minimum intensity for discretization.\n% maxIntensity - (optional) maximum intensity for discretization.\n%\n% Example:\n% scan3M(~mask3M) = NaN;\n% flagV = zeros(1,9);\n% flagV(2) = 1; % entropy only\n% nL = 64;\n% patchSizeV = [3 3 0];\n% [~,entropy3M] = textureByPatchAllOffsFromCtr(scan3M, nL, ...\n% patchSizeV, offsetsM, flagV);\n%\n% APA, 11/07/2018\n\n% Generate flags\nif ~exist('flagv','var')\n flagv = ones(1,9);\nelseif exist('flagv','var') && isempty(flagv)\n flagv = ones(1,9);\nend\n\n% Flag to draw waitbar\nwaitbarFlag = 0;\nif exist('hWait','var') && ishandle(hWait)\n waitbarFlag = 1;\nend\n\n% Get indices of non-NaN voxels\ncalcIndM = ~isnan(scanArray3M);\n\nslcWindow = 2 * patchSizeV(3) + 1;\nrowWindow = 2 * patchSizeV(1) + 1;\ncolWindow = 2 * patchSizeV(2) + 1;\n\n% Build distance matrices\nnumColsPad = floor(colWindow/2);\nnumRowsPad = floor(rowWindow/2);\nnumSlcsPad = floor(slcWindow/2);\n\n% Get number of voxels per slice\n[numRows, numCols, numSlices] = size(scanArray3M);\nnumVoxels = numRows*numCols;\n\n% Quantize the image\nif exist('minIntensity','var') && exist('maxIntensity','var')\n q = imquantize_cerr(scanArray3M,nL,minIntensity,maxIntensity);\nelse\n q = imquantize_cerr(scanArray3M,nL);\nend\n\n% Pad q, so that sliding window works also for the edge voxels\n%scanArrayTmp3M = padarray(scanArray3M,[numRowsPad numColsPad\n%numSlcsPad],NaN,'both'); % aa commented\nif exist('padarray.m','file')\n q = padarray(q,[numRowsPad numColsPad numSlcsPad],NaN,'both');\nelse\n q = padarray_oct(q,[numRowsPad numColsPad numSlcsPad],NaN,'both');\nend\n\nnanFlag = 0; % the quantized image is always padded with NaN. Hence, always,\n% nanFlag = 1.\nif any(isnan(q(:)))\n nanFlag = 1;\n q(isnan(q)) = nL+1;\nend\nlq = nL + 1;\n\nq = uint16(q); % q is the quantized image\n\n% Create indices for 2D blocks\n[m,n,~] = size(q);\nm = uint32(m);\nn = uint32(n);\ncolWindow = uint32(colWindow);\nrowWindow = uint32(rowWindow);\nslcWindow = uint32(slcWindow);\n\n% Index calculation adapted from\n% http://stackoverflow.com/questions/25449279/efficient-implementation-of-im2col-and-col2im\n\n% Start indices for each block\nstart_ind = reshape(bsxfun(@plus,[1:m-rowWindow+1]',[0:n-colWindow]*m),[],1);\n\n% Row indices\nlin_row = permute(bsxfun(@plus,start_ind,[0:rowWindow-1])',[1 3 2]);\n\n% Get linear indices based on row and col indices and get desired output\nindM = reshape(bsxfun(@plus,lin_row,(0:colWindow-1)*m),rowWindow*colWindow,[]);\n\n% Indices of last level to filter out\nnanIndV = false([lq*lq,1]);\nif nanFlag\n nanIndV([lq:lq:lq*lq-lq, lq*lq-lq:lq*lq]) = true;\nend\n\n% Build levels vector for mu, sig\nlevRowV = repmat(1:lq,[1 lq]);\nlevColV = repmat(1:lq,[lq 1]);\nlevColV = levColV(:)';\n\n% Build list of indices for px and contrast calculation\nnumElems = nL*nL; % APA 7/13\nindCtrstM = false(nL,numElems); % APA 7/13\nindPxM = false(nL,numElems); % APA 7/13\nindPxPlusYm = false(nL,numElems); % APA 7/13\nfor n=0:nL-1\n % indices for p(x-y), contrast\n indCtrstV = false(lq*lq,1);\n indCtrst1V = 1:lq-n;\n indCtrst2V = 1+n:lq;\n indCtrstTmpV = indCtrst1V + (indCtrst2V-1)*lq;\n indCtrstTmpV = [indCtrstTmpV indCtrst2V + (indCtrst1V-1)*lq];\n indCtrstV(indCtrstTmpV) = 1;\n indCtrstV(nanIndV) = [];\n % indCtrstC{n+1} = indCtrstV;\n indCtrstM(n+1,:) = indCtrstV;\n \n % indices for px\n indPxV = false(lq*lq,1);\n indPxV(lq*n+1:lq*(n+1)) = true;\n indPxV(nanIndV) = [];\n % indPxC{n+1} = indPxV;\n indPxM(n+1,:) = indPxV;\n \nend\nfor n=1:2*nL\n % indices for p(x+y)\n indPxPlusYv = false(lq*lq,1);\n indPxPlusYv(levRowV + levColV == n) = 1;\n indPxPlusYv(nanIndV) = [];\n % indPxPlusYc{n} = indPxPlusYv;\n indPxPlusYm(n,:) = indPxPlusYv;\nend\n\n% Build linear indices column/row-wise for Symmetry\nindRowV = zeros(1,lq*lq);\nfor i=1:lq\n indRowV((i-1)*lq+1:(i-1)*lq+lq) = i:lq:lq*lq;\nend\n\n% Filter out NaN levels\nlevRowV(nanIndV) = [];\nlevColV(nanIndV) = [];\n\n% Initialize\nenergy3M = [];\nentropy3M = [];\nsumAvg3M = [];\ncorr3M = [];\ninvDiffMom3M = [];\ncontrast3M = [];\nclustShade3M = [];\nclustPromin3M = [];\nharalCorr3M = [];\nif flagv(1)\n energy3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(2)\n entropy3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(3)\n sumAvg3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(4)\n corr3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(5)\n invDiffMom3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(6)\n contrast3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(7)\n clustShade3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(8)\n clustPromin3M = zeros([numRows, numCols, numSlices],'single');\nend\nif flagv(9)\n haralCorr3M = zeros([numRows, numCols, numSlices],'single');\nend\n\ntic\n% Iterate over slices. compute cooccurance for all patches per slice\nfor slcNum = 1:numSlices\n disp(['--- Texture Calculation for Slice # ', num2str(slcNum), ' ----'])\n if flagv(1), energyV = zeros(1,numVoxels,'single'); end\n if flagv(2), entropyV = zeros(1,numVoxels,'single'); end\n if flagv(3), sumAvgV = zeros(1,numVoxels,'single'); end\n if flagv(4), corrV = zeros(1,numVoxels,'single'); end\n if flagv(5), invDiffMomV = zeros(1,numVoxels,'single'); end\n if flagv(6), contrastV = zeros(1,numVoxels,'single'); end\n if flagv(7), clustShadeV = zeros(1,numVoxels,'single'); end\n if flagv(8), clustProminV = zeros(1,numVoxels,'single'); end\n if flagv(9), haralCorrV = zeros(1,numVoxels,'single'); end\n \n calcSlcIndV = calcIndM(:,:,slcNum);\n calcSlcIndV = calcSlcIndV(:);\n numCalcVoxs = sum(calcSlcIndV);\n %indSlcM = indM(:,calcSlcIndV);\n indSlcM = indM(:,calcSlcIndV);\n indCurrVox = ceil(size(indM,1)/2);\n indCurrVoxV = indSlcM(indCurrVox,:);\n %slcM = uint32(q(numRowsPad+(1:numRows),numColsPad+(1:numCols),slcNum));\n % List of Voxel numbers\n voxelNumsV = uint32(0:lq*lq:lq*lq*(numCalcVoxs-1));\n slcM = uint32(q(:,:,slcNum));\n voxelValsV = slcM(indCurrVoxV);\n slc2M = slcM(indSlcM);\n slc2M = bsxfun(@plus, slc2M, (voxelValsV-1)*lq + voxelNumsV);\n %slc2M = bsxfun(@plus,slc2M,voxelNumsV);\n cooccurPatchM = accumarray(slc2M(:) ...\n ,1, [lq*lq*numCalcVoxs,1],[],...\n [],true); % patch-wise cooccurance\n cooccurPatchM = reshape(cooccurPatchM,lq*lq,numCalcVoxs);\n cooccurPatchM = cooccurPatchM + cooccurPatchM(indRowV,:); % for symmetry\n cooccurPatchM(nanIndV,:) = [];\n cooccurPatchM = bsxfun(@rdivide,cooccurPatchM,sum(cooccurPatchM)+1e-5);\n cooccurPatchM = full(cooccurPatchM);\n \n \n % Angular Second Moment (Energy)\n if flagv(1)\n energyV(calcSlcIndV) = energyV(calcSlcIndV) + sum(cooccurPatchM.^2);\n end\n % Entropy\n if flagv(2)\n entropyV(calcSlcIndV) = entropyV(calcSlcIndV) - ...\n sum(cooccurPatchM.*log2(cooccurPatchM+1e-10));\n end\n \n % % Contrast, inverse Difference Moment, sum avg\n px = indPxM * cooccurPatchM;\n if flagv(3) || flagv(5) || flagv(6)\n %pXminusY = indCtrstM * cooccurPatchM;\n %pXplusY = indPxPlusYm * cooccurPatchM;\n contrastV(calcSlcIndV) = contrastV(calcSlcIndV) + ...\n (0:nL-1).^2 * indCtrstM * cooccurPatchM;\n invDiffMomV(calcSlcIndV) = invDiffMomV(calcSlcIndV) + ...\n 1./(1+(0:nL-1).^2) * indCtrstM * cooccurPatchM;\n sumAvgV(calcSlcIndV) = sumAvgV(calcSlcIndV) + ...\n (1:2*nL) * indPxPlusYm * cooccurPatchM;\n end\n \n % weighted pixel average (mu), weighted pixel variance (sig)\n mu = (1:nL) * px;\n sig = bsxfun(@minus,(1:nL)',mu);\n sig = sum(sig .*sig .* px, 1);\n \n if flagv(4) || flagv(7) || flagv(8)\n levIMinusMu = bsxfun(@minus,levRowV',mu);\n levJMinusMu = bsxfun(@minus,levColV',mu);\n end\n \n % Correlation\n if flagv(4)\n corrV(calcSlcIndV) = corrV(calcSlcIndV) + ...\n sum(levIMinusMu .* levJMinusMu .* cooccurPatchM, 1) ...\n ./ (sig + 1e-10); % sig.^2 to match ITK results (ITK bug)\n end\n \n % Cluster Shade\n if flagv(7)\n clstrV = levIMinusMu + levJMinusMu;\n clustShadeV(calcSlcIndV) = clustShadeV(calcSlcIndV) + ...\n sum(clstrV.*clstrV.*clstrV .* cooccurPatchM, 1);\n end\n % Cluster Prominence\n if flagv(8)\n clstrV = levIMinusMu + levJMinusMu;\n clustProminV(calcSlcIndV) = clustProminV(calcSlcIndV) + ...\n sum(clstrV.*clstrV.*clstrV.*clstrV .* cooccurPatchM, 1);\n end\n \n % Haralick Correlation\n if flagv(9)\n % muX = mean(px,1);\n muX = 1/nL;\n % sigX = bsxfun(@minus,px,muX);\n sigX = px - muX;\n sigX = sum(sigX .*sigX, 1)/(nL);\n \n % % Knuth method for mean and standard deviation (like ITK)\n % muX = px(1,:);\n % muPrevX = muX;\n % sigX = muX*0;\n % for col = 2:size(px,1)\n % muX = muPrevX + (px(col,:) - muPrevX)/col;\n % sigX = sigX + (px(col,:)-muX).*(px(col,:)-muPrevX);\n % muPrevX = muX;\n % end\n % sigX = sigX/nL;\n \n haralCorrV(calcSlcIndV) = haralCorrV(calcSlcIndV) + ...\n (levRowV .* levColV * cooccurPatchM - ...\n muX .* muX) ./ (sigX + eps); % (levRowV-1) .* (levColV-1) to match ITK? Bug?\n \n end\n \n if flagv(1)\n energy3M(:,:,slcNum) = reshape(energyV(:),[numRows, numCols]);\n end\n if flagv(2)\n entropy3M(:,:,slcNum) = reshape(entropyV(:),[numRows, numCols]);\n end\n if flagv(3)\n sumAvg3M(:,:,slcNum) = reshape(sumAvgV(:),[numRows, numCols]);\n end\n if flagv(4)\n corr3M(:,:,slcNum) = reshape(corrV(:),[numRows, numCols]);\n end\n if flagv(5)\n invDiffMom3M(:,:,slcNum) = reshape(invDiffMomV(:),[numRows, numCols]);\n end\n if flagv(6)\n contrast3M(:,:,slcNum) = reshape(contrastV(:),[numRows, numCols]);\n end\n if flagv(7)\n clustShade3M(:,:,slcNum) = reshape(clustShadeV(:),[numRows, numCols]);\n end\n if flagv(8)\n clustPromin3M(:,:,slcNum) = reshape(clustProminV(:),[numRows, numCols]);\n end\n if flagv(9)\n haralCorr3M(:,:,slcNum) = reshape(haralCorrV(:),[numRows, numCols]);\n end\n \n if waitbarFlag\n set(hWait, 'Vertices', [[0 0 slcNum/numSlices slcNum/numSlices]' [0 1 1 0]']);\n drawnow;\n end\nend\ntoc\n\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/PlanMetrics/heterogenity_metrics/textureByPatchAllOffsFromCtr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.35567148878130794}} {"text": "function [fgsegment keepFascicles] = dtiSegmentFiberWithNiftiRoi(fg, targetROIfile, targetROI2file, thresholdmm)\n\n% Extracting streamlines terminating within a certain distance from ROIs (e.g. gray matter ROIs)\n% \n% INPUT:\n% fg: fg structure\n% targetROIfile: the name of first ROI nifti file\n% targetROI2file: the name of second ROI nifti file\n% thresholdmm: the distance threshold in mm; the streamlines with endpoint within the threshold will be selected.\n% \n% Example:\n% fg = fgRead(wholebrainFG);\n% targetROIfile = 'Left_V3A.nii.gz';\n% targetROI2file = 'Left_hV4.nii.gz';\n% thresholdmm = 4;\n% [fgsegment keepFascicles] = dtiSegmentFiberWithNiftiRoi(fg, targetROIfile, targetROI2file, thresholdmm)\n% (C) Hiromasa Takemura, CiNet, 2017\n\nif notDefined('thresholdmm')\nthresholdmm = 4;\nend\n\n% Load ROIs\nroi1 = niftiRead(targetROIfile);\nroi2 = niftiRead(targetROI2file);\n\n% Define threshold in image space (assuming isotropic)\n% Note that the threshold is squared (we keep using squared number in subsequent process)\nthreshold = (thresholdmm./(roi1.pixdim(1)))^2;\n\n% Get acpc to image transformation matrix\nacpc2img = inv(roi1.qto_xyz);\n\n% Transfer fg into image coordinate\nfgImg = dtiXformFiberCoords(fg, acpc2img,'img');\n\n%% Select fibers within a certain distance from each ROIs\nfprintf('Segmenting tracts from Connectome ...\\n')\n\nstreamlinenum = length(fgImg.fibers);\n% Extract ACPC coordinate of tract endpoints\nfor kk = 1:streamlinenum\n fibercoordinate = cell2mat(fgImg.fibers(kk));\n fiberlength = size(fibercoordinate);\n firstfiberend(kk,1) = fibercoordinate(1,1);\n firstfiberend(kk,2) = fibercoordinate(2,1);\n firstfiberend(kk,3) = fibercoordinate(3,1);\n secondfiberend(kk,1) = fibercoordinate(1,fiberlength(2));\n secondfiberend(kk,2) = fibercoordinate(2,fiberlength(2));\n secondfiberend(kk,3) = fibercoordinate(3,fiberlength(2));\n \n clear fibercoordinate fiberlength\nend\n\n%% Extract coordinates of ROIs\n[tcoords(:,1), tcoords(:,2), tcoords(:,3)]= ind2sub(size(roi1.data), find(roi1.data));\n[t2coords(:,1), t2coords(:,2), t2coords(:,3)]= ind2sub(size(roi2.data), find(roi2.data));\n\n\n% Chose streamlines in which one endpoint is closer to first ROI, and the other\n% endpoint is close to second ROI\nfor kp = 1:streamlinenum\n [indices_ff(kp), bestSqDis_ff(kp)] = nearpoints(transpose(firstfiberend(kp,:)), transpose(tcoords));\n [indices_ss(kp), bestSqDis_ss(kp)] = nearpoints(transpose(secondfiberend(kp,:)),transpose(t2coords));\n [indices_fs(kp), bestSqDis_fs(kp)] = nearpoints(transpose(firstfiberend(kp,:)), transpose(t2coords));\n [indices_sf(kp), bestSqDis_sf(kp)] = nearpoints(transpose(secondfiberend(kp,:)),transpose(tcoords));\nend\n\n\n% Select fibers within the threshold, then create keepFascicles\n% structure\nfffiber = find(bestSqDis_ff 0\n keepFascicles = zeros(streamlinenum,1);\n for ik = 1:length(bothfiber)\n keepFascicles(bothfiber(ik)) = 1;\n end\nfgsegment = fgExtract(fg, logical(keepFascicles), 'keep');\nelse\nfprintf('No streamlines satisfied criteria ...\\n')\nend\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/mrDiffusion/fiber/dtiSegmentFiberWithNiftiRoi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3554583296471952}} {"text": " function y = reale(x, arg2)\n%function y = reale(x)\n%function y = reale(x, tol)\n%function y = reale(x, 'warn')\n%function y = reale(x, 'error')\n%function y = reale(x, 'report')\n%function y = reale(x, 'disp')\n% return real part of complex data (with error checking).\n% checks that imaginary part is negligible (or warning etc. if not)\n% Copyright Jeff Fessler, The University of Michigan\n\ncom = 'error';\ntol = 1e-13;\nif nargin > 1\n\tif ischar(arg2)\n\t\tcom = arg2;\n\telseif isnumeric(arg2)\n\t\ttol = arg2;\n\tend\nend\n\nif streq(com, 'disp')\n\t;\nelseif streq(com, 'warn')\n\tonlywarn = 1;\nelseif streq(com, 'error')\n\tonlywarn = 0;\nelseif streq(com, 'report')\n\t;\nelse\n\terror(sprintf('bad argument %s', com))\nend\n\nif max(abs(x(:))) == 0\n\tif any(imag(x(:)) ~= 0)\n\t\terror 'max real 0, but imaginary!'\n\telse\n\t\ty = real(x);\n\t\treturn\nend\nend\n\nfrac = max(abs(imag(x(:)))) / max(abs(x(:)));\nif streq(com, 'report')\n\tprintf('imaginary part %g%%', frac * 100)\n\treturn\nend\n\nif frac > tol\n\tt = sprintf('%s: imaginary fraction %g', mfilename, frac);\n\tif streq(com, 'disp')\n\t\tdisp(t)\n\telseif onlywarn\n\t\tdisp(t)\n\telse\n\t\terror(t)\n\tend\nend\ny = real(x);\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@NUFFT/private/reale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.35521038574260866}} {"text": "function out=airdata(uu)\n%\n% Fake air data - this will be replaced with real air data in Chapter 4\n%\n% modified 12/11/2009 - RB\n\n % process inputs to function\n pn = uu(1); % North position (meters)\n pe = uu(2); % East position (meters)\n h = -uu(3); % altitude (meters)\n u = uu(4); % body velocity along x-axis (meters/s)\n v = uu(5); % body velocity along y-axis (meters/s)\n w = uu(6); % body velocity along z-axis (meters/s)\n phi = 180/pi*uu(7); % roll angle (degrees) \n theta = 180/pi*uu(8); % pitch angle (degrees)\n psi = 180/pi*uu(9); % yaw angle (degrees)\n p = 180/pi*uu(10); % body angular rate along x-axis (degrees/s)\n q = 180/pi*uu(11); % body angular rate along y-axis (degrees/s)\n r = 180/pi*uu(12); % body angular rate along z-axis (degrees/s)\n\n Va = sqrt(u^2+v^2+w^2);\n alpha = atan2(w,u);\n beta = asin(v);\n wn = 0;\n we = 0;\n wd = 0;\n \n out = [Va; alpha; beta; wn; we; wd];\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/airdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.355089691163324}} {"text": "function h = rdivide(f, g, pref)\n%./ Pointwise CHEBFUN right divide.\n% F./G returns a CHEBFUN that represents the function F(x)/G(x).\n% If F and G are array-valued column (row) CHEBFUNs, they must have the same\n% number of columns (rows).\n%\n% See also MRDIVIDE, TIMES.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% Trivial empty case:\nif ( isempty(f) || isempty(g) )\n h = chebfun(); \n return\nend\n\n% Trivial zero numerator case:\nif ( isnumeric(f) && ~any(f) )\n h = 0*g;\n return\nend\n\nif ( nargin < 3 )\n pref = chebfunpref();\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CHEBFUN ./ CHEBFUN %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nif ( isa(f,'chebfun') && isa(g, 'chebfun') )\n\n % Check the number of columns match:\n if ( numColumns(f) ~= numColumns(g) )\n if ( numColumns(f) == 1 )\n h = g;\n for k = 1:numColumns(g)\n h(k) = rdivide(f, g(k));\n end\n elseif ( numColumns(g) == 1 )\n h = f;\n for k = 1:numColumns(f)\n h(k) = rdivide(f(k), g);\n end\n else\n error('CHEBFUN:CHEBFUN:rdivide:quasi', ...\n 'Chebfun quasimatrix dimensions must agree.')\n end\n return\n end\n \n if ( numel(f) == 1 && numel(g) == 1 )\n % CHEBFUN case :\n \n % If one of the two CHEBFUNs uses a PERIODICTECH reprensetation, \n % cast it to a NONPERIODICTECH.\n if ( ~isPeriodicTech(f.funs{1}) && isPeriodicTech(g.funs{1}) )\n g = chebfun(g, g.domain, 'tech', get(f.funs{1}, 'tech'));\n elseif ( isPeriodicTech(f.funs{1}) && ~isPeriodicTech(g.funs{1}) )\n f = chebfun(f, f.domain, 'tech', get(g.funs{1}, 'tech'));\n end\n \n % Array-valued CHEBFUN case:\n h = columnRdivide(f, g, pref);\n else\n % QUASIMATRIX case:\n \n % Convert to a cell array:\n f = mat2cell(f);\n g = mat2cell(g);\n % Loop over the columns:\n for k = numel(f):-1:1\n h(k) = columnRdivide(f{k}, g{k}, pref);\n end\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CHEBFUN ./ constant %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nelseif ( isa(f, 'chebfun') )\n\n numColsF = numColumns(f);\n numelF = numel(f);\n numelG = numel(g);\n \n % Different cases:\n if ( numColsF == 1 )\n % e.g., x./[1 2 3]\n h = columnRdivide(f, g, pref);\n elseif ( numelG == 1 )\n % e.g., [x sin(x)]./2\n for k = numelF:-1:1\n h(k) = columnRdivide(f(k), g, pref);\n end\n elseif ( numelG == numColsF )\n % e.g., [x sin(x) exp(x)]./[1 2 3]\n if ( numel(f) == 1 )\n h = columnRdivide(f, g, pref);\n else\n f = mat2cell(f);\n for k = numColsF:-1:1\n h(k) = columnRdivide(f{k}, g(k), pref);\n end\n end\n else\n error('CHEBFUN:CHEBFUN:rdivide:dim', ...\n 'Chebfun quasimatrix dimensions must agree.');\n end\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%% constant ./ CHEBFUN %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \nelse\n \n numColsG = numColumns(g);\n numelF = numel(f);\n numelG = numel(g);\n \n % Different cases:\n if ( numColsG == 1 )\n % e.g., [1 2 3]./(2+x)\n for k = numelF:-1:1\n h(k) = columnRdivide(f(k), g, pref);\n end\n h = quasi2cheb(h);\n elseif ( numelF == 1 )\n % e.g., 2./(2+[x x abs(x)])\n g = mat2cell(g);\n for k = numColsG:-1:1\n h(k) = columnRdivide(f, g{k}, pref);\n end\n try h = quasi2cheb(h); catch, end\n elseif ( numelF == numColsG )\n % e.g., [1 2]./(2+[x sin(x)])\n g = mat2cell(g);\n for k = numColsG:-1:1\n h(k) = columnRdivide(f(k), g{k}, pref);\n end\n try h = quasi2cheb(h); catch, end\n else\n error('CHEBFUN:CHEBFUN:rdivide:dim', ...\n 'Chebfun quasimatrix dimensions must agree.');\n end\n\nend\n\nend\n\nfunction h = columnRdivide(f, g, pref)\n\n% If g is numeric then call TIMES():\nif ( isnumeric(g) )\n if ( any(g == 0) )\n % note g could be a vector, with some zero components\n % TODO: Return identically Inf/NaN CHEBFUN instead?\n error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:divisionByZero', ...\n 'Division by zero.')\n end\n h = f.*(1./g);\n return\nend\n\n% Check for zero FUNs:\nfor k = 1:numel(g.funs)\n if ( iszero(g.funs{k}) )\n % TODO: Return CHEBFUN with identically Inf/NaN FUN instead?\n error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:divisionByZeroChebfun', ...\n 'Division by CHEBFUN with identically zero FUN.');\n end\nend\n\n% Add breaks at the roots of g:\ng = addBreaksAtRoots(g, pref);\n\nif ( isa(f, 'chebfun') )\n \n % Check that the domains are the same:\n if ( ~domainCheck(f, g) )\n error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:domain', ...\n 'Inconsistent domains.');\n end\n \n % Check that the orientation is the same:\n if ( xor(f.isTransposed, g.isTransposed) )\n error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:dim', ...\n 'Matrix dimension do not agree (transposed)');\n end\n \n % Introduce matching breakpoints in f and g:\n [f, g] = overlap(f, g);\n\n % Copy g to h in preparation for output:\n h = g;\n\n % Loop over the FUNS:\n for k = 1:numel(g.funs)\n h.funs{k} = rdivide(f.funs{k}, g.funs{k});\n end\n \n % Divide the pointValues:\n h.pointValues = f.pointValues./g.pointValues;\n \n % Avoid NaN or Inf from divide by zero where possible:\n hpv = h.pointValues; fpv = f.pointValues; gpv = g.pointValues;\n idx = (isnan(hpv) & ~(isnan(fpv) | isnan(gpv))) | ...\n (isinf(hpv) & (abs(fpv) < 100*chebfuneps*vscale(f)));\n if ( any(idx) )\n pvavg = (feval(h, h.domain, 'left') + feval(h, h.domain, 'right'))/2;\n h.pointValues(idx) = pvavg(idx);\n end\n \n \nelse\n\n % Copy g to h in preparation for output:\n h = g;\n\n % Loop over the FUNS:\n for k = 1:numel(g.funs)\n h.funs{k} = rdivide(f, g.funs{k});\n end\n \n % Divide the pointValues:\n h.pointValues = f./g.pointValues;\n \nend\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/@chebfun/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.354875985009871}} {"text": "function femI = genP1IFEM3D(mesh,fem,btM,btP)\n%% Usage: Generate Quadrature Information on Interface Elements\n% Each interface tetrahedron is cut into 4 to 9 small tetrahedra \n%\n% femI.t --- global index on small tetrahedra\n% femI.bas --- nt-4-4 matrix stores basis functions on all small tetra \n% femI.gx --- Gaussian x nodes\n% femI.gy --- Gaussian y nodes\n% femI.gz --- Gaussian z nodes\n% femI.gw --- Gaussian weights\n% femI.area --- Areas of all small tetra\n% femI.quadT --- number of small tetras of each interface element\n% femI.locID --- order of local index, to match with the basis function\n\n% ***** The following info only used for partial penalty IFEM *****\n\n% femI.bas1 --- nti-4-4 basis function on 1st piece of interface element\n% femI.bas2 --- nti-4-4 basis function on 2nd piece of interface element\n% femI.plusPC --- 1 or 2 denotes which piece corresponds to btP.\n\n% Last Modified by Xu Zhang 08/02/2020\n\n%% \nntI = -min(mesh.tLoc);\nt = zeros(8*ntI,4); bas = zeros(8*ntI,4,4); A = zeros(8*ntI,1);\ngx = zeros(8*ntI,4); gy = zeros(8*ntI,4); gz = zeros(8*ntI,4);\nQelemID = zeros(8*ntI,1);\nquadT = zeros(ntI,1); locIDvec = zeros(ntI,4);\nbas1 = zeros(ntI,4,4); bas2 = zeros(ntI,4,4); plusPC = zeros(ntI,1);\nintID = find(mesh.tLoc<0);\nid = 0;\nfor i = 1:ntI\n tID = intID(i);\n t_e = mesh.t_e(tID,:);\n intpt = mesh.eIntP(-mesh.eLoc(t_e(mesh.eLoc(t_e)<0)),:);\n pLocK = mesh.pLoc(mesh.t(tID,:));\n vert0 = mesh.p(mesh.t(tID,:),:); \n if size(intpt,1) == 3 % Type 1 Interface Element (3 intersection pts)\n if pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == 1 && pLocK(4) == 1 \n locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == 1 \n locID = [2,3,4,1]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == 1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == 1 \n locID = [3,4,1,2]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == 1 && pLocK(2) == 1 && pLocK(3) == 1 && pLocK(4) == -1 \n locID = [4,1,2,3]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == -1 && pLocK(4) == -1 \n locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n elseif pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == -1 \n locID = [2,3,4,1]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n elseif pLocK(1) == -1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == -1 \n locID = [3,4,1,2]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n elseif pLocK(1) == -1 && pLocK(2) == -1 && pLocK(3) == -1 && pLocK(4) == 1 \n locID = [4,1,2,3]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n end\n p1 = [vert(1,:);intpt]; t1 = delaunay(p1);\n p2 = [vert(2:4,:);intpt];t2 = delaunay(p2); \n elseif size(intpt,1) == 4 % Type 2 Interface Element (4 intersection pts)\n if pLocK(1) == -1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == 1 \n locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == 1 \n locID = [1,3,2,4]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == 1 && pLocK(4) == -1 \n locID = [1,4,2,3]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;\n elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == -1 && pLocK(4) == 1 \n locID = [1,4,2,3]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == -1 \n locID = [1,3,2,4]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n elseif pLocK(1) == 1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == -1 \n locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;\n end\n p1 = [vert(1:2,:);intpt]; t1 = delaunay(p1);\n p2 = [vert(3:4,:);intpt]; t2 = delaunay(p2);\n else\n stp = 1;\n end\n [BAS1,BAS2] = basIFE3DP1coef(vert,intpt,coef); \n X1 = p1(t1(:,1),:); X2 = p1(t1(:,2),:); X3 = p1(t1(:,3),:); X4 = p1(t1(:,4),:);\n [gx1, gy1, gz1] = gaussPtetra(X1,X2,X3,X4,fem.ng);\n A1 = tetraArea(X1,X2,X3,X4);\n \n X1 = p2(t2(:,1),:); X2 = p2(t2(:,2),:); X3 = p2(t2(:,3),:); X4 = p2(t2(:,4),:);\n [gx2, gy2, gz2] = gaussPtetra(X1,X2,X3,X4,fem.ng);\n A2 = tetraArea(X1,X2,X3,X4); \n \n nt1 = size(t1,1); nt2 = size(t2,1);\n bas(id+1:id+nt1,:,1) = repmat(BAS1(1,:),nt1,1);\n bas(id+1:id+nt1,:,2) = repmat(BAS1(2,:),nt1,1);\n bas(id+1:id+nt1,:,3) = repmat(BAS1(3,:),nt1,1);\n bas(id+1:id+nt1,:,4) = repmat(BAS1(4,:),nt1,1);\n bas(id+nt1+1:id+nt1+nt2,:,1) = repmat(BAS2(1,:),nt2,1);\n bas(id+nt1+1:id+nt1+nt2,:,2) = repmat(BAS2(2,:),nt2,1);\n bas(id+nt1+1:id+nt1+nt2,:,3) = repmat(BAS2(3,:),nt2,1);\n bas(id+nt1+1:id+nt1+nt2,:,4) = repmat(BAS2(4,:),nt2,1);\n gx(id+1:id+nt1+nt2,:) = [gx1;gx2];\n gy(id+1:id+nt1+nt2,:) = [gy1;gy2];\n gz(id+1:id+nt1+nt2,:) = [gz1;gz2];\n A(id+1:id+nt1+nt2,:) = [A1;A2];\n QelemID(id+1:id+nt1+nt2) = tID;\n \n temp = fem.t(tID,:);\n temp2 = temp(locID);\n t(id+1:id+nt1+nt2,:) = repmat(temp2,nt1+nt2,1);\n locIDvec(i,:) = locID;\n quadT(i) = nt1+nt2;\n \n bas1(i,:,1) = BAS1(1,:); bas2(i,:,1) = BAS2(1,:);\n bas1(i,:,2) = BAS1(2,:); bas2(i,:,2) = BAS2(2,:);\n bas1(i,:,3) = BAS1(3,:); bas2(i,:,3) = BAS2(3,:);\n bas1(i,:,4) = BAS1(4,:); bas2(i,:,4) = BAS2(4,:);\n \n id = id+nt1+nt2;\nend\nt(id+1:end,:) = []; bas(id+1:end,:,:) = []; A(id+1:end) = [];\ngx(id+1:end,:) = []; gy(id+1:end,:) = []; gz(id+1:end,:) = [];\nQelemID(id+1:end,:) = [];\nfemI = struct('t',t,'bas',bas,'gx',gx,'gy',gy,'gz',gz,'area',A,'gw',fem.gw,...\n 'quadT',quadT,'locID',locIDvec,'bas1',bas1,'bas2',bas2,'plusPC',plusPC,...\n 'QelemID',QelemID);\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/genP1IFEM3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.3548121706938063}} {"text": "function [It, Ix, Iy] = partial_deriv(images, uv_prev, interpolation_method, deriv_filter, b)\n\n%PARTIAL_DERIV Spatio-temporal derivatives\n% P = PARTIAL_DERIV(IMAGES, INIT) computes the spatio-temporal derivatives\n%\n% Author: Deqing Sun, Department of Computer Science, Brown University\n% Contact: dqsun@cs.brown.edu\n% $Date: 2007-11-30 $\n% $Revision $\n%\n% Copyright 2007-2010, Brown University, Providence, RI. USA\n% \n% All Rights Reserved\n% \n% All commercial use of this software, whether direct or indirect, is\n% strictly prohibited including, without limitation, incorporation into in\n% a commercial product, use in a commercial service, or production of other\n% artifacts for commercial purposes. \n%\n% Permission to use, copy, modify, and distribute this software and its\n% documentation for research purposes is hereby granted without fee,\n% provided that the above copyright notice appears in all copies and that\n% both that copyright notice and this permission notice appear in\n% supporting documentation, and that the name of the author and Brown\n% University not be used in advertising or publicity pertaining to\n% distribution of the software without specific, written prior permission. \n%\n% For commercial uses contact the Technology Venture Office of Brown University\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO\n% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR\n% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n% THIS SOFTWARE. \n\nif nargin == 2\n interpolation_method = 'cubic';\nend;\n\nif nargin == 4\n h = deriv_filter;\nelse\n h = [1 -8 0 8 -1]/12; % used in Wedel etal \"improved TV L1\"\nend;\n\nif nargin < 5\n b = 0.5; %blending ratio\nend;\n\nH = size(images, 1);\nW = size(images, 2);\n\n[x,y] = meshgrid(1:W,1:H);\nx2 = x + uv_prev(:,:,1); \ny2 = y + uv_prev(:,:,2); \n\n% Record out of boundary pixels\nB = (x2>W) | (x2<1) | (y2>H) | (y2<1);\n\nif size(images, 4) ~= 1\n B = repmat(B, [1 1 size(images, 3)]);\nend;\n\nif size(images, 4) == 1\n img1 = images(:,:,1);\n img2 = images(:,:,2);\nelse\n img1 = images(:,:,:,1);\n img2 = images(:,:,:,2);\nend;\n\nif strcmp(interpolation_method, 'bi-cubic')\n\n %h = [-0.5, 0, 0.5]; % consistent with bi-cubic interpolation \n \n % Bicubic interpolation\n if nargout == 1\n \n if size(images, 4) == 1\n % gray-level\n warpIm = interp2_bicubic(images(:,:,2),x2,y2, h);\n else\n % color\n warpIm = zeros(size(images(:,:,:,1)));\n for j = 1:size(images,3)\n warpIm(:,:,j) = interp2_bicubic(images(:,:,j, 2),x2,y2, h);\n end;\n end;\n \n elseif nargout == 3\n \n if size(images, 4) == 1\n % gray-level\n [warpIm Ix Iy] = interp2_bicubic(images(:,:,2),x2,y2, h);\n else\n % color\n warpIm = zeros(size(images(:,:,:,1)));\n Ix = warpIm;\n Iy = warpIm;\n for j = 1:size(images,3)\n [warpIm(:,:,j) Ix(:,:,j) Iy(:,:,j)] = interp2_bicubic(images(:,:,j,2),x2,y2, h);\n end;\n end;\n \n else\n error('partial_deriv: number of output wrong!');\n end;\n\n indx = isnan(warpIm);\n if size(images, 4) == 1\n It = warpIm - images(:,:,1);\n else\n It = warpIm - images(:,:,:,1);\n end;\n \n % Disable those out-of-boundary pixels in warping\n It(indx) = 0;\n if nargout == 3 \n \n % Temporal average\n I1x = imfilter(img1, h, 'corr', 'symmetric', 'same'); %\n I1y = imfilter(img1, h', 'corr', 'symmetric', 'same');\n \n % b = 0.6; % recommended in Wedal etal \"improved TV-L1\" 2008\n % b = 0.5;\n% b = 1;\n \n \n Ix = b*Ix+(1-b)*I1x;\n Iy = b*Iy+(1-b)*I1y;\n\n Ix(indx) = 0;\n Iy(indx) = 0; \n end;\n \nelseif strcmp(interpolation_method, 'bi-linear') || strcmp(interpolation_method, 'cubic') \n\n if strcmp(interpolation_method, 'bi-linear')\n method = 'linear';\n else\n method = 'cubic';\n end;\n \n % Matlab built-in \n if size(images, 4) == 1\n % Gray-level\n warpIm = interp2(x,y,images(:,:,2),x2,y2,method);\n It = warpIm - images(:,:,1); \n \n else\n % Color\n warpIm = zeros(size(images(:,:,:,1)));\n for j = 1:size(images,3)\n warpIm(:,:,j) = interp2(x,y,images(:,:,j,2),x2,y2,method, NaN);\n end;\n It = warpIm - images(:,:,:,1);\n \n end;\n\n % spline-based bicubic interpolation code with incorrect derivatives (below)\n% if size(images, 4) == 1\n% % gray-level\n% warpIm = interp2_bicubic(images(:,:,2),x2,y2, h);\n% It = warpIm - images(:,:,1); \n% else\n% % color\n% warpIm = zeros(size(images(:,:,:,1)));\n% for j = 1:size(images,3)\n% warpIm(:,:,j) = interp2_bicubic(images(:,:,j, 2),x2,y2, h);\n% end;\n% It = warpIm - images(:,:,:,1);\n% end;\n \n if nargout == 3\n \n % First compute derivative then warp\n I2x = imfilter(img2, h, 'corr', 'symmetric', 'same');\n I2y = imfilter(img2, h', 'corr', 'symmetric', 'same');\n \n if size(images, 4) == 1\n % Gray-level\n Ix = interp2(x,y,I2x,x2,y2,method);\n Iy = interp2(x,y,I2y,x2,y2,method);\n\n% % spline-based bicubic interpolation code with incorrect derivatives \n% Ix = interp2_bicubic(I2x,x2,y2, h);\n% Iy = interp2_bicubic(I2y,x2,y2, h);\n \n else\n % Color\n Ix = zeros(size(images(:,:,:,1)));\n Iy = Ix;\n \n for j = 1:size(images,3)\n Ix(:,:,j) = interp2(x,y,I2x(:,:,j),x2,y2,method);\n Iy(:,:,j) = interp2(x,y,I2y(:,:,j),x2,y2,method);\n end;\n \n end;\n \n % warp then derivative \n% if size(images, 4) == 1\n% tmp = images(:,:,1);\n% else\n% tmp = images(:,:,:,1);\n% end;\n% warpIm(B) = tmp(B); \n% Ix = imfilter(warpIm, h, 'corr', 'symmetric', 'same'); %\n% Iy = imfilter(warpIm, h', 'corr', 'symmetric', 'same');\n % end of warp then derivative\n \n\n % Temporal average\n I1x = imfilter(img1, h, 'corr', 'symmetric', 'same'); %\n I1y = imfilter(img1, h', 'corr', 'symmetric', 'same');\n \n % b = 0.6; % recommended in Wedal etal \"improved TV-L1\" 2008\n % b = 0.5;\n \n Ix = b*Ix+(1-b)*I1x;\n Iy = b*Iy+(1-b)*I1y; \n \n end;\n \n % Disable those out-of-boundary pixels in warping\n It(B) = 0;\n if nargout == 3\n Ix(B) = 0;\n Iy(B) = 0;\n end;\n \nelse\n error('partial_deriv: unknown interpolation method!');\nend;", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/utils/partial_deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.35471509621614966}} {"text": "% AstarMOO A*-MOO navigation class\n% \n% A concrete subclass of the Navigation class that implements the A*\n% navigation algorithm for multiobjective optimization (MOO) - i.e.\n% optimizes over several objectives/criteria.\n% \n% Methods:\n% plan Compute the cost map given a goal and map\n% path Compute a path to the goal\n% visualize Display the obstacle map (deprecated)\n% plot Display the obstacle map\n% costmap_modify Modify the costmap\n% costmap_get Return the current costmap\n% costmap_set Set the current costmap\n% distancemap_get Set the current distance map\n% heuristic_get Get the current heuristic map\n% display Print the parameters in human readable form\n% char Convert to string\n% \n% Properties:\n% TBD\n% \n% Example::\n%\n% load map1 % load map\n% goal = [50;30];\n% start = [20;10];\n% as = AstarMOO(map); % create Navigation object\n% as.plan(goal,2); % setup costmap for specified goal\n% as.path(start); % plan solution path star-goal, animate\n% P = as.path(start); % plan solution path star-goal, return path\n%\n% Example 2:\n% goal = [100;100];\n% start = [1;1];\n% as = AstarMOO(0); % create Navigation object with random occupancy grid\n% as.addCost(1,L); % add 1st add'l cost layer L\n% as.plan(goal,3); % setup costmap for specified goal\n% as.path(start); % plan solution path start-goal, animate\n% P = as.path(start); % plan solution path start-goal, return path\n% \n% Notes::\n% - Obstacles are represented by Inf in the costmap.\n% \n% References::\n% - A Pareto Optimal D* Search Algorithm for Multiobjective Path Planning, A. Lavin.\n% - A Pareto Front-Based Multiobjective Path Planning Algorithm, A. Lavin.\n% - Robotics, Vision & Control, Sec 5.2.2, Peter Corke, Springer, 2011.\n%\n% Author::\n% Alexander Lavin\n% \n% See also Navigation, Astar, AstarPO.\n\n% Copyright (C) 1993-2015, by Peter I. Corke, Alexander Lavin\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%\n% The RTB implementation of this algorithm is done by Alexander Lavin.\n% http://alexanderlavin.com\n\n\n% Implementation notes:\n%\n% All the state is kept in the structure called a\n% X is an index into the array of states.\n% state pointers are kept as matlab array index rather than row,col format\n\nclassdef AstarMOO < Navigation\n\n properties (SetAccess=private, GetAccess=private)\n\n % essential world info\n costmap % world cost map: obstacle = Inf\n G % index of goal point\n N % number of objectives\n \n % info kept per cell (state):\n b % backpointer (0 means not set)\n t % tag: NEW OPEN CLOSED\n \n cost_g % path distance summation\n cost_h % path heuristic (state to goal) cost\n cost_01 % add'l cost layer 01 (unused)\n cost_02 % add'l cost layer 02 (unused)\n cost_03 % add'l cost layer 03 (unused)\n % add more cost layers if needed...\n \n priority\n tie\n \n % list of open states: 2xN matrix\n % each open point is a column, row 1 = index of cell, row 2 = k\n openlist\n niter\n\n changed\n\n openlist_maxlen % keep track of maximum length\n quiet\n\n % tag state values\n NEW = 0;\n OPEN = 1;\n CLOSED = 2;\n end\n \n methods % start of public methods\n % AstarMOO class constructor:\n function as = AstarMOO(world, varargin)\n %AstarMOO.AstarMOO A*-MOO constructor\n %\n % AS = AstarMOO(MAP, OPTIONS) is a A* navigation object, and MAP is an\n % occupancy grid, a representation of a planar world as a\n % matrix whose elements are 0 (free space) or 1 (occupied).\n % The occupancy grid is coverted to a costmap with a unit cost\n % for traversing a cell.\n %\n % Options::\n % 'goal',G Specify the goal point (2x1)\n % 'metric',M Specify the distance metric as 'euclidean' (default)\n % or 'cityblock'.\n % 'inflate',K Inflate all obstacles by K cells.\n % 'quiet' Don't display the progress spinner\n %\n % Other options are supported by the Navigation superclass.\n %\n % Notes::\n % - If MAP == 0 a random map is created.\n %\n % See also Navigation.Navigation.\n \n % invoke the superclass constructor\n as = as@Navigation(world, varargin{:}); % includes the occgrid\n\n % options\n opt.quiet = false;\n opt = tb_optparse(opt, varargin);\n as.quiet = opt.quiet;\n \n as.occgrid2costmap(as.occgrid);\n\n % initialize the A* state variables\n as.reset();\n if ~isempty(as.goal)\n as.goal_change();\n end\n as.changed = false;\n end\n \n function reset(as)\n %AstarMOO.reset Reset the planner\n %\n % AS.reset() resets the A* planner. The next instantiation\n % of AS.plan() will perform a global replan.\n\n % build the matrices required to hold the state of each cell for A*\n as.b = zeros(size(as.occgrid), 'uint32'); % backpointers\n as.t = zeros(size(as.occgrid), 'uint8'); % tags, all NEW=0\n as.cost_g = Inf*ones(size(as.costmap)); % path cost estimate\n as.openlist = zeros(2,0); % the open list, one column per point\n \n as.openlist_maxlen = -Inf;\n end\n \n %AstarMOO.goal_change Changes to costlayers due to new goal\n %position\n function goal_change(as)\n\n if isempty(as.b)\n return;\n end\n goal = as.goal;\n\n % keep goal in index rather than row,col format\n as.G = sub2ind(size(as.occgrid), goal(2), goal(1));\n as.INSERT(as.G, as.projectCost(as.G), 'goalset');\n as.cost_g(as.G) = 0;\n \n % new goal changes cost layers:\n as.calcHeuristic(as.occgrid, as.goal);\n end\n \n function s = char(as)\n %AstarMOO.char Convert navigation object to string\n %\n % AS.char() is a string representing the state of the Astar\n % object in human-readable form.\n %\n % See also AstarMOO.display, Navigation.char.\n \n % most of the work is done by the superclass\n s = char@Navigation(as);\n end\n\n function plot(as, varargin)\n %AstarMOO.plot Visualize navigation environment\n %\n % AS.plot() displays the occupancy grid and the goal distance\n % in a new figure. The goal distance is shown by intensity which\n % increases with distance from the goal. Obstacles are overlaid\n % and shown in red.\n %\n % AS.plot(P) as above but also overlays a path given by the set\n % of points P (Mx2).\n %\n % See also Navigation.plot.\n \n plot@Navigation(as, 'distance', as.cost_h, varargin{:});\n end\n\n % invoked by Navigation.step\n function n = next(as, current)\n % Backpropagate from goal to start\n % Return [col;row] of previous step\n if as.changed\n error('Cost map has changed, replan');\n end\n X = sub2ind(size(as.occgrid), current(2), current(1));\n X = as.b(X); % set X as the backpointer of X\n if X == 0\n n = []; % goal (no further backpointer)\n else\n [r,c] = ind2sub(size(as.costmap), X);\n n = [c;r];\n end\n end \n \n function plan(as, goal, N)\n %AstarMOO.plan Prep the grid for planning.\n %\n % AS.plan() updates AS with a costmap of distance to the\n % goal from every non-obstacle point in the map. The goal is\n % as specified to the constructor.\n %\n % Inputs:\n % goal: goal state coordinates\n % N: number of optimization objectives; standard A* is 2\n % (i.e. distance and heuristic)\n \n as.N = N; % number of optimization objectives\n as.openlist = zeros(as.N+1,0);\n \n % Setup cost layers. If a\n % cost layer is goal-dependent, it's setup function needs to\n % also be called in AS.goal_change(). If more cost layers are\n % needed, add similar to AS.cost_01.\n \n % initializations first:\n as.cost_g = zeros(size(as.occgrid));\n as.cost_h = zeros(size(as.occgrid)); % filled after setting goal below\n % if add'l costs haven't been added with addCost()\n if isempty(as.cost_01)\n as.cost_01 = zeros(size(as.occgrid));\n end\n if isempty(as.cost_02)\n as.cost_02 = zeros(size(as.occgrid));\n end\n if isempty(as.cost_03)\n as.cost_03 = zeros(size(as.occgrid));\n end\n \n if nargin > 1\n as.goal = goal; % invokes superclass method set.goal()\n end\n if isempty(as.goal)\n error('must specify a goal point');\n end\n \n % Setup cost layers AS.cost_g and AS.cost_h. \n % assign values to the distance cost layer, set as AS.costmap\n as.occgrid2costmap(as.occgrid);\n % assign values to the heuristic cost layer, set as AS.cost_h\n as.calcHeuristic(as.occgrid, as.goal);\n % Additional cost layers are added by the user with the\n % AS.addCost() method\n \n % Cost priority/tiebreaker: cost_g (distance to node)\n as.priority = as.cost_g;\n as.tie = 1; % first cost: cost_g\n end\n \n function P = path(as, start)\n %AstarMOO.path Find a path between two points\n %\n % AS.path(START) finds and displays a path from START to GOAL\n % which is overlaid on the occupancy grid.\n %\n % P = AS.path(START) returns the path (2xM) from START to GOAL.\n if nargin < 1\n error('must specify start state');\n end\n\n % invoke the superclass path function, which iterates on our\n % next method\n start = [start; 1]; % Specifies backpropogation for NAV.path()\n if nargout == 0\n path@Navigation(as, start);\n else\n P = path@Navigation(as, start);\n end\n end\n \n % Handler invoked by Navigation.path() to start the navigation process\n % Calculate the solution path\n % Line comments LN reference A* pseudocode in Lavin's \"A Pareto\n % Front-Based Multiobjective Path Planning Algorithm\" where n is\n % the line number.\n function navigate_init(as, start)\n as.openlist = zeros(as.N+1,0); % make sure openlist is empty\n % begin with the start node\n start = sub2ind(size(as.costmap), start(2), start(1));\n as.openlist(1,1) = start;\n as.t(start) = as.OPEN;\n as.niter = 0; flag = 0; % init while loop\n % Plan the A* path\n while ~isempty(as.openlist) % L4\n % Normalize costs on the open list, choose expansion state:\n queue = normc(as.openlist(2:size(as.openlist,1),:)');\n [~,ind]=min(sum(queue,2));\n X = as.openlist(1,ind); % L5; minimum state on the open list\n as.DELETE(X); % L6; remove state from the openlist\n \n as.niter = as.niter + 1;\n \n if ~as.quiet && mod(as.niter, 20) == 0 % i.e. spinner every 20 iterations\n as.spinner();\n end\n \n % Populate the openlist:\n for Y=as.neighbors(X) % L7,8; check node's 8 neighbors\n if(Y==as.G) % L9; check for goal\n as.b(Y) = X; \n as.updateCosts(Y,X,as.N)\n flag = 1; % flag for goal\n break;\n end\n if as.t(Y)==as.NEW && as.costmap(Y)~=Inf % hasn't been checked and isn't an obstacle\n as.b(Y) = X;\n as.updateCosts(Y,X,as.N); % as.N = 2 -> base case w/ only distance cost parameters (g and h)\n % project node's costs into objective space:\n objspace = as.projectCost(Y,X);\n as.INSERT(Y, objspace, '');\n end\n end \n if as.verbose\n disp(' ')\n end\n if flag==1 % goal found\n break;\n end\n end\n if ~as.quiet\n fprintf('\\r');\n end\n as.changed = false;\n end\n \n function layer = cost_get(as)\n %AstarMOO.cost_get Get the specified cost layer\n layer = as.cost_02;\n end\n \n function c = heuristic_get(as)\n %AstarMOO.heuristic_get Get the current heuristic map\n %\n % C = AS.heuristic_get() is the current heuristic map. This map is the same size\n % as the occupancy grid and the value of each element is the shortest distance \n % from the corresponding point in the map to the current goal. It is computed\n % by Astar.plan.\n %\n % See also Astar.plan.\n c = as.cost_h;\n end\n\n function c = costmap_get(as)\n %AstarMOO.costmap_get Get the current costmap\n %\n % C = AS.costmap_get() is the current costmap. The cost map is the same size\n % as the occupancy grid and the value of each element represents the cost\n % of traversing the cell. It is autogenerated by the class constructor from\n % the occupancy grid such that:\n % - free cell (occupancy 0) has a cost of 1\n % - occupied cell (occupancy >0) has a cost of Inf\n %\n % See also Astar.costmap_set, Astar.costmap_modify.\n\n c = as.costmap;\n end\n\n function costmap_set(as, costmap)\n %AstarMOO.costmap_set Set the current costmap\n %\n % AS.costmap_set(C) sets the current costmap. The cost map is the same size\n % as the occupancy grid and the value of each element represents the cost\n % of traversing the cell. A high value indicates that the cell is more costly\n % (difficult) to traverese. A value of Inf indicates an obstacle.\n %\n % Notes::\n % - After the cost map is changed the path should be replanned by \n % calling AS.plan(). \n %\n % See also Astar.costmap_get, Astar.costmap_modify.\n if ~all(size(costmap) == size(as.occgrid))\n error('costmap must be same size as occupancy grid');\n end\n as.costmap = costmap;\n as.changed = true;\n end\n\n function costmap_modify(as, point, newcost)\n %AstarMOO.costmap_modify Modify cost map\n %\n % AS.costmap_modify(P, NEW) modifies the cost map at P=[X,Y] to\n % have the value NEW. If P (2xM) and NEW (1xM) then the cost of\n % the points defined by the columns of P are set to the corresponding\n % elements of NEW.\n %\n % Notes::\n % - After one or more point costs have been updated the path\n % should be replanned by calling AS.plan().\n %\n % See also AstarMOO.costmap_set, AstarMOO.costmap_get.\n\n if numel(point) == 2\n % for case of single point ensure it is a column vector\n point = point(:);\n end\n if numcols(point) ~= numcols(newcost)\n error('number of columns in point must match columns in newcost');\n end\n for i=1:numcols(point)\n X = sub2ind(size(as.costmap), point(2,i), point(1,i));\n as.costmap(X) = newcost(i);\n end\n if as.t(X) == as.CLOSED\n as.INSERT(X, as.h(X), 'modifycost');\n end\n as.changed = true;\n end \n \n function addCost(as, layer, values)\n %AstarMOO.addCost Add an additional cost layer\n %\n % AS.addCost(LAYER, VALUES) adds the matrix specified by values as a\n % cost layer. The layer number is given by LAYER, and VALUES has the same\n % size as the original occupancy grid.\n\n if size(values)~=size(as.occgrid)\n display('Layer size does not match the environment')\n return\n end\n if max(max(values))~=1 || min(min(values))~=0\n display('Layer values are not normalized [0:1]')\n return\n end\n \n if layer==1\n as.cost_01 = values;\n elseif layer==2\n as.cost_02 = values;\n elseif layer==3\n as.cost_03 = values;\n else\n display('Layer index out of range')\n end\n % If more cost layers needed, add additional elseif statements\n % as above.\n end\n \n end % end of public methods\n \n methods (Access=protected) % start of private methods\n \n function occgrid2costmap(as, og, cost)\n if nargin < 3\n cost = 1; % cost to traverse each cell\n end\n as.costmap = og;\n as.costmap(as.costmap==1) = Inf; % occupied cells -> infinite path cost\n as.costmap(as.costmap==0) = cost; % unoccupied cells -> path cost\n end\n \n function calcHeuristic(as, grid, goal)\n as.cost_h=zeros(size(grid));\n for ii=1:size(grid,1)\n for jj=1:size(grid,2)\n as.cost_h(ii,jj)=sqrt((ii-goal(1))^2+(jj-goal(2))^2);\n end\n end\n end\n \n % NOTE: Only for costs that accumulate (i.e. sum) over the\n % path, and for dynamic costs.\n % E.g. the heuristic parameter AS.cost_h only needs updating\n % when the goal state changes; it's values are stored for each\n % cell.\n %\n % Location moving from state b to a.\n \n function k_new = updateCosts(as, a, b, obj)\n\n if nargout > 0\n k_new = as.cost_g(b) + as.dc(b,a);\n return\n end\n if obj == 0 % just return what the new priority cost would be (k_new)\n return\n end\n if obj > 1 % base case\n as.cost_g(a) = as.cost_g(b) + as.dc(b,a);\n % (no heuristic update needed)\n end\n if obj > 2 % w/ cost_01: elevation\n % (no elevation update needed)\n end\n if obj > 3 % w/ cost_02: solar\n sV = [cos(as.niter/100);sin(as.niter/100)]; % rotates 1rad per 100 steps\n as.cost_02(a) = dot(sV,as.vc(b,a));\n end\n if obj > 4 % w/ cost_03: risk\n % (no risk update needed)\n end\n end\n \n % Returns the projection of state a into objective space. If\n % specified, location is moving from b to a.\n function pt = projectCost(as, a, b)\n switch nargin\n case 2\n pt = [as.cost_g(a);\n as.cost_h(a);\n as.cost_01(a);\n as.cost_02(a);\n as.cost_03(a);\n ];\n case 3\n pt = [as.cost_g(b) + as.dc(a,b);\n as.cost_h(a);\n as.cost_01(a);\n as.cost_02(a);\n as.cost_03(a);\n ];\n otherwise\n return\n end\n end\n \n % X is new node with costs in array pt\n\n function INSERT(as, X, pt, where)\n\n if nargin>2\n as.message('insert (%s) %d = %f\\n', where, X, pt);\n end\n \n i = find(as.openlist(1,:) == X);\n if length(i) > 1\n error('A*:INSERT: state in open list %d times', X);\n end\n\n if as.t(X) == as.NEW\n % add a new column to the open list\n as.openlist = [as.openlist [X; pt]];\n elseif as.t(X) == as.OPEN\n % L13: If a node with same position as successor is in the\n % OPEN list & has a lower f than successor, then skip this\n % successor.\n if pt(as.tie) < as.priority(X) % break tie with the sum of path costs\n % add a new column to the open list\n as.openlist = [as.openlist [X; pt]];\n end\n elseif as.t(X) == as.CLOSED\n % L14: If a node with same position as successor is in the\n % CLOSED list & has a lower f than successor, then skip this\n % successor.\n if pt(as.tie) < as.priority(X) % break tie with the sum of path costs\n % add a new column to the open list\n as.openlist = [as.openlist [X; pt]];\n end\n end\n\n % keep track of the max length of the openlist:\n if numcols(as.openlist) > as.openlist_maxlen\n as.openlist_maxlen = numcols(as.openlist);\n end\n\n as.t(X) = as.OPEN; % tag X as open\n end\n\n function DELETE(as, X)\n as.message('delete %d\\n', X);\n i = find(as.openlist(1,:) == X);\n if length(i) ~= 1\n error('D*:DELETE: state %d doesnt exist', X);\n end\n as.openlist(:,i) = []; % remove the column\n as.t(X) = as.CLOSED;\n end\n \n % return the distance cost of moving from state X to state Y\n function cost = dc(as, X, Y)\n [r,c] = ind2sub(size(as.costmap), [X; Y]);\n dist = sqrt(sum(diff([r c]).^2));\n dcost = (as.costmap(X) + as.costmap(Y))/2;\n\n cost = dist * dcost;\n end\n\n % return the robot unit vector; direction of moving from state X to state Y\n function vector = vc(as, X, Y)\n [Xi,Xj] = ind2sub(size(as.occgrid),X);\n [Yi,Yj] = ind2sub(size(as.occgrid),Y);\n vector = [Yi-Xi;Yj-Xj];\n vector = vector/norm(vector);\n% slope = vector(2) / vector(1);\n% theta = dot([0,1],[vector])/(norm([0,1])*norm(vector)); \n end\n \n % return index of neighbor states (max 8) as a row vector\n function Y = neighbors(as, X)\n dims = size(as.costmap);\n [r,c] = ind2sub(dims, X);\n\n % list of 8-way neighbors:\n Y = [r-1 r-1 r-1 r r r+1 r+1 r+1; c-1 c c+1 c-1 c+1 c-1 c c+1];\n % only use neighbors w/in grid bounds...\n k = (min(Y)>0) & (Y(1,:)<=dims(1)) & (Y(2,:)<=dims(2));\n Y = Y(:,k);\n Y = sub2ind(dims, Y(1,:)', Y(2,:)')';\n end\n \n end % end of private methods\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/AstarMOO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.35417875022622325}} {"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: nickabattista@gmail.com\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 lengths, 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 (nickabattista@gmail.com) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: updates the target point positions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction targets = update_Target_Point_Positions(dt,current_time,targets)\n\n\n%IDs = targets(:,1); % Stores Lag-Pt IDs in col vector\n%xPts= targets(:,2); % Original x-Values of x-Target Pts.\n%yPts= targets(:,3); % Original y-Values of y-Target Pts.\n%kStiffs = targets(:,4); % Stores Target Stiffnesses \n%N_target = length(targets(:,1)); % Gives total number of target pts!\n\n\ntR1 = 0.25; % Period A->B (and B->A) for RIGHT\ntR2 = 0.25; % Period B->C (abd C->B) for RIGHT\nperiodR = (tR1+tR2); % Time it takes to move to the right\n\noff_Left = 0;%0.10*periodR; % OFFSET FOR LEFT ARM\ntL1 = 0.25; % Period A->B (and B->A) for LEFT\ntL2 = 0.25; % Period B->C (abd C->B) for LEFT\nperiodL = (tL1+tL2); % Time it takes to move to the LEFT\n\ntR = rem(current_time,periodR); % \"Time\" (moded out) according to right arm\n\ntL = rem(current_time,periodL); % \"Time\" (moded out) according to left arm\n\n\n% Cubic Interpolation Information\np1 = 0.125;\np2 = 0.875;\n\n% a COEFFICIENTS\na0 = 0; \na1 = 0; \na2 = 0; \na3 = 9.1429;\n\n% b COEFFICIENTS\nb0 = 0.0238;\nb1 = -0.5714;\nb2 = 4.5714;\nb3 = -3.0476;\n\n% c COEFFICIENTS\nc0 = -8.1429;\nc1 = 27.4286;\nc2 = -27.4286;\nc3 = 9.1429;\n\n%\n% JELLYFISH STATES: \n% XY(:,1) = 1st X-positions\n% XY(2:150,2) = 2nd X-positions (RIGHT)\n% XY(151:end,2) = 2nd X-positions (LEFT)\n%\n% XY(:,3) = 1st Y-positions\n% XY(2:150,4) = 2nd Y-positions (RIGHT)\n% XY(151:end,4) = 2nd Y-positions (LEFT)\n%\nXY = read_In_Phase_Positions('XY_2Pos.txt');\n\n% Coming from give_Me_Jelly:\nNArm = 174;\n\n% 1st and 2nd position of RIGHT arm\nxR1 = XY(2:NArm+1,1); yR1 = XY(2:NArm+1,3);\nxR2 = XY(2:NArm+1,2); yR2 = XY(2:NArm+1,4);\n\n% 1st and 2nd position of LEFT arm\nxL1 = XY(NArm+2:end,1); yL1 = XY(NArm+2:end,3);\nxL2 = XY(NArm+2:end,2); yL2 = XY(NArm+2:end,4);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% START THE INTERPOLATING BETWEEN STATES!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%\n%\n% RIGHT ARM!\n%\n%%%%%%%%%%%%%\n\nif tR <= tR1+off_Left % STATE A -> STATE B\n \n % Scaling time for appropriate use in interp. function so tRTilde\\in[0,1]\n tRTilde = ( tR / tR1 ); \n \n % Evaluate Piecewise Cubic Interpolation Poly\n if tRTilde<=p1\n gFUNC = a0 + a1*tRTilde + a2*tRTilde^2 + a3*tRTilde^3; \n elseif tRTilde<=p2\n gFUNC = b0 + b1*tRTilde + b2*tRTilde^2 + b3*tRTilde^3; \n else\n gFUNC = c0 + c1*tRTilde + c2*tRTilde^2 + c3*tRTilde^3; \n end\n \n % MOVING X-POSITIONS\n targets(2:NArm+1,2) = xR1 + gFUNC*( xR2 - xR1 );\n \n % MOVING Y-POSITIONS\n targets(2:NArm+1,3) = yR1 + gFUNC*( yR2 - yR1 );\n \nelseif tR <= (tR1+tR2) % STATE B -> A\n \n % Scaling time for appropriate use in interp. function so tRTilde\\in[0,1]\n tRTilde = (tR-tR1)/( tR2 ); \n \n % Evaluate Piecewise Cubic Interpolation Poly\n if tRTilde<=p1\n gFUNC = a0 + a1*tRTilde + a2*tRTilde^2 + a3*tRTilde^3; \n elseif tRTilde<=p2\n gFUNC = b0 + b1*tRTilde + b2*tRTilde^2 + b3*tRTilde^3; \n else\n gFUNC = c0 + c1*tRTilde + c2*tRTilde^2 + c3*tRTilde^3; \n end\n\n % MOVING X-POSITIONS\n targets(2:NArm+1,2) = xR2 + gFUNC*( xR1 - xR2 );\n \n % MOVING Y-POSITIONS\n targets(2:NArm+1,3) = yR2 + gFUNC*( yR1 - yR2 );\n \nend\n\n\n%%%%%%%%%%%%%\n%\n% LEFT ARM!\n%\n%%%%%%%%%%%%%\n\nif current_time >= off_Left\n\n if tL <= tL1 % STATE A -> STATE B\n\n % Scaling time for appropriate use in interp. function so tRTilde\\in[0,1]\n tLTilde = (tL/tL1); \n\n % Evaluate Piecewise Cubic Interpolation Poly\n if tLTilde<=p1\n gFUNC = a0 + a1*tLTilde + a2*tLTilde^2 + a3*tLTilde^3; \n elseif tRTilde<=p2\n gFUNC = b0 + b1*tLTilde + b2*tLTilde^2 + b3*tLTilde^3; \n else\n gFUNC = c0 + c1*tLTilde + c2*tLTilde^2 + c3*tLTilde^3; \n end\n\n % MOVING X-POSITIONS\n targets(NArm+2:end,2) = xL1 + gFUNC*( xL2 - xL1 );\n\n % MOVING Y-POSITIONS\n targets(NArm+2:end,3) = yL1 + gFUNC*( yL2 - yL1 );\n\n elseif tL <= (tL1+tL2) % STATE B -> A\n\n % Scaling time for appropriate use in interp. function so tRTilde\\in[0,1]\n tLTilde = (tL-tL1)/(tL2); \n\n % Evaluate Piecewise Cubic Interpolation Poly\n if tLTilde<=p1\n gFUNC = a0 + a1*tLTilde + a2*tLTilde^2 + a3*tLTilde^3; \n elseif tLTilde<=p2\n gFUNC = b0 + b1*tLTilde + b2*tLTilde^2 + b3*tLTilde^3; \n else\n gFUNC = c0 + c1*tLTilde + c2*tLTilde^2 + c3*tLTilde^3; \n end\n\n % MOVING X-POSITIONS\n targets(NArm+2:end,2) = xL2 + gFUNC*( xL1 - xL2 );\n\n % MOVING Y-POSITIONS\n targets(NArm+2:end,3) = yL2 + gFUNC*( yL1 - yL2 );\n\n end\n\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Reads in the # of vertex pts and all the vertex pts from the\n% .vertex file.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction PTS = read_In_Phase_Positions(struct_name)\n\n\nfilename = struct_name; %Name of file to read in\nfileID = fopen(filename);\n\n% Read in the file, use 'CollectOutput' to gather all similar data together\n% and 'CommentStyle' to to end and be able to skip lines in file.\nC = textscan(fileID,'%f %f %f %f','CollectOutput',1);\n\nfclose(fileID); %Close the data file.\n\nvertices = C{1}; %Stores all read in data in vertices (N+1,2) array\n\nPTS = vertices(1:end,1:4);\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_Jellyfish_Swimming/Tethered_Jellyfish/600x400/update_Target_Point_Positions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.35411021592821423}} {"text": "classdef prtRegressRvm < prtRegress\n % prtRegressRvm Relevance vector machine regression object\n %\n % REGRESS = prtRegressRvm returns a prtRegressRvm object\n %\n % REGRESS = prtRegressRVM(PROPERTY1, VALUE1, ...) constructs a\n % prtRegressRvm object REGRESS with properties as specified by\n % PROPERTY/VALUE pairs.\n % \n % A prtRegressRvm object inherits all properties from the prtRegress\n % class. In addition, it has the following properties:\n %\n % SetAccess = public:\n % kernels - A cell array of prtKernel objects specifying\n % the kernels to use\n % verbosePlot - Flag indicating whether or not to plot during\n % training\n % verboseText - Flag indicating whether or not to display\n % a message during training\n %\n % SetAccess = private/protected:\n % learningConverged - Flag indicating if the training converged\n % learningResults - Struct with information about the convergence\n % beta - The weights on each of the kernel elements;\n % learned during training\n % Sigma - The learned covariance\n % sparseBeta - The weights on the retained kernel elements;\n % learned durning training\n % sparseKernels - The retained kernels\n %\n % This code is based on:\n % Michael E Tipping, Sparse bayesian learning and the relevance \n % vector machine, The Journal of Machine Learning Research, Vol 1.\n %\n % Also see http://en.wikipedia.org/wiki/Relevance_vector_machine\n % \n % A prtRegressionRvm object inherits the PLOT method from the\n % prtRegress object, and the TRAIN, RUN, CROSSVALIDATE and KFOLDS\n % methods from the prtAction object.\n %\n % Example:\n % \n % dataSet = prtDataGenNoisySinc; % Load a prtDataRegress\n % dataSet.plot; % Display data\n % reg = prtRegressRvm; % Create a prtRegressRvm object\n % reg = reg.train(dataSet); % Train the prtRegressRvm object\n % reg.plot(); % Plot the resulting curve\n % dataSetOut = reg.run(dataSet); % Run the regressor on the data\n % hold on;\n % plot(dataSet.getX,dataSetOut.getX,'c.') % Plot, overlaying the\n % % fitted points with the \n % % curve and original data\n % legend('Regression curve','Original Points','Kernel Locations Used',0)\n %\n %\n % See also prtRegress, prtRegressGP, prtRegressLslr\n\n\n\n\n\n\n\n \n properties (SetAccess=private)\n name = 'Relevance Vector Machine' % Relevance Vector Machine\n nameAbbreviation = 'RVM' % RVM\n end\n \n properties\n kernels = prtKernelDc & prtKernelRbfNdimensionScale;\n \n verbosePlot = false; % Whether or not to plot during training\n verboseText = false; % Whether or not to plot during training\n end\n \n properties (Hidden = true)\n learningMaxIterations = 1000; % Maximum number of iteratoins\n learningConvergedTolerance = 1e-6;\n learningRelevantTolerance = 1e-3;\n end\n properties (SetAccess = 'protected',GetAccess = 'public')\n learningConverged = [];% Whether or not the training converged\n \n beta = []; % Estimated in training\n Sigma = []; % Estimated in training\n sigma2 = []; % Estimated in training\n \n sparseBeta = [];% Estimated in training\n sparseKernels = {};% Estimated in training \n end\n methods\n % Allow for string, value pairs\n function Obj = prtRegressRvm(varargin)\n Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});\n end\n \n function Obj = set.kernels(Obj,val)\n if ~isa(val,'prtKernel')\n error('prt:prtRegressRvm:kernels','kernels must be a prtKernel');\n end\n \n Obj.kernels = val;\n end\n \n function Obj = set.verbosePlot(Obj,val)\n if ~prtUtilIsLogicalScalar(val)\n error('prt:prtRegressRvm:verbosePlot','verbosePlot must be a logical value or a positive integer');\n end\n Obj.verbosePlot = val;\n end\n \n function Obj = set.verboseText(Obj,val)\n if ~prtUtilIsLogicalScalar(val)\n error('prt:prtRegressRvm:verboseText','verboseText must be a logical value or a positive integer');\n end\n Obj.verboseText = val;\n end\n end\n \n methods (Access = protected, Hidden = true)\n \n function Obj = trainAction(Obj,DataSet)\n %Rvm = trainAction(Rvm,DataSet) (Private; see prtClass\\train)\n % Implements Jefferey's prior based training of a relevance\n % vector machine. The Rvm output from this function contains\n % fields \"sparseBeta\" and \"sparseKernels\"\n \n warningState = warning;\n \n if DataSet.nTargetDimensions ~= 1\n error('prt:prtRegressRvm:tooManyTargets','prtRegressRvm can only operate on single target data.');\n end\n \n y = DataSet.getTargets(1:DataSet.nObservations,1);\n \n localKernels = Obj.kernels.train(DataSet);\n gram = localKernels.run_OutputDoubleArray(DataSet);\n nBasis = size(gram,2);\n \n if Obj.verboseText\n fprintf('RVM training with %d possible vectors.\\n', nBasis);\n end\n \n Obj.beta = zeros(nBasis,1);\n \n relevantIndices = true(nBasis,1); % Everybody!\n \n alpha = ones(nBasis,1); % Initialize\n \n Obj.sigma2 = var(y); % A descent guess to start with\n \n for iteration = 1:Obj.learningMaxIterations\n % Given currenet relevant stuff find the weight mean and\n % covariance\n if ~any(relevantIndices)\n break;\n end\n cPhi = gram(:,relevantIndices);\n A = diag(alpha(relevantIndices));\n \n sigma2Inv = (Obj.sigma2^-1);\n \n SigmaInv = A + sigma2Inv*(cPhi'*cPhi);\n Obj.Sigma = inv(SigmaInv);\n mu = sigma2Inv*(SigmaInv\\(cPhi'*y));\n \n % Find the current prediction\n yHat = cPhi*mu;\n \n % Update A\n logAlphaOld = log(alpha(relevantIndices));\n \n cG = 1 - alpha(relevantIndices).*diag(Obj.Sigma);\n alpha(relevantIndices) = cG./(mu.^2);\n \n % Update sigma2\n Obj.sigma2 = norm(y-yHat)./(length(yHat) - sum(cG));\n \n Obj.beta = zeros(nBasis,1);\n Obj.beta(relevantIndices) = mu;\n \n \n %check tolerance for basis removal\n TOL = abs(log(alpha(relevantIndices))-logAlphaOld);\n TOL(isnan(TOL)) = 0; % inf-inf = nan\n \n if Obj.verboseText\n fprintf('\\t Iteration %d: %d RV''s, Convergence tolerance: %g \\n',iteration, sum(relevantIndices), max(TOL));\n end\n \n if all(TOL < Obj.learningConvergedTolerance) && iteration > 1\n Obj.learningConverged = true;\n \n if Obj.verboseText\n fprintf('Convergence reached. Exiting...\\n\\n');\n end\n \n break;\n end\n % We didn't break so we can contiue on\n % Select relevant stuff\n newRelevantIndices = alpha < 1./Obj.learningRelevantTolerance;\n \n if ~mod(iteration,Obj.verbosePlot)\n if DataSet.nFeatures == 1\n Obj.verboseIterationPlot(DataSet,relevantIndices);\n elseif iteration == 1\n warning('prt:prtRegressRvm','Learning iteration plot can only be produced for training Datasets with 1 feature.');\n end\n end\n \n relevantIndices = newRelevantIndices;\n end\n \n if Obj.verboseText && iteration == Obj.learningMaxIterations\n fprintf('Exiting...Convergence not reached before the maximum allowed iterations was reached.\\n\\n');\n end\n \n % Make sparse represenation\n Obj.sparseBeta = Obj.beta(relevantIndices,1);\n Obj.sparseKernels = localKernels.retainKernelDimensions(relevantIndices);\n \n \n % Very bad training\n if isempty(Obj.sparseBeta)\n warning('prt:prtClassRvm:NoRelevantFeatures','No relevant features were found during training.');\n end\n \n % Reset warning\n warning(warningState);\n \n end\n \n function DataSetOut = runAction(Obj,DataSet)\n \n if isempty(Obj.sparseBeta)\n DataSetOut = DataSet.setObservations(zeros(DataSet.nObservations,Obj.dataSetSummary.nTargetDimensions));\n return\n end\n \n memChunkSize = 1000; % Should this be moved somewhere?\n n = DataSet.nObservations;\n \n DataSetOut = prtDataSetRegress(zeros(n,1));\n for i = 1:memChunkSize:n;\n cI = i:min(i+memChunkSize,n);\n cDataSet = prtDataSetRegress(DataSet.X(cI,:));\n gram = Obj.sparseKernels.run_OutputDoubleArray(cDataSet);\n \n DataSetOut = DataSetOut.setObservations(gram*Obj.sparseBeta, cI);\n end\n end\n end\n \n methods\n function varargout = plot(Obj)\n \n HandleStructure = plot@prtRegress(Obj);\n \n holdState = get(gca,'nextPlot');\n \n % Plot the kernels\n hold on\n %This only plots the x-coordinate... which is weird, but it's\n %all we can do right now b/c kernels don't know about\n %targets...\n Obj.sparseKernels.plot();\n set(gca, 'nextPlot', holdState);\n \n varargout = {};\n if nargout > 0\n varargout = {HandleStructure};\n end\n end\n end\n \n methods (Access=protected,Hidden=true)\n function Obj = verboseIterationPlot(Obj,DataSet,relevantIndices)\n DsSummary = DataSet.summarize;\n \n [linGrid, gridSize] = prtPlotUtilGenerateGrid(DsSummary.lowerBounds, DsSummary.upperBounds, Obj.plotOptions);\n \n trainedKernel = train(Obj.kernels, DataSet);\n trainedKernel = trainedKernel.retainKernelDimensions(relevantIndices);\n cPhi = trainedKernel.run_OutputDoubleArray(prtDataSetClass(linGrid));\n \n yHat = reshape(cPhi*Obj.beta(relevantIndices),gridSize);\n \n colors = Obj.plotOptions.colorsFunction(Obj.dataSetSummary.nTargetDimensions);\n lineWidth = Obj.plotOptions.lineWidth;\n plot(linGrid,yHat,'color',colors(1,:),'lineWidth',lineWidth);\n hold on\n plot(DataSet);\n plot(trainedKernel);\n hold off\n drawnow;\n end\n end\nend\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/regress/prtRegressRvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.35400923718038557}} {"text": "function g = matRad_objectiveGradient(optiProb,apertureInfoVec,dij,cst)\n% matRad IPOPT callback: gradient function for direct aperture optimization\n%\n% call\n% g = matRad_objectiveGradient(optiProb,apertureInfoVec,dij,cst)\n%\n% input\n% optiProb: option struct defining the type of optimization\n% apertureInfoVect: aperture info in form of vector\n% dij: matRad dij struct as generated by bixel-based dose calculation\n% cst: matRad cst struct\n%\n% output\n% g: gradient\n%\n% References\n% [1] http://dx.doi.org/10.1118/1.4914863\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% update apertureInfo, bixel weight vector an mapping of leafes to bixels\nif ~isequal(apertureInfoVec,optiProb.apertureInfo.apertureVector)\n optiProb.apertureInfo = optiProb.matRad_daoVec2ApertureInfo(optiProb.apertureInfo,apertureInfoVec);\nend\napertureInfo = optiProb.apertureInfo;\n\n% bixel based gradient calculation\nbixelG = matRad_objectiveGradient@matRad_OptimizationProblem(optiProb,apertureInfo.bixelWeights,dij,cst);\n \n% allocate gradient vector for aperture weights and leaf positions\ng = NaN * ones(size(apertureInfoVec,1),1);\n\n% 1. calculate aperatureGrad\n% loop over all beams\noffset = 0;\nfor i = 1:numel(apertureInfo.beam)\n\n % get used bixels in beam\n ix = ~isnan(apertureInfo.beam(i).bixelIndMap);\n\n % loop over all shapes and add up the gradients x openingFrac for this shape\n for j = 1:apertureInfo.beam(i).numOfShapes \n g(j+offset) = apertureInfo.beam(i).shape(j).shapeMap(ix)' ...\n * bixelG(apertureInfo.beam(i).bixelIndMap(ix));\n end\n\n % increment offset\n offset = offset + apertureInfo.beam(i).numOfShapes;\n\nend\n\n% 2. find corresponding bixel to the leaf Positions and aperture \n% weights to calculate the gradient\ng(apertureInfo.totalNumOfShapes+1:end) = ...\n apertureInfoVec(apertureInfo.mappingMx(apertureInfo.totalNumOfShapes+1:end,2)) ...\n .* bixelG(apertureInfo.bixelIndices(apertureInfo.totalNumOfShapes+1:end)) / apertureInfo.bixelWidth;\n\n% correct the sign for the left leaf positions\ng(apertureInfo.totalNumOfShapes+1:apertureInfo.totalNumOfShapes+apertureInfo.totalNumOfLeafPairs) = ...\n -g(apertureInfo.totalNumOfShapes+1:apertureInfo.totalNumOfShapes+apertureInfo.totalNumOfLeafPairs);\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/optimization/@matRad_OptimizationProblemDAO/matRad_objectiveGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3536891935609101}} {"text": "function DCM = VBA_spm_dcm_test(DCM)\n% tests whether DCM parameters are zero using Savage-Dickey ratios\n% function DCM = spm_dcm_test(DCM)\n% IN:\n% - DCM: the DCM structure\n% OUT:\n% - DCM: the DCM structure, augmented with field .sdr, which contains the\n% Savage-Dickey ratios in the same format as DCM.Ep\n\nn = size(DCM.Ep.A,1);\nnu = size(DCM.Ep.C,2);\n\nE = VBA_spm_vec(DCM.Ep);\nV = DCM.Cp;\nE0 = VBA_spm_vec(DCM.M.pE);\nV0 = DCM.M.pC;\n\nsdr.A = zeros(n,n);\nfor i=1:n\n for j=1:n\n % 0- identify param index in DCM.Cp\n tmp = DCM.Vp;\n tmp.A(i,j) = 0;\n ind = find(full(VBA_spm_vec(tmp))~=full(VBA_spm_vec(DCM.Vp)));\n % 1- define reduced model\n E0r = E0;\n E0r(ind) = 0;\n V0r = V0;\n V0r(ind,:) = 0;\n V0r(:,ind) = 0;\n % 2- call Savage-Dickey ratios\n if isempty(ind) % this param was fixed\n if isequal(E0,E0r)\n dF = Inf;\n else\n dF = -Inf;\n end\n else\n dF = VBA_spm_log_evidence(E,V,E0,V0,E0r,V0r);\n end\n % 3- store Bayes factor\n sdr.A(i,j) = 1./(1+exp(dF));\n end\nend\n\nsdr.B = zeros(n,n,nu);\nfor i=1:n\n for j=1:n\n for k=1:nu\n tmp = DCM.Vp;\n tmp.B(i,j,k) = 0;\n ind = find(full(VBA_spm_vec(tmp))~=full(VBA_spm_vec(DCM.Vp)));\n E0r = E0;\n E0r(ind) = 0;\n V0r = V0;\n V0r(ind,:) = 0;\n V0r(:,ind) = 0;\n if isempty(ind) % this param was fixed\n if isequal(E0,E0r)\n dF = Inf;\n else\n dF = -Inf;\n end\n else\n dF = VBA_spm_log_evidence(E,V,E0,V0,E0r,V0r);\n end\n sdr.B(i,j,k) = 1./(1+exp(dF));\n end\n end\nend\n\n\nsdr.C = zeros(n,nu);\nfor i=1:n\n for j=1:nu\n tmp = DCM.Vp;\n tmp.C(i,j) = 0;\n ind = find(full(VBA_spm_vec(tmp))~=full(VBA_spm_vec(DCM.Vp)));\n E0r = E0;\n E0r(ind) = 0;\n V0r = V0;\n V0r(ind,:) = 0;\n V0r(:,ind) = 0;\n if isempty(ind) % this param was fixed\n if isequal(E0,E0r)\n dF = Inf;\n else\n dF = -Inf;\n end\n else\n dF = VBA_spm_log_evidence(E,V,E0,V0,E0r,V0r);\n end\n sdr.C(i,j) = 1./(1+exp(dF));\n end\nend\n\nnD = size(DCM.Ep.D,3);\nif nD > 0\n for i=1:n\n for j=1:n\n for k=1:n\n tmp = DCM.Vp;\n tmp.D(i,j,k) = 0;\n ind = find(full(VBA_spm_vec(tmp))~=full(VBA_spm_vec(DCM.Vp)));\n E0r = E0;\n E0r(ind) = 0;\n V0r = V0;\n V0r(ind,:) = 0;\n V0r(:,ind) = 0;\n if isempty(ind) % this param was fixed\n if isequal(E0,E0r)\n dF = Inf;\n else\n dF = -Inf;\n end\n else\n dF = VBA_spm_log_evidence(E,V,E0,V0,E0r,V0r);\n end\n sdr.D(i,j,k) = 1./(1+exp(dF));\n end\n end\n end\nend\n\n\nDCM.sdr = sdr;\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/thrid-party/spm/VBA_spm_dcm_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.35368363441886713}} {"text": "function [g1, g2] = ggwhiteXggwhiteKernGradient(ggwhiteKern1, ggwhiteKern2, ...\n x, x2, covGrad)\n\n% GGWHITEXGGWHITEKERNGRADIENT Compute a cross gradient between two GG WHITE kernels.\n% FORMAT\n% DESC computes cross gradient of parameters of a cross kernel between two\n%\tgg white kernels for the multiple output kernel.\n% RETURN g1 : gradient of the parameters of the first kernel, for ordering\n%\t see ggwhiteKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for ordering\n%\t see ggwhiteKernExtractParam.\n% ARG ggwhiteKern1 : the kernel structure associated with the first GG white\n%\t kernel.\n% ARG ggwhiteKern2 : the kernel structure associated with the second GG white\n%\t kernel.\n% ARG x : inputs for which kernel is to be computed.\n% ARG covgrad : gradient of the objective function with respect to the\n%\t elements of the cross kernel matrix.\n%\n% FORMAT\n% DESC computes cross kernel terms between two GG WHITE kernels for the multiple\n%\toutput kernel.\n% RETURN g1 : gradient of the parameters of the first kernel, for ordering\n%\t see ggwhiteKernExtractParam.\n% RETURN g2 : gradient of the parameters of the second kernel, for ordering\n%\t see ggwhiteKernExtractParam.\n% ARG ggwhiteKern1 : the kernel structure associated with the first GG WHITE\n%\t kernel.\n% ARG ggwhiteKern2 : the kernel structure associated with the second GG WHITE\n%\t kernel.\n% ARG x : row inputs for which kernel is to be computed.\n% ARG x2 : column inputs for which kernel is to be computed.\n% ARG covgrad : gradient of the objective function with respect to the\n%\t elements of the cross kernel matrix.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, ggwhiteKernParamInit,\n% ggwhiteKernExtractParam\n%\n% COPYRIGHT : Mauricio A. Alvarez and Neil D. Lawrence, 2008\n%\n% MODIFICATIONS : Mauricio A. Alvarez, 2009.\n\n% KERN\n\nif nargin < 5\n covGrad = x2;\n x2 = x;\nend\n\n[K, Pinv, Lqrinv, Lsrinv, Kbase, factorNoise, factorVar1, factorVar2, dist] = ...\n ggwhiteXggwhiteKernCompute(ggwhiteKern1, ggwhiteKern2, x, x2);\nP = 1./Pinv;\n\nif ggwhiteKern1.isArd\n matGradLqr = zeros(ggwhiteKern1.inputDimension,1);\n matGradLsr = zeros(ggwhiteKern1.inputDimension,1);\n for i=1:ggwhiteKern1.inputDimension\n X = repmat(x(:,i),1, size(x2,1));\n X2 = repmat(x2(:,i)',size(x,1),1);\n X_X2 = (X - X2).*(X - X2);\n matGradLqr(i) = sum(sum(0.5*covGrad.*K.*...\n (-0.5*Lqrinv(i) + Lqrinv(i)*P(i)*Lqrinv(i) - Lqrinv(i)*P(i)*X_X2*P(i)*Lqrinv(i) )));\n matGradLsr(i) = sum(sum(0.5*covGrad.*K.*...\n (-0.5*Lsrinv(i) + Lsrinv(i)*P(i)*Lsrinv(i) - Lsrinv(i)*P(i)*X_X2*P(i)*Lsrinv(i) )));\n end\nelse \n matGradLqr = sum(sum(0.5*covGrad.*K.*( -0.5*ggwhiteKern1.inputDimension*Lqrinv...\n + ((P*Lqrinv)^2)*(ggwhiteKern1.inputDimension*Pinv - dist)) ));\n matGradLsr = sum(sum(0.5*covGrad.*K.*( -0.5*ggwhiteKern1.inputDimension*Lsrinv...\n + ((P*Lsrinv)^2)*(ggwhiteKern1.inputDimension*Pinv - dist)) ));\nend\ngrad_sigma2Noise = factorNoise*sum(sum(covGrad.*Kbase));\ngrad_variance1 = factorVar1*sum(sum(covGrad.*Kbase));\ngrad_variance2 = factorVar2*sum(sum(covGrad.*Kbase));\n% only pass the gradient with respect to the inverse width to one\n% of the gradient vectors ... otherwise it is counted twice.\ng1 = [matGradLqr(:)' grad_sigma2Noise grad_variance1];\n%g1 = [matGradLqr(:)' 0 grad_variance1];\ng2 = [matGradLsr(:)' 0 grad_variance2];\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/ggwhiteXggwhiteKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3536836284865028}} {"text": "function [g, model] = vargplvmPointLogLikeGradient(model, vardistx, y)\n% VARGPLVMPOINTLOGLIKEGRADIENT Log-likelihood gradient for of some points of the GP-LVM.\n% FORMAT\n% DESC returns the gradient of the log likelihood with respect to\n% the latent positions, where the log likelihood is conditioned on\n% the training set. The function works even when we are interested only in\n% one point. See vargplvmPointLogLikelihood for more details.\n% ARG model : the model for which the gradient computation is being\n% done.\n% ARG x : the latent positions where the gradient is being computed.\n% ARG y : the positions in data space for which the computation is\n% being done.\n% RETURN g : the gradient of the log likelihood, conditioned on the\n% training data, with respect to the latent position.\n%\n% SEEALSO : vargplvmPointLogLikelihood, vargplvmOptimisePoint, vagplvmSequenceLogLikeGradient\n%\n% COPYRIGHT : Michalis K. Titsias and Neil D. Lawrence, 2009, 2011\n% COPYRIGHT : Andreas C. Damianou, 2011\n% VARGPLVM\n\n\nif isfield(model, 'dynamics') && ~isempty(model.dynamics)\n dynUsed = 1;\nelse\n dynUsed = 0;\nend\n\nindexMissing = find(isnan(y(1,:)));\nindexPresent = setdiff(1:model.d, indexMissing);\ny = y(:,indexPresent);\n\n\nif dynUsed\n % use a special function\n [g, model] = dynPointLogLikeGradient(model, vardistx, y, indexPresent, indexMissing);\n % g = g(:)'; %%% RE-OPT-CODE-REM\n return;\nend\n\n\n\n% normalize y exactly as model.m is normalized\nmy = y - repmat(model.bias(indexPresent),size(y,1),1);\nmy = my./repmat(model.scale(indexPresent),size(y,1),1);\n\n[gPsi0, gPsi1, gPsi2] = vargpCovGrads(model, vardistx, my, indexPresent);\n\n[gKern1, gVarmeans1, gVarcovs1] = kernVardistPsi1Gradient(model.kern, vardistx, model.X_u, gPsi1');\n[gKern2, gVarmeans2, gVarcovs2] = kernVardistPsi2Gradient(model.kern, vardistx, model.X_u, gPsi2);\n[gKern0, gVarmeans0, gVarcovs0] = kernVardistPsi0Gradient(model.kern, vardistx, gPsi0);\n\ngVarcovs0 = (gVarcovs0(:).*vardistx.covars(:))';\ngVarcovs1 = (gVarcovs1(:).*vardistx.covars(:))';\ngVarcovs2 = (gVarcovs2(:).*vardistx.covars(:))';\n\n% KL divergence terms\ngVarmeansKL = - vardistx.means(:)';\n% !!! the covars are optimized in the log space\ngVarcovsKL = 0.5 - 0.5*vardistx.covars(:)';\n\ngVarmeans = gVarmeans0 + gVarmeans1 + gVarmeans2 + gVarmeansKL;\ngVarcovs = gVarcovs0 + gVarcovs1 + gVarcovs2 + gVarcovsKL;\n\ng = [gVarmeans gVarcovs];\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --------------------------------------------------------\nfunction [gPsi0, gPsi1, gPsi2] = vargpCovGrads(model, vardistx, my, indexPresent)\n%\n%\n\nd = prod(size(indexPresent));\n\n% change the data (by including the new point and taking only the present indices)\nmodel.m = model.m(:,indexPresent);\nmodel.m = [my; model.m];\n\npointPsi1 = kernVardistPsi1Compute(model.kern, vardistx, model.X_u);\npointPsi2 = kernVardistPsi2Compute(model.kern, vardistx, model.X_u);\n\nmodel.Psi1 = [pointPsi1; model.Psi1];\n\nmodel.C = model.invLm * (model.Psi2 + pointPsi2) * model.invLmT;\nmodel.TrC = sum(diag(model.C)); % Tr(C)\nmodel.At = (1/model.beta) * eye(size(model.C,1)) + model.C;\nmodel.Lat = jitChol(model.At)';\nmodel.invLat = model.Lat\\eye(size(model.Lat,1));\nmodel.invLatT = model.invLat';\nmodel.logDetAt = 2*(sum(log(diag(model.Lat)))); % log |At|\nmodel.P1 = model.invLat * model.invLm; % M x M\nmodel.P = model.P1 * (model.Psi1' * model.m);\nmodel.TrPP = sum(sum(model.P .* model.P));\nmodel.B = model.P1' * model.P;\nP1TP1 = (model.P1' * model.P1);\nTb = (1/model.beta) * d * P1TP1;\nTb = Tb + (model.B * model.B');\nmodel.T1 = d * model.invK_uu - Tb;\n\ngPsi2 = (model.beta/2) * model.T1;\n\ngPsi0 = -0.5 * model.beta * d;\n\ngPsi1 = model.beta*(P1TP1*model.Psi1'*model.m*my');\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --------------------------------------------------------\nfunction [gPointDyn, model] = dynPointLogLikeGradient(model, vardistx, y, indexPresent, indexMissing)\njitter = 1e-6;\n\n%%% RE-OPT-CODE-NEW_\nif isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise\n % In this case the inducing points and theta_t are optimised and\n % since updateStats is not called, any computations which need X_u\n % or theta_t must be done here.\n model = vargplvmDynamicsUpdateStats(model);\n model.K_uu = kernCompute(model.kern, model.X_u);\n model.K_uu = model.K_uu ...\n + sparseDiag(repmat(jitter, size(model.K_uu, 1), 1));\n model.Lm = jitChol(model.K_uu)';\n model.invLm = model.Lm\\eye(model.k);\n model.invLmT = model.invLm';\n model.invK_uu = model.invLmT * model.invLm;\nend %%% _RE-OPT-CODE-NEW\n\n%%%%%%%%% Only the missing parts and from the training data only\nmOrig = model.m;\nvardistDynTemp = model.dynamics.vardist;\n\nN = model.N;\nNstar = size(y,1);\nKt = zeros(N+Nstar, N+Nstar);\n\n\n%model.y = model.y(:,indexMissing);\nmodel.m = model.m(:,indexMissing);\nmodel.d = prod(size(indexMissing));\n% Augment the time vector to include the timestamp of the new point\nmodel.dynamics.t = [model.dynamics.t; model.dynamics.t_star];\n% Augment the reparametrized variational parameters mubar and lambda\nmodel.dynamics.vardist.means = [model.dynamics.vardist.means; vardistx.means];\nmodel.dynamics.vardist.covars = [model.dynamics.vardist.covars; vardistx.covars];\nmodel.dynamics.N = model.dynamics.N + Nstar;\nmodel.vardist.numData = model.dynamics.N;\nmodel.dynamics.vardist.numData = model.dynamics.N;\nmodel.vardist.nParams = 2*prod(size(model.dynamics.vardist.means));\nmodel.dynamics.vardist.nParams = 2*prod(size(model.dynamics.vardist.means));\n%model.dynamics.seq = model.dynamics.N; %%%%%% Chec\n% Faster computation of the Kt matrix\n% (all this could have been avoided as Kt is constant... we need to do these\n% precomputations outside of this function)\n% construct Kt\nKt(1:N,1:N) = model.dynamics.Kt;\n% new diagonal block\nKt(N+1:end, N+1:end) = kernCompute(model.dynamics.kern, model.dynamics.t_star);\n% cross block\nif ~isfield(model.dynamics, 'seq') || isempty(model.dynamics.seq)\n Kt(1:N, N+1:end) = kernCompute(model.dynamics.kern, model.dynamics.t(1:N), model.dynamics.t_star);\n Kt(N+1:end, 1:N) = Kt(1:N, N+1:end)';\nend\nmodel.dynamics.Kt = Kt;\nmodel.dynamics.fixedKt = 1;\nmodel = vargpTimeDynamicsUpdateStats(model);\n\nvardist2 = model.vardist;\nvardist2.means = model.vardist.means(1:end-Nstar,:);\nvardist2.covars = model.vardist.covars(1:end-Nstar,:);\nvardist2.nParams = 2*prod(size(vardist2.means));\nvardist2.numData = size(vardist2.means,1);\nmodel.Psi0 = kernVardistPsi0Compute(model.kern, vardist2);\nmodel.Psi1 = kernVardistPsi1Compute(model.kern, vardist2, model.X_u);\nmodel.Psi2 = kernVardistPsi2Compute(model.kern, vardist2, model.X_u);\n\nmodel.C = model.invLm * model.Psi2 * model.invLmT;\n%model.TrC = sum(diag(model.C)); % Tr(C)\nmodel.At = (1/model.beta) * eye(size(model.C,1)) + model.C; % At = beta^{-1} I + C\nmodel.Lat = jitChol(model.At)';\nmodel.invLat = model.Lat\\eye(size(model.Lat,1));\n%model.invLatT = model.invLat';\n%model.logDetAt = 2*(sum(log(diag(model.Lat)))); % log |At|\nmodel.P1 = model.invLat * model.invLm; % M x M\nmodel.P = model.P1 * (model.Psi1' * model.m);\n%model.TrPP = sum(sum(model.P .* model.P));\nmodel.B = model.P1' * model.P;\n%model.invK_uu = model.invLmT * model.invLm;\nTb = (1/model.beta) * model.d * (model.P1' * model.P1);\nTb = Tb + (model.B * model.B');\nmodel.T1 = model.d * model.invK_uu - Tb;\n\nmodelTmp = model;\nmodelTmp.vardist = vardist2;\nmodelTmp.dynamics.vardist = vardistDynTemp;\nmodelTmp.dynamics.Kt = modelTmp.dynamics.Kt(1:end-Nstar,1:end-Nstar);\nmodelTmp.dynamics.N = N;\nmodelTmp.dynamics.t = modelTmp.dynamics.t(1:end-Nstar);\nmodelTmp.dynamics.vardist.numData = modelTmp.dynamics.N; %%%% new...\nmodelTmp.vardist.numData = modelTmp.N;%%%% new...\n%modelTmp.TrYY = sum(sum(model.m .* model.m));\n\n\n\n% GRADIENT OF THE LL1 TERM mu,S from the training data\n\n% To understand the following code it's helpful to see\n% vargpTimeDynamicsPriorReparamGrads.m; LL1 term now is not computed\n% together with KL so we cannot use that function here; however, it does\n% contain theta_t so these computations must be done but only for the part\n% corresponding to modelTmp. Thus, the following code actually is a copy of\n% vargpTimeDynamicsPriorReparamGrads but is applied only on the appropriate\n% part of Kt.\n% i.e: gPointDyn1Tmp(:,1:model.dynamics.q) -> gVarmeansLik\n% gPointDyn1Tmp(:,model.dynamics.q+q) -> gVarcovsLik(:,q)\n\n%gPointDyn1 = zeros(Nstar,modelTmp.dynamics.q*2);\ngPointDyn1 = zeros(N+Nstar,modelTmp.dynamics.q*2);\nif ~isempty(indexMissing)\n if isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise %%% RE-OPT-CODE-NEW\n % gDynKern will be empty in that case (includeKL is 0) %%% RE-OPT-CODE-NEW\n [gPointDyn1Tmp, gDynKern, gInd1]= vargplvmLogLikeGradientsVar1(modelTmp, 0); %%% RE-OPT-CODE-NEW\n sumTrGradKL = 0; %%% RE-OPT-CODE-NEW\n else %%% RE-OPT-CODE-NEW\n gPointDyn1Tmp = vargplvmLogLikeGradientsVar1(modelTmp, 0);\n end %%% RE-OPT-CODE-NEW\n gPointDyn1Tmp = reshape(gPointDyn1Tmp, modelTmp.dynamics.vardist.numData, modelTmp.dynamics.q*2);\n \n % means (Note: Kt(1:N,:)' == Kt(:,1:N) )\n gPointDyn1(:,1:modelTmp.dynamics.q) = model.dynamics.Kt(1:N,:)'*gPointDyn1Tmp(:,1:model.dynamics.q);\n \n % covars\n %gcovTmp = zeros(Nstar,modelTmp.dynamics.q);\n gcovTmp = zeros(N+Nstar,modelTmp.dynamics.q); \n sumTrGradKL1 = zeros(N+Nstar,N); \n sumTrGradKL2 = zeros(N+Nstar, N+Nstar); \n for q=1:model.dynamics.q\n LambdaH_q = model.dynamics.vardist.covars(:,q).^0.5;\n Bt_q = eye(model.dynamics.N) + LambdaH_q*LambdaH_q'.*model.dynamics.Kt;\n % Invert Bt_q\n Lbt_q = jitChol(Bt_q)';\n G1 = Lbt_q \\ diag(LambdaH_q);\n G = G1*model.dynamics.Kt;\n % Find Sq\n Sq = model.dynamics.Kt - G'*G;\n Sq = - (Sq .* Sq);\n \n % only the cross matrix is needed as in barmu case\n %gcovTmp(:,q) = Sq(1:N,N+1:end)'*gPointDyn1Tmp(:,model.dynamics.q+q);\n \n % gPointDyn1Tmp contains [means covars]. model.dynamics.q+q gives\n % us only the covars.\n gcovTmp(:,q) = Sq(1:N,:)'*gPointDyn1Tmp(:,model.dynamics.q+q);\n \n %%% RE-OPT-CODE-NEW_ \n if isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise\n % Find the coefficient for the grad. wrt theta_t (params of Kt)\n G1T=G1';\n Bhat=G1T*G1;\n BhatKt=G1T*G;\n \n \n IBK = eye(model.dynamics.N) - BhatKt;\n\n diagVarcovs = repmat(gPointDyn1Tmp(:,model.dynamics.q+q)', model.dynamics.N,1); \n sumTrGradKL2 = sumTrGradKL2 + (IBK(:,1:N).*diagVarcovs)*IBK(:,1:N)';\n \n %%%\n % tmp = [gPointDyn1Tmp(:,model.dynamics.q+q)' zeros(1,Nstar)]; %tmp\n % tmp2=IBK*diag(tmp)*IBK'; %tmp\n % sumTrGradKL2 = sumTrGradKL2 + tmp2; % tmp\n %%% \n\n \n \n sumTrGradKL1 = sumTrGradKL1 + model.dynamics.vardist.means(:,q)*gPointDyn1Tmp(:,q)';\n %if ~isempty(gInd)\n % trGradKL = trGradKL + dynModel.vardist.means(:,q) * gInd(:,q)';\n %end\n end\n %%% _RE-OPT-CODE-NEW\n end\n \n gPointDyn1(:,(modelTmp.dynamics.q+1):(modelTmp.dynamics.q*2)) = gcovTmp;\n \n if isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise %%% RE-OPT-CODE-NEW\n gDynKern1 = kernGradient(model.dynamics.kern, model.dynamics.t, model.dynamics.t(1:N), sumTrGradKL1) ; %%% RE-OPT-CODE-NEW\n gDynKern1 = gDynKern1 + kernGradient(model.dynamics.kern, model.dynamics.t, sumTrGradKL2); %%% RE-OPT-CODE-NEW\n end %%% RE-OPT-CODE-NEW\n \nend\n\n\n% GRADIENT FOR LL2 plus KL TERMS\n%\nmodel.m = mOrig;\n% normalize y exactly as model.m is normalized\nmy = y - repmat(model.bias(indexPresent), Nstar, 1);\nmy = my./repmat(model.scale(indexPresent), Nstar, 1);\nmodel.m = model.m(:,indexPresent);\nmodel.m = [model.m; my];\nmodel.N = model.N + Nstar;\nd = prod(size(indexPresent));\nmodel.d = d;\nmodel.dynamics.nParams = model.dynamics.nParams + 2*prod(size(vardistx.means));\nmodel.nParams = model.nParams + 2*prod(size(vardistx.means));\n\nvardist2 = model.vardist;\nvardist2.means = model.vardist.means(end-Nstar+1:end,:);\nvardist2.covars = model.vardist.covars(end-Nstar+1:end,:);\nvardist2.nParams = 2*prod(size(vardist2.means));\nvardist2.numData = size(vardist2.means,1);\npointPsi0 = kernVardistPsi0Compute(model.kern, vardist2);\npointPsi1 = kernVardistPsi1Compute(model.kern, vardist2, model.X_u);\npointPsi2 = kernVardistPsi2Compute(model.kern, vardist2, model.X_u);\nmodel.Psi1 = [model.Psi1; pointPsi1];\nmodel.Psi2 = model.Psi2 + pointPsi2;\nmodel.Psi0 = model.Psi0 + pointPsi0;\n\nmodel.C = model.invLm * model.Psi2 * model.invLmT;\n%model.TrC = sum(diag(model.C)); % Tr(C)\nmodel.At = (1/model.beta) * eye(size(model.C,1)) + model.C; % At = beta^{-1} I + C\nmodel.Lat = jitChol(model.At)';\nmodel.invLat = model.Lat\\eye(size(model.Lat,1));\n%model.invLatT = model.invLat';\n%model.logDetAt = 2*(sum(log(diag(model.Lat)))); % log |At|\nmodel.P1 = model.invLat * model.invLm; % M x M\nmodel.P = model.P1 * (model.Psi1' * model.m);\n%model.TrPP = sum(sum(model.P .* model.P));\nmodel.B = model.P1' * model.P;\n%model.invK_uu = model.invLmT * model.invLm;\nTb = (1/model.beta) * model.d * (model.P1' * model.P1);\nTb = Tb + (model.B * model.B');\nmodel.T1 = model.d * model.invK_uu - Tb;\n\nif isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise %%% RE-OPT-CODE-NEW\n [gPointDyn2, gDynKern2, gInd2] = vargplvmLogLikeGradientsVar1(model,1); %%% RE-OPT-CODE-NEW\nelse %%% RE-OPT-CODE-NEW\n gPointDyn2 = vargplvmLogLikeGradientsVar1(model,1);\nend %%% RE-OPT-CODE-NEW\n\ngPointDyn2 = reshape(gPointDyn2, model.dynamics.vardist.numData, model.dynamics.q*2);\n%gPointDyn2 = gPointDyn2(N+1:end,:);\n\ngPointDyn = gPointDyn1 + gPointDyn2;\n\n%%% RE-OPT-CODE-NEW_\ngPointDyn = gPointDyn(:)';\nif isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise\n gDynKern = gDynKern1 + gDynKern2;\n gInd = gInd1 + gInd2;\n if strcmp(model.dynamics.kern.comp{1}.type,'rbf') || strcmp(model.dynamics.kern.comp{1}.type,'matern32')\n if ~isfield(model.dynamics, 'learnVariance') || ~model.dynamics.learnVariance\n gDynKern(2) = 0;\n end\n end\n gPointDyn = [gPointDyn 0*gDynKern gInd]; %%%%%%%%%% TEMP!!!!\nend\n%%% _RE-OPT-CODE-NEW\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --------------------------------------------------------\n%function gVar = vargplvmLogLikeGradientsVar1(model, includeKL) %%% RE-OPT-CODE-REM\nfunction [gVar, gDynKern, gInd] = vargplvmLogLikeGradientsVar1(model, includeKL) %%% RE-OPT-CODE-NEW\n% Like vargplvmLogLikeGradients but only for the variational parameters (ehm, not exactly). %%% RE-OPT-CODE-MOD\n\n\n% Likelihood terms (coefficients)\ngPsi1 = model.beta * model.m * model.B';\ngPsi1 = gPsi1'; % because it is passed to \"kernVardistPsi1Gradient\" as gPsi1'...\ngPsi2 = (model.beta/2) * model.T1;\ngPsi0 = -0.5 * model.beta * model.d;\n\n[gKern1, gVarmeans1, gVarcovs1, gInd1] = kernVardistPsi1Gradient(model.kern, model.vardist, model.X_u, gPsi1');\n[gKern2, gVarmeans2, gVarcovs2, gInd2] = kernVardistPsi2Gradient(model.kern, model.vardist, model.X_u, gPsi2);\n[gKern0, gVarmeans0, gVarcovs0] = kernVardistPsi0Gradient(model.kern, model.vardist, gPsi0);\n\ngVarmeansLik = gVarmeans0 + gVarmeans1 + gVarmeans2;\n\ngVarcovsLik = gVarcovs0 + gVarcovs1 + gVarcovs2;\nif includeKL\n %[gVarmeans gVarcovs gDynKern] = modelPriorReparamGrads(model.dynamics, gVarmeansLik, gVarcovsLik);\n % TODO: This may have to be changed if we have model.fixInducing==1.\n [gVarmeans gVarcovs gDynKern] = modelPriorReparamGrads(model.dynamics, gVarmeansLik, gVarcovsLik,[]);\nelse\n dynModel = model.dynamics;\n gVarmeansLik = reshape(gVarmeansLik,dynModel.N,dynModel.q);\n gVarcovsLik = reshape(gVarcovsLik,dynModel.N,dynModel.q);\n gVarmeans = gVarmeansLik;\n gVarcovs = gVarcovsLik;\n \n gVarcovs = gVarcovs(:)';\n gVarmeans = gVarmeans(:)';\nend\n\ngVarcovs = (gVarcovs(:).*model.dynamics.vardist.covars(:))';\ngVar = [gVarmeans gVarcovs];\n\n%%% RE-OPT-CODE-NEW_\nif isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise\n % Compute Gradients with respect to X_u\n gK_uu = 0.5 * (model.T1 - (model.beta * model.d) * model.invLmT * model.C * model.invLm);\n gKX = kernGradX(model.kern, model.X_u, model.X_u);\n gKX = gKX*2;\n dgKX = kernDiagGradX(model.kern, model.X_u);\n for i = 1:model.k\n gKX(i, :, i) = dgKX(i, :);\n end\n gX_u = zeros(model.k, model.q);\n for i = 1:model.k\n for j = 1:model.q\n gX_u(i, j) = gKX(:, j, i)'*gK_uu(:, i);\n end\n end\n gInd = gInd1 + gInd2 + gX_u(:)';\n if ~includeKL\n gDynKern = [];\n end\nend\n%%% _RE-OPT-CODE-NEW\n\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/vargplvmPointLogLikeGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3536276786508946}} {"text": " function ob = Gblur2(mask, varargin)\n%function ob = Gblur(mask, options)\n%|\n%| Construct Gblur object for image restoration.\n%|\n%| See Gblur_test.m for example usage.\n%|\n%| in\n%|\tmask\tsize(image)\tlogical array of object support.\n%|\n%| options\n%|\t'chat'\t\tverbose printing of debug messages\n%|\t'psf'\t\tpoint spread function (aka impulse response)\n%|\t'type'\t\ttype of blur:\n%|\t\t\t\t'conv,same'\tusual case (default)\n%|\t\t\t\t'conv,per'\t(periodic end conditions)\n%|\t\t\t\t'fft,same'\t(periodic end conditions)\n%|\t\t\t\ttodo: allow replicated end conditions!\n%|\t\t\t\t'imfilter,same'\t(requires image toolbox)\n%|\t\t\t\t'imfilter,circ'\t(requires image toolbox)\n%|\t\t\t\t'imfilter,mirror' (requires image toolbox)\n%|\t\t\t\t\t(do not use - adjoint fails)\n%|\t\t\t\t'sparse'\ttodo: return sparse matrix\n%|\t'imfilter_options'\toptions to 'imfilter' (if used)\n%|\n%| out\n%|\tob [nd np]\tnp = sum(mask(:)), so it is already \"masked\"\n%|\t\t\tnd = prod(size(mask)) for 'conv,same' type\n%|\n%| Copyright 2005-4-22, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(mask, 'test'), Gblur_test, return, end\nif nargin < 1, help(mfilename), error(mfilename), end\n\narg.mask = mask;\n\n% option defaults\narg.chat = 0;\narg.psf = 1; % identity matrix\narg.type = 'conv,same';\narg.class = 'fatrix2';\narg.imfilter_options = {};\n\n% options specified by name/value pairs\narg = vararg_pair(arg, varargin);\n\nif ndims(arg.psf) ~= ndims(mask), error 'psf dim mismatch', end\nif any(size(arg.psf) > size(mask)), error 'psf too large', end\n\nif streq(arg.type, 'imfilter,circ') && exist('imfilter') ~= 2\n\twarn 'no imfilter (no image processing toolbox) so using fft'\n\targ.type = 'fft,same';\nend\n\nif streq(arg.type, 'imfilter,mirror') && exist('imfilter') ~= 2\n\tfail 'no imfilter (no image processing toolbox)'\nend\n\nif streq(arg.type, 'imfilter,same') && exist('imfilter') ~= 2\n\twarn 'no imfilter (no image processing toolbox) so using slower convn'\n\targ.type = 'conv,same';\nend\n\narg.psf = Gblur_mask_psf_odd(arg.psf);\n\npsf_flip = conj(flipdims2(arg.psf, 'odd', 1));\ndoes_many = false;\n\nswitch arg.type\n\ncase 'conv,same'\n\targ.odim = size(mask);\n\targ.psf_flip = psf_flip;\n\thandle_forw = @(arg,x) convn(x, arg.psf, 'same');\n\thandle_back = @(arg,y) fatrix2_maskit(arg.mask, ...\n\t\t\tconvn(y, arg.psf_flip, 'same'));\n\tdoes_many = true;\n\ncase 'conv,per'\n\targ.odim = size(mask);\n\targ.psf_flip = psf_flip;\n\thandle_forw = @(arg,x) ir_conv(x, arg.psf, 'per', true);\n\thandle_back = @(arg,y) fatrix2_maskit(arg.mask, ...\n\t\t\tir_conv(y, arg.psf_flip, 'per', true));\n\ncase 'fft,same'\n\targ.odim = size(mask);\n\t[arg, handle_forw, handle_back] = Gblur_setup_fft_same(arg);\n\ncase 'imfilter,circ'\n\targ.odim = size(mask);\n\targ.psf_flip = psf_flip;\n\thandle_forw = @(arg,x) imfilter(x, arg.psf, 'conv', 'same', ...\n\t\t'circular', arg.imfilter_options{:});\n\thandle_back = @(arg,y) fatrix2_maskit(arg.mask, ...\n\t\t\timfilter(y, arg.psf_flip, 'conv', 'same', ...\n\t\t\t\t'circular', arg.imfilter_options{:}));\n\ncase 'imfilter,mirror'\n\targ.odim = size(mask);\n\targ.psf_flip = psf_flip;\n\thandle_forw = @(arg,x) imfilter(x, arg.psf, 'conv', 'same', ...\n\t\t'symmetric', arg.imfilter_options{:});\n\thandle_back = @(arg,y) fatrix2_maskit(arg.mask, ...\n\t\t\timfilter(y, arg.psf_flip, 'conv', 'same', ...\n\t\t\t\t'symmetric', arg.imfilter_options{:}));\n\ncase 'imfilter,same'\n\targ.odim = size(mask);\n\targ.psf_flip = psf_flip;\n\thandle_forw = @(arg,x) imfilter(x, arg.psf, 'conv', 'same', ...\n\t\targ.imfilter_options{:});\n\thandle_back = @(arg,y) fatrix2_maskit(arg.mask, ...\n\t\t\timfilter(y, arg.psf_flip, 'conv', 'same', ...\n\t\t\t\targ.imfilter_options{:}));\n\ncase 'sparse'\n\tob = Gblur_sparse(arg.psf, arg.idim);\n\tob = ob(:,arg.mask(:));\n\treturn\n\notherwise\n\terror 'unknown blur type'\nend\n\nswitch arg.class\n\ncase 'Fatrix'\n\n\targ.nd = prod(arg.odim);\n\targ.np = sum(mask(:));\n\tdim = [arg.nd arg.np]; % trick: make it masked by default!\n\n\tob = Fatrix(dim, arg, 'caller', 'Gblur', ...\n\t\t'abs', @Gblur_abs, ...\n\t\t'forw', @Gblur_forw_Fatrix, 'back', @Gblur_back_Fatrix);\n\ncase 'fatrix2'\n\n\tob = fatrix2('idim', arg.odim, 'arg', arg, 'does_many', does_many, ...\n\t\t'abs', @Gblur_abs, 'forw', handle_forw, 'back', handle_back);\n\notherwise\n\tfail('bug')\nend\n\n\n% Gblur_mask_psf_odd(psf)\n% having an odd-sized psf facilites adjoint\nfunction psf = Gblur_mask_psf_odd(psf)\nnd = ndims(psf);\nfor id=1:nd\n\tsz = size(psf, id);\n\tif ~mod(sz, 2) % even\n\t\twarn('size(psf, %d) = %d is even; appending 0', id, sz)\n\t\ttmp = size(psf);\n\t\ttmp(id) = 1;\n\t\tz = zeros(tmp);\n\t\t%psf = cat(id, psf, z);\n\t\tpsf = cat(id, z, psf);\n\tend\nend\n\n\n% Gblur_sparse()\n% a_ij = b[ n(i) - n(j), m(i) - m(j) ]\n% n(i) = (i-1) mod N\n% m(i) = floor((i-1) / N)\nfunction sp = Gblur_sparse(psf, idim)\nif numel(idim) ~= 2\n\tfail 'not done'\nend\nfail 'todo: not done'\n%sp = sparse(i, j, s, length(ii), size(ob.arg.G, 2));\n\n\n% Gblur_abs(): |A| for abs(A)\nfunction ob = Gblur_abs(ob)\nob.arg.psf = abs(ob.arg.psf);\nif isfield(ob.arg, 'psf_flip')\n\tob.arg.psf_flip = abs(ob.arg.psf_flip);\nend\nif isfield(ob.arg, 'psf_fft') % fixed 2012-04-08\n\tob.arg.psf_fft = Gblur_setup_fft_same_fft(ob.arg.psf, ob.mask);\nend\n\n\n% Gblur_setup_fft_same()\nfunction [arg, handle_forw, handle_back] = Gblur_setup_fft_same(arg)\n\narg.psf_fft = Gblur_setup_fft_same_fft(arg.psf, arg.mask);\n\nhandle_forw = @(arg,x) ifftn(fftn(x) .* arg.psf_fft);\nhandle_back = @(arg,y) fatrix2_maskit(arg.mask, ...\n\t\t\tifftn(fftn(y) .* conj(arg.psf_fft)));\n\n\n% Gblur_setup_fft_same_fft()\nfunction psf_fft = Gblur_setup_fft_same_fft(psf, mask)\n\n% % put psf in center of array\n% tmp = zeros(size(mask));\n% switch ndims(psf)\n% case 2\n% \t[n1 n2] = size(mask);\n% \t[p1 p2] = size(psf);\n% %\th1 = (size(psf,1)-1)/2;\n% %\th2 = (size(psf,2)-1)/2;\n% %\ti1 = floor(n1/2) + 1 + [-h1:h1]\n% %\ti2 = floor(n2/2) + 1 + [-h2:h2]\n% \ti1 = floor(n1/2) + 1 + (1:p1) - floor((p1+1)/2);\n% \ti2 = floor(n2/2) + 1 + (1:p2) - floor((p2+1)/2);\n% \ttmp(i1,i2) = psf;\n% case 3\n% \tif any(~rem(size(psf),2)), error 'psf size must be odd', end\n% \th1 = (size(psf,1)-1)/2;\n% \th2 = (size(psf,2)-1)/2;\n% \th3 = (size(psf,3)-1)/2;\n% \ti1 = floor(size(mask,1)/2) + 1 + [-h1:h1];\n% \ti2 = floor(size(mask,2)/2) + 1 + [-h2:h2];\n% \ti3 = floor(size(mask,3)/2) + 1 + [-h3:h3];\n% \ttmp(i1,i2,i3) = psf;\n% otherwise\n% \terror 'only 2d & 3d done'\n% end\n% psf_fft = fftn(fftshift(tmp));\n\n% pad psf with 0, and make size(psf)==size(mask)\nsz_mask = size(mask);\nsz_psf = ones(1,ndims(mask));\nfor ii=1:length(sz_psf), sz_psf(ii) = size(psf,ii); end\nif any(sz_mask>sz_psf)\n psf = padarray(psf, sz_mask-sz_psf, 'post');\nend\ncenter = ceil(sz_psf/2-1/2) + 1; % or center = floor(sz_psf/2) + 1;\npsf_fft = fftn( circshift(psf, 1-center) ); % by yusheng\n\n\n% Gblur_forw_Fatrix(): y = A * x\nfunction y = Gblur_forw_Fatrix(arg, x)\n\n[x ei] = embed_in(x, arg.mask, arg.np);\n\nswitch arg.type\ncase 'conv,same'\n\ty = convn(x, arg.psf, 'same');\ncase 'conv,per'\n\ty = ir_conv(x, arg.psf, 'per', true);\ncase 'fft,same'\n\tif ndims(x) > ndims(arg.mask);\n\t\ty = fft_conv_multi(x, arg.psf_fft);\n\telse\n\t\ty = ifftn(fftn(x) .* arg.psf_fft);\n\tend\ncase 'imfilter,circ'\n\ty = imfilter(x, arg.psf, 'conv', 'same', ...\n\t\t'circular', arg.imfilter_options{:});\ncase 'imfilter,same'\n\ty = imfilter(x, arg.psf, 'conv', 'same', arg.imfilter_options{:});\notherwise\n\terror 'bug'\nend\n\ny = ei.shape(y);\n\n\n% Gblur_back_Fatrix(): x = A' * y\nfunction x = Gblur_back_Fatrix(arg, y)\n\n[y eo] = embed_out(y, arg.odim);\n\nswitch arg.type\ncase 'conv,same'\n\tx = convn(y, arg.psf_flip, 'same');\ncase 'conv,per'\n\tx = ir_conv(y, arg.psf_flip, 'per', true);\ncase 'fft,same'\n\tif ndims(y) > ndims(arg.mask);\n\t\tx = fft_conv_multi(y, conj(arg.psf_fft));\n\telse\n\t\tx = ifftn(fftn(y) .* conj(arg.psf_fft));\n\tend\ncase 'imfilter,circ'\n\tx = imfilter(y, arg.psf_flip, 'conv', 'same', ...\n\t\t'circular', arg.imfilter_options{:});\ncase 'imfilter,same'\n\tx = imfilter(y, arg.psf_flip, 'conv', 'same', arg.imfilter_options{:});\notherwise\n\terror 'bug'\nend\n\nx = eo.shape(x, arg.mask, arg.np);\n\n\n% fft_conv_multi()\nfunction y = fft_conv_multi(x, H)\ndim = size(x);\ny = zeros(size(x));\ny = [];\nfor ii=1:dim(end)\n\ttmp = ifftn(fftn(stackpick(x, ii)) .* H);\n\ty = cat(length(dim), y, tmp); % slow: keeps enlarging y.\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/Gblur2/Gblur2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3534158944958701}} {"text": "% LOTKA-VOLTERRA system\n\nclear all, close all, clc\nfigpath = '../FIGURES/'; mkdir(figpath)\ndatapath = '../DATA/';\naddpath('../utils');\n\n%% Load Models\nModelCollection = {'DMDc','SINDYc', 'NARX'}; \nNmodels = length(ModelCollection);\nInputSignalType = 'sphs'; % prbs; chirp; noise; sine2; sphs; mixed\nTrainAlg = 'trainbr'; %trainlm,trainbr\ndep_trainlength = 1;\ndep_noise = 0;\n\n% Ntrain_vec = [5:15,20:5:95,100:100:1000];%,1500:500:3000];\n% eta_vec = 0.0;\n% Nr = 1;\n\nNtrain_vec = [5:15,20:5:95,100:100:1000,1250,1500,2000,3000];%,1500:500:3000];\neta_vec = 0.05;\nNr = 1;\n\nN_LENGTHS = length(Ntrain_vec);\n\n%% Load data\nResultsALL(N_LENGTHS,1:Nmodels) = struct('x', [], 'u', [], 't', [], 'xref', [], 'J', [], 'eval_time', []);\n\nModelName = 'DMDc';\ndatapath1 = [datapath,'EX_LOTKA_Dependencies/',ModelName,'/'];\nload(fullfile(datapath1,['EX_LOTKA_MPC_',ModelName,'_',InputSignalType,'_TrainLength','.mat']))\nResultsALL(:,1) = Results;\n\nModelName = 'SINDYc';\ndatapath1 = [datapath,'EX_LOTKA_Dependencies/',ModelName,'/'];\nload(fullfile(datapath1,['EX_LOTKA_MPC_',ModelName,'_',InputSignalType,'_TrainLength','.mat']))\nResultsALL(:,2) = Results;\n\nModelName = 'NARX';\ndatapath1 = [datapath,'EX_LOTKA_Dependencies/',ModelName,'/',TrainAlg,'/'];\nload(fullfile(datapath1,['EX_LOTKA_MPC_',ModelName,'_',InputSignalType,'_TrainLength','.mat']))\nResultsALL(:,3) = Results;\n\n%% Correct cost\nQ = [1,1]; R = 0.5; Ru = 0.5;\nfor iM = 1:Nmodels\n for iL = 1:N_LENGTHS\n ResultsALL(iL,iM).J = evalObjectiveFCN(ResultsALL(iL,iM).u,ResultsALL(iL,iM).x,ResultsALL(iL,iM).xref,diag(Q),R,Ru);\n end\nend\n\n%% Show trajectories\ncb_hrzntl = 1;\n\ncmap = jet(N_LENGTHS);\nfor jModel = 1:Nmodels\n figure, hold on, box on\n for iM = 1:N_LENGTHS\n plot(ResultsALL(iM,jModel).x(1,:),ResultsALL(iM,jModel).x(2,:),'-','Color',cmap(iM,:),'LineWidth',1)\n end\n plot(ResultsALL(iM,jModel).xref(1,1),ResultsALL(iM,jModel).xref(2,1),'ok','MarkerFaceColor','k')\n % axis equal\n ylim([-20 100]), xlim([0 200])\n colormap(cmap),\n ch = colorbar;\n ch.Limits = [0 1];\n ch.Ticks = [0,0.25,0.5,0.75,1];\n ch.TickLabels = num2str( Ntrain_vec( [1, (N_LENGTHS-1)/4, (N_LENGTHS-1)/2+1, 3*(N_LENGTHS-1)/4+1, 4*(N_LENGTHS-1)/4+1] )' );\n if cb_hrzntl == 0\n ch.Position = [ch.Position(1),ch.Position(2)+0.14,ch.Position(3)-0.01,ch.Position(4)-0.1];\n set(gca,'Position',[0.08 0.2753 0.775 0.6497])\n elseif cb_hrzntl == 1\n ch.Location = 'southoutside';\n ch.Position = [0.2,0.1,0.75,ch.Position(4)];\n set(gca,'Position',[0.2 0.4 0.75 0.55])\n end\n xlabel('x1');\n ylabel('x2')\n set(gca,'LineWidth',1, 'FontSize',14)\n set(gcf,'Position',[100 100 300 200])\n set(gcf,'PaperPositionMode','auto')\n print('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_State_',ModelCollection{jModel},'.eps']);\nend\n\n\n%% Show cost trajectory\ncb_hrzntl = 1;\n\ncmap = jet(N_LENGTHS);\nfor jModel = 1:Nmodels\n figure, hold on, box on\n for iM = 1:N_LENGTHS\n plot(ResultsALL(end,jModel).t,cumsum(ResultsALL(iM,jModel).J),'-','Color',cmap(iM,:),'LineWidth',1)\n end\n plot(ResultsALL(end,2).t,cumsum(ResultsALL(end,2).J),'--','Color','k','LineWidth',2)\n ylim([-10 10^6]), xlim([200 max(ResultsALL(end,jModel).t)])\n colormap(cmap),\n ch = colorbar;\n ch.Limits = [0 1];\n ch.Ticks = [0,0.25,0.5,0.75,1];\n ch.TickLabels = num2str( Ntrain_vec( [1, (N_LENGTHS-1)/4, (N_LENGTHS-1)/2+1, 3*(N_LENGTHS-1)/4+1, 4*(N_LENGTHS-1)/4+1] )' );\n if cb_hrzntl == 0\n ch.Position = [ch.Position(1),ch.Position(2)+0.14,ch.Position(3)-0.01,ch.Position(4)-0.1];\n set(gca,'Position',[0.08 0.2753 0.775 0.6497])\n elseif cb_hrzntl == 1\n ch.Location = 'southoutside';\n ch.Position = [0.2,0.1,0.75,ch.Position(4)];\n set(gca,'Position',[0.2 0.4 0.75 0.55])\n end\n ylim([10^3 10^6])\n set(gca,'yscale','log')\n xlabel('Time');\n ylabel('Cost')\n set(gca,'LineWidth',1, 'FontSize',14)\n set(gcf,'Position',[100 100 300 200])\n set(gcf,'PaperPositionMode','auto')\n print('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_Cost_',ModelCollection{jModel},'.eps']);\nend\n\n\n%% Show execution time\nclear ph\nccolors = [1 0 0; 0 1 0; 0.7,0.7,1];\nlstyles = {'-', '--', '-.'};\nsymbols = {'o', 'd', 's'};\n\nTx = zeros(length(N_LENGTHS),Nmodels);\nfor iM = 1:Nmodels\n for iL = 1:N_LENGTHS\n Tx(iL,iM) = ResultsALL(iL,iM).eval_time;\n end\nend\nfigure, hold on, box on\nfor iM = 1:Nmodels\n plot(Ntrain_vec,Tx(:,iM)./60,symbols{iM},'Color',ccolors(iM,:),'MarkerFaceColor',ccolors(iM,:))\nend\nxlim([4 1001])\nylim([0.5*10^-5 10^2])\nset(gca,'ytick',[10.^([-5:2:2])])\nset(gca,'XScale','log','YScale','log')\nxlabel('Length of Training Data');\nylabel('Time [m]')\nlegend(ModelCollection,'Location','SouthEast')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_ExecTime','.eps']);\nlegend('off')\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_ExecTime','_noleg.eps']);\n\n%% Add penalization\nQ = 1*eye(2); %20\nfor iM = 1:Nmodels\n for iL = 1:N_LENGTHS\n if ResultsALL(iL,iM).t(end) == 0\n % Flag not converged / ended early\n ResultsALL(iL,iM).J(end) = 10^6;\n else\n % Flag if far from end state at end of time\n %ResultsALL(iL,iM).J(end) = ResultsALL(iL,iM).J(end) + abs(ResultsALL(iL,iM).xref(:,end) - ResultsALL(iL,iM).x(:,end))'*Q*abs(ResultsALL(iL,iM).xref(:,end) - ResultsALL(iL,iM).x(:,end));\n end\n end\nend\n\n\n%% Show Performance over training lengths\nclear ph\nccolors = [1 0 0; 0 1 0; 0.7,0.7,1];\nlstyles = {'-', '--', '-.'};\nsymbols = {'o', 'd', 's'};\n\nNstart = 20;\nxx = Ntrain_vec(Nstart):2:1000;\nyModel = zeros(length(xx),Nmodels);\nJendAll = zeros(length(N_LENGTHS),Nmodels);\nJend = cell(Nmodels,1);\nxJend = cell(Nmodels,1);\n\nfor iM = 1:Nmodels\n% Jend{iM} = zeros(length(N_LENGTHS),Nmodels);\n count = 0;\n for iL = 1:N_LENGTHS,\n tmp = cumsum(ResultsALL(iL,iM).J);\n if tmp(end)<10^10\n count = count + 1;\n xJend{iM}(count) = Ntrain_vec(iL);\n Jend{iM}(count) = tmp(end);\n end\n JendAll(iL,iM) = tmp(end);\n end\n yModel(:,iM) = spline(xJend{iM}(Nstart:end),Jend{iM}(Nstart:end),xx);\nend\n\nclear ph\nfigure, hold on, box on\n\nif eta_vec == 0.05\n fillh1 = fill([4.5*10^0 2.85*10^3 2.85*10^3 4.5*10^0], [5.5*10^3 5.5*10^3 1.5*10^4 1.5*10^4],0.9*ones(1,3)); % /w noise, not performing well above \nelseif eta_vec == 0.0\n fillh1 = fill([4.5*10^0 2.85*10^3 2.85*10^3 4.5*10^0], [5.5*10^3 5.5*10^3 2.5*10^4 2.5*10^4],0.9*ones(1,3));\nend\nfillh1.EdgeColor = 0.9*ones(1,3); fillh1.FaceAlpha = 0.5; \n\n[~,idx_best] = min(JendAll(:,2));\nplot(Ntrain_vec,JendAll(idx_best,2)*ones(size(Ntrain_vec)),'-','Color',ccolors(2,:),'LineWidth',1)\n\nfor iM = 1:Nmodels\n% if iM <= Nmodels\n% plot(xx,yModel(:,iM),'-','Color',ccolors(iM,:), 'LineWidth',1, 'LineStyle',lstyles{iM}), hold on,\n% end\n ph(iM) = plot(Ntrain_vec,JendAll(:,iM),symbols{iM},'Color',ccolors(iM,:),'MarkerFaceColor',ccolors(iM,:),'MarkerSize',4);\nend\nif eta_vec == 0\n iM = 1; plot([6.5,6.5],[5*10^3 10^7],'Color',ccolors(iM,:),'LineStyle',lstyles{iM});\n iM = 2; plot([13.5,13.5],[5*10^3 10^7],'Color',ccolors(iM,:),'LineStyle',lstyles{iM});\n iM = 3; plot([100,100],[5*10^3 10^7],'Color',ccolors(iM,:),'LineStyle',lstyles{iM});\nelseif eta_vec == 0.05\n iM = 1; plot([7.5,7.5],[5*10^3 10^7],'Color',ccolors(iM,:),'LineStyle',lstyles{iM});\n iM = 2; plot([70,70],[5*10^3 10^7],'Color',ccolors(iM,:),'LineStyle',lstyles{iM});\n iM = 3; plot([130,130],[5*10^3 10^7],'Color',ccolors(iM,:),'LineStyle',lstyles{iM}); \nend\nxlim([4 3001])\n% ylim([-100 5000])\n% ylim([5*10^2 1.5*10^4])\n% ylim([1*10^2 10^5])\nylim([5*10^3 10^7])\n% set(gca,'YScale','log')\nset(gca,'XScale','log','YScale','log', 'ytick', [10^3,10^4,10^5,10^6,10^7], 'xtick', [10^0,10^1,10^2,10^3]) %[10^3,5*10^3,10^4]\nxlabel('Length of Training Data');\nylabel('Cost')\nlh = legend(ph,ModelCollection,'Location','NorthEast');\nlh.Position = [0.71 0.73 lh.Position(3)-0.05 lh.Position(4)];\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_Cost','.eps']);\n\nlh.Location = 'NorthOutside';\nlh.Orientation = 'horizontal';\nlh.Box = 'off';\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_Cost','_legout.eps']);\nlegend('off')\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_Cost','_noleg.eps']);\n\n%% Show best case for all models\n% eta = 0.05: 8 38 21 \n% --> Ntrain = 12 1250 65\n% --> Jend = 9.0603e+03, 8.6549e+03, 2.0592e+04 \n% Jend for best eta==0: 8(12), 38(1250), 21(65) \n% SINDY converged Ntrain = 200\n% eta = 0.0: 12 25 37\n% --> Ntrain = 20 85 1000\n% --> Jend = 9.0601e+03, 8.6595e+03, 8.9236e+03 \n% SINDY converged Ntrain = 200\nBestModelIDX = zeros(1,Nmodels);\nJend = zeros(N_LENGTHS,Nmodels);\nfor iM = 1:Nmodels\n for iL = 1:N_LENGTHS\n tmp = cumsum(ResultsALL(iL,iM).J);\n Jend(iL,iM) = tmp(end);\n end\n [~,BestModelIDX(iM)] = min(Jend(:,iM));\nend\n\n% [val,idx1] = min(abs(Jend(:,1)-9.0601e+03))\n% Ntrain_vec(idx1)\n% [val,idx2] = min(abs(Jend(:,2)-8.6595e+03))\n% Ntrain_vec(idx2)\n% [val,idx3] = min(abs(Jend(:,3)-8.9236e+03))\n% Ntrain_vec(idx3)\n\nccolors = [1 0 0; 0 1 0; 0.7,0.7,1];\nlstyles = {'-', '--', '-.'};\n\nfigure,\nhold on, box on\nplot(ResultsALL(BestModelIDX(1),1).t,ResultsALL(1,1).xref(1,:),'-k')\nfor iM = 1:Nmodels\n plot(ResultsALL(BestModelIDX(iM),iM).t,ResultsALL(BestModelIDX(iM),iM).x(1,:),'Color',ccolors(iM,:),'LineStyle',lstyles{iM},'LineWidth',2)\nend\nylim([65 110])\nxlabel('Time'), ylabel('Prey')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 100])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_BestModels_x1','.eps']);\n\nfigure,\nhold on, box on\nplot(ResultsALL(BestModelIDX(1),1).t,ResultsALL(1,1).xref(2,:),'-k')\nfor iM = 1:Nmodels\n plot(ResultsALL(BestModelIDX(iM),iM).t,ResultsALL(BestModelIDX(iM),iM).x(2,:),'Color',ccolors(iM,:),'LineStyle',lstyles{iM},'LineWidth',2)\nend\nylim([7 27])\nxlabel('Time'), ylabel('Predator')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 100])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_BestModels_x2','.eps']);\n\nfigure,\nhold on, box on\nfor iM = 1:Nmodels\n plot(ResultsALL(BestModelIDX(iM),iM).t,cumsum(ResultsALL(BestModelIDX(iM),iM).J),'Color',ccolors(iM,:),'LineStyle',lstyles{iM},'LineWidth',2)\nend\nif eta_vec == 0\n ylim([7*10^3 9.5*10^3])\nelseif eta_vec == 0.05\n ylim([7*10^3 1*10^4])\nend\nset(gca,'yscale','linear','ytick',[7*10^3,8*10^3,9*10^3],'yticklabels',{'70','80','90'})\nxlabel('Time'), ylabel('Cost')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 100])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_BestModels_J','.eps']);\n\n%% Show State Performance over training lengths\nQ = 1*eye(2); %20\nJstate = zeros(length(ResultsALL(iL,iM).J),N_LENGTHS,Nmodels);\nfor iM = 1:Nmodels\n for iL = 1:N_LENGTHS\n for it = 1:length(ResultsALL(iL,iM).xref(1,:))\n Jstate(it,iL,iM) = abs(ResultsALL(iL,iM).xref(:,it) - ResultsALL(iL,iM).x(:,it))'*Q*abs(ResultsALL(iL,iM).xref(:,it) - ResultsALL(iL,iM).x(:,it));\n end\n end\nend\n\n\nclear ph\nccolors = [1 0 0; 0 1 0; 0.7,0.7,1];\nlstyles = {'-', '--', '-.'};\nsymbols = {'o', 'd', 's'};\n\nNstart = 20;\nxx = Ntrain_vec(Nstart):2:1000;\nyModel = zeros(length(xx),Nmodels);\nJendAll = zeros(length(N_LENGTHS),Nmodels);\nJend = cell(Nmodels,1);\nxJend = cell(Nmodels,1);\n\nfor iM = 1:Nmodels\n% Jend{iM} = zeros(length(N_LENGTHS),Nmodels);\n count = 0;\n for iL = 1:N_LENGTHS,\n tmp = cumsum(Jstate(:,iL,iM));\n if tmp(end)<10^10\n count = count + 1;\n xJend{iM}(count) = Ntrain_vec(iL);\n Jend{iM}(count) = tmp(end);\n end\n JendAll(iL,iM) = tmp(end);\n end\n yModel(:,iM) = spline(xJend{iM}(Nstart:end),Jend{iM}(Nstart:end),xx);\nend\n\nfigure, hold on, box on\nfor iM = 1:Nmodels\n% if iM < Nmodels\n% plot(xx,yModel(:,iM),'-','Color',ccolors(iM,:), 'LineWidth',1, 'LineStyle',lstyles{iM}), hold on,\n% end\n plot(Ntrain_vec,JendAll(:,iM),symbols{iM},'Color',ccolors(iM,:),'MarkerFaceColor',ccolors(iM,:),'MarkerSize',4)\nend\nxlim([4 1001])\nylim([5*10^3 5*10^6])\n% set(gca,'YScale','log')\nset(gca,'XScale','log','YScale','log', 'ytick', [10^4,10^5,10^6], 'xtick', [10^0,10^1,10^2,10^3])\nxlabel('Length of Training Data');\nylabel('Cost')\nlh = legend(ModelCollection,'Location','NorthEast');\nlh.Position = [0.71 0.73 lh.Position(3)-0.05 lh.Position(4)];\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_CostState','.eps']);\n\nlh.Location = 'NorthOutside';\nlh.Orientation = 'horizontal';\nlh.Box = 'off';\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_CostState','_legout.eps']);\nlegend('off')\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_CostState','_noleg.eps']);\n\n\nreturn\n%% Legend // Dummy plot\nfigure, hold on, box on\nfor iM = 1:Nmodels\n plot(Ntrain_vec,ones(size(Ntrain_vec)),'-','Marker',symbols{iM},'Color',ccolors(iM,:),'MarkerFaceColor',ccolors(iM,:))\nend\n\n% xlabel('Length of Training Data');\n% ylabel('Cost')\naxis off\nlh = legend(ModelCollection,'Location','NorthEast');\nlh.Location = 'NorthOutside';\nlh.Orientation = 'horizontal';\nlh.Box = 'off';\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 100])\nset(gcf,'PaperPositionMode','auto'),\nprint('-depsc2', '-painters', '-loose', '-cmyk', [figpath,'EX_LOTKA_CTRLPERF_',InputSignalType,'_Eta',sprintf('%03g',100*eta_vec),'_TrainingLength_Legend','.eps']);\n\n\nreturn\n%% TESTING\n\n% [~,idx_best_DMDc] = min(JendAll(:,1));\n% % plot(Ntrain_vec,JendAll(idx_best,2)*ones(size(Ntrain_vec)),'-','Color',ccolors(2,:),'LineWidth',1)\n% iM = 1;\n% iL = idx_best_DMDc; \n\n% \niM = 3;\niL = find(Ntrain_vec == 85); % DMDc\n\n% iM = 1;\n% iL = find(Ntrain_vec == 10); % DMDc\n\n\n\n% iM = 3;\n% iL = find(Ntrain_vec == 3000); % NARX: 85, 100, 14\n\nfigure, hold on\nplot(ResultsALL(end,2).x(1,:),ResultsALL(end,2).x(2,:),'-k','LineWidth',1)\nplot(ResultsALL(iL,iM).x(1,:),ResultsALL(iL,iM).x(2,:),'--r','LineWidth',1)\n\nfigure, hold on\nplot(ResultsALL(end,2).t,ResultsALL(end,2).x(2,:),'-k','LineWidth',1)\nplot(ResultsALL(end,iM).t,ResultsALL(iL,iM).x(2,:),'--r','LineWidth',1)\nplot(ResultsALL(end,2).t,ResultsALL(end,2).x(1,:),'-k','LineWidth',1)\nplot(ResultsALL(end,iM).t,ResultsALL(iL,iM).x(1,:),'--r','LineWidth',1)\n\nfigure, hold on\nplot(ResultsALL(end,2).t,cumsum(ResultsALL(end,2).J),'-k','LineWidth',1)\nplot(ResultsALL(end,iM).t,cumsum(ResultsALL(iL,iM).J),'--r','LineWidth',1)\n\nfigure, hold on\nplot(ResultsALL(end,2).t,ResultsALL(end,2).u,'-k','LineWidth',1)\nplot(ResultsALL(end,iM).t,ResultsALL(iL,iM).u,'--r','LineWidth',1)\n\n%% TESTING\nfigure,hold on\nfor iM = 1:Nmodels\n Jend = cumsum(ResultsALL(iM,1).J);\n semilogx(Ntrain_vec(iM),Jend(end),'or')\n Jend = cumsum(ResultsALL(iM,2).J);\n semilogx(Ntrain_vec(iM),Jend(end),'og')\n Jend = cumsum(ResultsALL(iM,3).J);\n semilogx(Ntrain_vec(iM),Jend(end),'ob')\nend\n\n%%\nfigure,hold on\nfor iM = 1:Nmodels\n Jend = cumsum(ResultsALL(iM,1).J);\n plot3(Ntrain_vec(iM).*ones(size(Jend)),ResultsALL(iM,1).t,Jend,'-r')\nend\n\n%%\nJend = zeros(Nmodels,1);\nfor iM = 1:Nmodels\n tmp = cumsum(ResultsALL(iM,1).J); Jend(iM) = tmp(end);\nend\n\nfigure,plot(Jend)\n\nfigure,plot(ResultsALL(3,1).x(1,:))\nfigure,plot(ResultsALL(3,1).u)\n\n", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LOTKA_VOLTERRA/VIZ_MPC_LOTKA_ModelComparison_Dependency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3532147608096485}} {"text": "% Focussed Detector in 3D Example\n%\n% This example shows how k-Wave can be used to model the output of a\n% focussed bowl detector in 3D where the directionality arises from\n% spatially averaging across the detector surface. It builds on the\n% Focussed Detector in 2D example. \n%\n% author: Ben Cox\n% date: 29th October 2010\n% last update: 18th 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 = 64; % number of grid points in the x direction\nNy = 64; % number of grid points in the y direction\nNz = 64; % number of grid points in the z direction\ndx = 100e-3/Nx; % grid point spacing in the x direction [m]\ndy = dx; % grid point spacing in the y direction [m]\ndz = dx; % grid point spacing in the z direction [m]\nkgrid = makeGrid(Nx, dx, Ny, dy, Nz, dz);\n\n% define the properties of the propagation medium\nmedium.sound_speed = 1500;\t% [m/s]\n\n% create the time array\n[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);\nNt = length(kgrid.t_array);\n\n% create a concave sensor\nradius = Nx/4-1;\nheight = 10;\nss = makeSphericalSection(radius, height);\n\n% add it to a mask of the correct size\nsensor.mask = zeros(Nx, Ny, Nz);\n[a,b,c] = size(ss);\nsphere_offset = 10;\nsensor.mask(sphere_offset+(1:a),(Ny-b+1)/2+(1:b),(Nz-c+1)/2+(1:c)) = ss;\n\n% define a time varying sinusoidal source\nsource_freq = 0.25e6;\nsource_mag = 1;\nsource.p = source_mag*sin(2*pi*source_freq*kgrid.t_array);\nsource.p = filterTimeSeries(kgrid, medium, source.p);\n\n% place the first point source near the focus of the detector\nsource1 = zeros(Nx, Ny, Nz);\nsource1(sphere_offset+radius, Ny/2+1, Nz/2+1) = 1;\n\n% place the second point source off axis\nsource2 = zeros(Nx, Ny, Nz);\nsource2(sphere_offset+radius, Ny/2+6, Nz/2+6) = 1;\n\n% run the first simulation\nsource.p_mask = source1;\ninput_args = {'PMLSize', 10, 'DataCast', 'single', 'PlotSim', false};\nsensor_data1 = kspaceFirstOrder3D(kgrid, medium, source, sensor, input_args{:});\n\n% average the data recorded at each grid point to simulate the measured\n% signal from a single element focussed detector\nsensor_data1 = sum(sensor_data1, 1);\n\n% run the second simulation\nsource.p_mask = source2;\nsensor_data2 = kspaceFirstOrder3D(kgrid, medium, source, sensor, input_args{:});\n\n% average the data recorded at each grid point to simulate the measured\n% signal from a single element focussed detector\nsensor_data2 = sum(sensor_data2, 1);\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the detector and on-axis and off-axis point sources\nvoxelPlot(sensor.mask + source1 + source2);\nview([99, 18]);\n\n% plot the time series corresponding to the on-axis and off-axis sources\nfigure\n[t_sc, t_scale, t_prefix] = scaleSI(kgrid.t_array(end));\nplot(kgrid.t_array.*t_scale, sensor_data1, '-');\nhold on\nplot(kgrid.t_array.*t_scale, sensor_data2, 'r-');\nxlabel(['Time [' t_prefix 's]']);\nylabel('Average Pressure Measured By Focussed Detector [Pa]');\nlegend('Source on axis', 'Source off axis');\n", "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_sd_focussed_detector_3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.35273881274522767}} {"text": "function soITrans = findSoITransitions(initialState, maxSearchUT, soiSkipIds, massLoss, orbitDecay, celBodyData)\n%findSoITransitions Summary of this function goes here\n% Detailed explanation goes here\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %findSoITransitions() returns a matrix of information that contains\n % data on upcoming SoI transitions for a given state. SoI transition\n % information is given in the following format:\n %\n % [transType, transUT, fromSoI, toSoI, fromRx, fromRy, fromRz, fromVx, fromVy, fromVz, toRx, toRy, toRz, toVx, toVy, toVz]\n %\n % transType - type of SoI transition. 1 for upwards, -1 for downwards\n % transUT - UT of the SoI transition\n % fromSoI - ID number of the body transitioning out of\n % toSoI - ID number of the body transitioning into\n %\n % fromRx - The following three are the position components of the s/c prior to leaving, relative to the fromSoI body\n % fromRy\n % fromRz\n % fromVx - The following three are the velocity components of the s/c prior to leaving, relative to the fromSoI body\n % fromVy\n % fromVz\n %\n % toRx - The following three are the position components of the s/c after moving to new SoI, relative to the toSoI body\n % toRy\n % toRz\n % toVx - The following three are the velocity components of the s/c after moving to new SoI, relative to the toSoI body\n % toVy\n % toVz\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n global num_SoI_search_revs use_selective_soi_search soi_search_tol num_soi_search_attempts_per_rev;\n \n if(isempty(use_selective_soi_search))\n use_selective_soi_search = 0;\n end\n \n if(isempty(num_SoI_search_revs))\n num_SoI_search_revs = 3;\n end\n \n if(isempty(soi_search_tol))\n soi_search_tol = 1E-12;\n end\n \n if(isempty(num_soi_search_attempts_per_rev))\n num_soi_search_attempts_per_rev = 1000;\n end\n \n ut = initialState(1);\n \n if(isempty(maxSearchUT))\n maxSearchUT = Inf;\n else\n if(maxSearchUT <= ut)\n maxSearchUT = Inf;\n end\n end\n \n bodyID = initialState(8);\n bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);\n\n gmu = bodyInfo.gm;\n rVect = initialState(2:4)';\n vVect = initialState(5:7)';\n \n [sma, ecc, inc, raan, arg, truINI] = getKeplerFromState(rVect,vVect,gmu);\n% meanINI = computeMeanFromTrueAnom(truINI, ecc);\n% scBodyInfo = getBodyInfoStructFromOrbit([sma, ecc, inc, raan, arg, meanINI, ut]);\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %There are two cases to consider: moving up the heirarchy and moving\n % down the heirarchy. For example:\n % Up Heirarchy: Kerbin -> Sun\n % Down Heirarchy Kerbin -> Mun\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %This segment looks for SoI transitions upwards.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n upSoITrans = [];\n parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);\n if(~isempty(parentBodyInfo))\n soiRadius = getSOIRadius(bodyInfo, parentBodyInfo);\n if(ecc < 1)\n [rAp, ~] = computeApogeePerigee(sma, ecc);\n else\n rAp = Inf;\n end\n\n if(ecc >= 1 || rAp > soiRadius) %definite SoI transition upwards exists!\n if(abs(norm(rVect)-soiRadius)<0.001 && dot(rVect, vVect) > 0)\n truSoI = truINI;\n tempEventLog = initialState;\n else\n truSoI = computeTrueAFromRadiusEcc(soiRadius, sma, ecc);\n tempEventLog = ma_executeCoast_goto_tru(truSoI, initialState, -1, false, soiSkipIds, [], massLoss, orbitDecay, celBodyData);\n end\n \n upSoITransUT = tempEventLog(end,1);\n \n if(upSoITransUT <= maxSearchUT)\n [rVectUp, vVectUp] = convertRVVectOnUpwardsSoITransition(bodyInfo, celBodyData, upSoITransUT, tempEventLog(end,2:4), tempEventLog(end,5:7));\n \n upSoITrans = [1, upSoITransUT, bodyInfo.id, parentBodyInfo.id, ...\n tempEventLog(end,2:7), ...\n rVectUp', vVectUp'];\n else\n upSoITrans = [];\n end\n else \n upSoITrans = [];\n end\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %This segment looks for SoI transitions downwards. This is the\n % trickier of the two algorithms.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);\n [childBodies] = getChildrenOfParentInfo(celBodyData, lower(bodyInfo.name));\n downSoITrans = [];\n \n searchableChildBodies = KSPTOT_BodyInfo.empty(1,0);\n childBodySoIRadii = [];\n for(child = childBodies)\n childBodyInfo = child{1};\n \n if(use_selective_soi_search && ismember(childBodyInfo.id,soiSkipIds))\n continue;\n else\n searchableChildBodies(end+1) = childBodyInfo; %#ok\n childBodySoIRadii(end+1) = getSOIRadius(childBodyInfo, bodyInfo);\n end\n end\n \n if(not(isempty(searchableChildBodies)))\n meanMotion = computeMeanMotion(sma, gmu);\n odefun = @(ut, mean) soiSearchOdeFun(ut, mean, meanMotion);\n \n [maxSearchUTComputed, maxStepSize] = getMaxSoISearchTime(ut, sma, ecc, truINI, bodyInfo, gmu, parentBodyInfo, num_SoI_search_revs, num_soi_search_attempts_per_rev);\n if(isempty(maxSearchUT) || not(isfinite(maxSearchUT)) || isnan(maxSearchUT))\n maxSearchUT = maxSearchUTComputed;\n end\n\n tspan = [ut, maxSearchUT];\n if(isempty(maxSearchUT))\n fprintf('%0.9f - %0.9f - %0.9f - %0.9f - %0.9f - %0.9f - %0.9f\\n\\n', ut, sma, ecc, truINI, gmu, num_SoI_search_revs, num_soi_search_attempts_per_rev);\n end\n \n meanIni = computeMeanFromTrueAnom(truINI, ecc);\n if(ecc < 1)\n meanIni = AngleZero2Pi(meanIni);\n end\n y0 = meanIni;\n \n odeEvtFcn = @(ut,mean) getSoITransitionOdeEvents(ut, mean, sma, ecc, inc, raan, arg, bodyInfo, gmu, searchableChildBodies, childBodySoIRadii, celBodyData);\n options = odeset('RelTol',soi_search_tol, 'AbsTol',soi_search_tol, 'Events',odeEvtFcn, 'MaxStep',maxStepSize, 'Refine',1, 'InitialStep',maxStepSize);\n \n [~,~,te,~,ie] = ode113(odefun,tspan,y0,options);\n \n if(not(isempty(ie)))\n [crossingUT, I] = min(te);\n childBodyInfo = searchableChildBodies(ie(I));\n \n tempEventLog = ma_executeCoast_goto_ut(crossingUT, initialState, -1, false, soiSkipIds, massLoss, orbitDecay, celBodyData);\n \n [rVectDown, vVectDown] = convertRVVectOnDownwardsSoITransition(childBodyInfo, celBodyData, crossingUT, tempEventLog(end,2:4), tempEventLog(end,5:7));\n \n if(dot(rVectDown, vVectDown) < 0)\n downSoITrans(end+1,:) = [-1, crossingUT, bodyInfo.id, childBodyInfo.id, ...\n tempEventLog(end,2:7), ...\n rVectDown', vVectDown'];\n end\n end\n end\n \n soITrans = [upSoITrans;downSoITrans]; \nend\n\nfunction [maxSearchUT, maxStep] = getMaxSoISearchTime(utINI, sma, ecc, truINI, bodyInfo, gmu, parentBodyInfo, num_SoI_search_revs, num_soi_search_attempts_per_rev)\n numStepsPer = num_soi_search_attempts_per_rev;\n \n if(ecc < 1)\n oPeriod = computePeriod(sma,gmu);\n \n maxSearchUT = utINI + num_SoI_search_revs .* oPeriod;\n \n maxStep = abs(maxSearchUT - utINI)/num_SoI_search_revs/numStepsPer;\n else\n soiRadius = getSOIRadius(bodyInfo, parentBodyInfo);\n maxHypTru = AngleZero2Pi(real(computeTrueAFromRadiusEcc(soiRadius, sma, ecc)));\n\n meanMotion = computeMeanMotion(sma, gmu);\n meanIni = computeMeanFromTrueAnom(truINI, ecc);\n maxMean = computeMeanFromTrueAnom(maxHypTru, ecc);\n \n maxSearchUT = utINI + (maxMean - meanIni)./meanMotion;\n \n maxStep = abs(maxSearchUT - utINI)./numStepsPer;\n end\nend\n\nfunction meandot = soiSearchOdeFun(~, ~, meanMotion)\n meandot = meanMotion;\nend\n\nfunction [value, isterminal, direction] = getSoITransitionOdeEvents(ut, mean, sma, ecc, inc, raan, arg, bodyInfo, gmu, childBodies, searchableChildBodies, celBodyData)\n value = [];\n isterminal = [];\n direction = [];\n \n tru = computeTrueAnomFromMean(mean, ecc);\n [rVect, vVect] = getStatefromKepler(sma, ecc, inc, raan, arg, tru, gmu, false);\n\n for(i=1:length(childBodies)) %#ok<*NO4LP>\n childBodyInfo = childBodies(i);\n\n dVect = getAbsPositBetweenSpacecraftAndBody(ut, rVect, bodyInfo, childBodyInfo, celBodyData);\n distToChild = norm(dVect);\n\n rSOI = searchableChildBodies(i);\n\n val = distToChild - rSOI;\n \n value(end+1) = val; %#ok\n direction(end+1) = -1; %#ok\n isterminal(end+1) = 1; %#ok\n end \nend\n \n% for(child = childBodies)\n% childBodyInfo = child{1};\n% \n% if(use_selective_soi_search && ismember(childBodyInfo.id,soiSkipIds))\n% continue;\n% end\n% \n% soiRadius = getSOIRadius(childBodyInfo, bodyInfo);\n% if(~isempty(parentBodyInfo))\n% soiRadiusParent = getSOIRadius(bodyInfo, parentBodyInfo);\n% else\n% soiRadiusParent = Inf;\n% end\n% \n% [rAp, rPe] = computeApogeePerigee(sma, ecc);\n% if(ecc > 1)\n% rAp = Inf;\n% end\n% \n% [rApBody, rPeBody] = computeApogeePerigee(childBodyInfo.sma, childBodyInfo.ecc);\n% \n% %%%%%%%%%%%\n% %These are the two cases in which an SoI transition downwards is\n% %impossible:\n% % 1) S/C apogee is less than the child body perigee minus the SoI\n% % radius (we don't get up the child body).\n% % 2) S/C perigee is greater than the child body apogee plus the SoI\n% % radius (we don't get down to the child body).\n% % 3) Position vectors at the asc/desc nodes must be within some\n% % small number of SoI radii.\n% %%%%%%%%%%%\n% if(rAp < rPeBody-soiRadius)\n% continue;\n% end\n% if(rPe > rApBody+soiRadius)\n% continue;\n% end\n% \n% if(strict_SoI_search)\n% sma1=sma;\n% ecc1=ecc;\n% inc1=inc;\n% raan1=raan;\n% arg1=arg;\n% \n% sma2=childBodyInfo.sma;\n% ecc2=childBodyInfo.ecc;\n% inc2=deg2rad(childBodyInfo.inc);\n% raan2=deg2rad(childBodyInfo.raan);\n% arg2=deg2rad(childBodyInfo.arg);\n% \n% [TF] = intersectCheck(sma1, ecc1, inc1, raan1, arg1,...\n% sma2, ecc2, inc2, raan2, arg2,...\n% gmu, soiRadius);\n% \n% if(TF == false)\n% continue;\n% end\n% end\n% \n% soiSf = 0;\n% \n% distScChildBody = norm(getAbsPositBetweenSpacecraftAndBody(ut, rVect, scBodyInfo, childBodyInfo, celBodyData));\n% if(distScChildBody < (soiRadius-2*soiSf)) %The spacecraft starts out inside the SoI for some reason!\n% [rVectDown, vVectDown] = convertRVVectOnDownwardsSoITransition(childBodyInfo, celBodyData, ut, initialState(end,2:4), initialState(end,5:7));\n% if(dot(rVectDown,vVectDown) < 0) %we're already headed down, so we can transition downwards. But if we're headed up at the SoI boundary, don't transition! Will cause SoI dithering.\n% downSoITrans(end+1,:) = [-1, ut, bodyInfo.id, childBodyInfo.id, ...\n% initialState(end,2:7), ...\n% rVectDown', vVectDown']; %#ok\n% end\n% end\n% \n% n1 = computeMeanMotion(sma, gmu);\n% n2 = computeMeanMotion(childBodyInfo.sma, gmu);\n% maxSearchRadius = min(rApBody+soiRadius,rAp);\n% minSearchRadius = max(rPeBody-soiRadius,rPe);\n% if(ecc < 1) \n% sPeriod = computeSynodicPeriod(n1, n2);\n% oPeriod = computePeriod(sma,gmu);\n% if(sPeriod / oPeriod > 3)\n% sPeriod = 3*computePeriod(sma,gmu);\n% end\n% numPeriods = ceil(sPeriod/oPeriod);\n% numPeriods = num_SoI_search_revs;\n% \n% truMax1=real(computeTrueAFromRadiusEcc(maxSearchRadius, sma, ecc));\n% truMin1=real(computeTrueAFromRadiusEcc(minSearchRadius, sma, ecc));\n% \n% truMax2 = 2*pi-truMin1;\n% truMin2 = 2*pi-truMax1;\n% \n% %%%%%%%%%Set 1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MA1 = computeMeanFromTrueAnom(truMin1, ecc);\n% MA2 = computeMeanFromTrueAnom(truMax1, ecc);\n% \n% dt = (MA1 - meanINI)/n1;\n% if(dt < 0)\n% % if(meanINI>=MA1 && meanINI<=MA2)\n% % dt = (2*pi-meanINI+MA1)/n1;\n% % else\n% % dt = (2*pi-meanINI+MA1)/n1;\n% % end\n% dt = (2*pi-meanINI+MA1)/n1;\n% end\n% \n% minT = ut+dt-100;\n% if(minT < ut)\n% minT = ut;\n% end\n% \n% dMA = MA2-MA1;\n% sPeriod = dMA/n1;\n% tArr = [];\n% for(i=1:numPeriods)\n% t1 = minT + (i-1)*oPeriod;\n% t2 = minT + (i-1)*oPeriod + sPeriod + 100;\n% \n% if(t1 <= maxSearchUT && t2 <= maxSearchUT)\n% tArr(end+1) = t1;\n% tArr(end+1) = t2;\n% elseif(t1 <= maxSearchUT && t2 > maxSearchUT)\n% tArr(end+1) = t1;\n% tArr(end+1) = maxSearchUT; %we don't want to exceed maxSearchUT\n% else\n% continue; %both t1 and t2 are greater than maxSearchUT, don't add them\n% end\n% end \n% \n% if(truINI >= truMin1 && truINI <= truMax1)\n% tArr(end+1) = ut;\n% tArr(end+1) = minT;\n% end\n% \n% %%%%%%%%%Set 2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MA1 = computeMeanFromTrueAnom(truMin2, ecc);\n% MA2 = computeMeanFromTrueAnom(truMax2, ecc);\n% \n% dt = (MA1 - meanINI)/n1;\n% if(dt < 0)\n% % dt = 0;\n% dt = (2*pi-meanINI+MA1)/n1;\n% end\n% \n% minT = ut+dt-100;\n% if(minT < ut)\n% minT = ut;\n% end\n% \n% dMA = MA2-MA1;\n% sPeriod = dMA/n1;\n% for(i=1:numPeriods)\n% t1 = minT + (i-1)*oPeriod;\n% t2 = minT + (i-1)*oPeriod + sPeriod + 100;\n% \n% if(t1 <= maxSearchUT && t2 <= maxSearchUT)\n% tArr(end+1) = t1;\n% tArr(end+1) = t2;\n% elseif(t1 <= maxSearchUT && t2 > maxSearchUT)\n% tArr(end+1) = t1;\n% tArr(end+1) = maxSearchUT; %we don't want to exceed maxSearchUT\n% else\n% continue; %both t1 and t2 are greater than maxSearchUT, don't add them\n% end\n% end \n% \n% if(truINI >= truMin2 && truINI <= truMax2)\n% tArr(end+1) = ut;\n% tArr(end+1) = minT;\n% end\n% \n% else\n% iniHyTruMax1 = AngleZero2Pi(real(computeTrueAFromRadiusEcc(maxSearchRadius, sma, ecc)));\n% iniHyTruMin1 = AngleZero2Pi(real(computeTrueAFromRadiusEcc(minSearchRadius, sma, ecc))); \n% \n% iniHyTruMax2 = -iniHyTruMin1;\n% iniHyTruMin2 = -iniHyTruMax1;\n% \n% %%%%%%%%%Set 1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MA1 = computeMeanFromTrueAnom(iniHyTruMin1, ecc);\n% MA2 = computeMeanFromTrueAnom(iniHyTruMax1, ecc);\n% \n% dt = (MA1 - meanINI)/n1;\n% if(dt < 0)\n% dt = 0;\n% end\n% \n% dMA = MA2-MA1;\n% sPeriod = dMA/n1;\n% \n% minT = ut+dt-100;\n% if(minT < ut)\n% minT = ut;\n% end\n% tArr = linspace(minT, ut+dt+sPeriod+100, 2);\n% \n% %%%%%%%%%Set 2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MA1 = computeMeanFromTrueAnom(iniHyTruMin2, ecc);\n% MA2 = computeMeanFromTrueAnom(iniHyTruMax2, ecc);\n% \n% dt = (MA1 - meanINI)/n1;\n% if(dt < 0)\n% dt = 0;\n% end\n% \n% dMA = MA2-MA1;\n% sPeriod = dMA/n1;\n% \n% minT = ut+dt-100;\n% if(minT < ut)\n% minT = ut;\n% end\n% \n% tArrTmp = linspace(minT, ut+dt+sPeriod+100, 2);\n% tArr(end+1) = min(tArrTmp);\n% tArr(end+1) = max(tArrTmp);\n% end\n% \n% %These two lines sort the SoI calculations so that they're in\n% %time-order, meaning that earlier SoI transitions will not be\n% %missed if there are multiple possible SoI transitions.\n% tArr = sortrows(reshape(tArr, [2,length(tArr)/2])', 1);\n% tArr = reshape(tArr',1,[]);\n% \n% findChildSoITransFunc = @(ut) isSoICrossing(ut, scBodyInfo, childBodyInfo, bodyInfo, soiRadius-soiSf, true, celBodyData);\n% findChildSoITransFuncNoAbs = @(ut) isSoICrossing(ut, scBodyInfo, childBodyInfo, bodyInfo, soiRadius-soiSf, false, celBodyData);\n% findChildSoITransFuncRealSoI = @(ut) isSoICrossing(ut, scBodyInfo, childBodyInfo, bodyInfo, soiRadius-10/1000, false, celBodyData);\n% \n% options = optimset('TolX',soi_search_tol);\n% tolX2 = soi_search_tol;\n% for(i=1:length(tArr)/2) %#ok<*NO4LP>\n% tInds = [2*(i-1)+1, 2*i];\n% \n% if(tArr(tInds(1)) >= tArr(tInds(2)))\n% continue;\n% end\n% \n% %%%%%%%%%\n% %This block of code is designed to weed out extraneous calls to\n% %fminbnd by avoiding looking for SoI transitions where the\n% %child body in question is clearly off on the other side of the\n% %orbit.\n% %%%%%%%%%\n% [rVectSc1] = getStateAtTime(scBodyInfo, tArr(tInds(1)), gmu);\n% [rVectSc2] = getStateAtTime(scBodyInfo, tArr(tInds(2)), gmu);\n% \n% [rVectC1] = getStateAtTime(childBodyInfo, tArr(tInds(1)), gmu);\n% [rVectC2] = getStateAtTime(childBodyInfo, tArr(tInds(2)), gmu);\n% \n% distT1 = norm(rVectSc1-rVectC1)/childBodyInfo.sma;\n% distT2 = norm(rVectSc2-rVectC2)/childBodyInfo.sma;\n% \n% if(strict_SoI_search)\n% smaFrac = 0.5;\n% else\n% smaFrac = 60.0; %used to be 0.9\n% end\n% \n% if(min(distT1, distT2) > smaFrac)\n% if(strict_SoI_search)\n% fprintf('While propagating Mission Architect orbit, strict SoI search setting skipped over a possible SoI transition between UT = %f sec and UT = %f sec.\\n', tArr(tInds(1)), tArr(tInds(2)))\n% end\n% continue;\n% end\n% \n% try\n% minUT = max(tArr(tInds(1)), initialState(1));\n% maxUT = tArr(tInds(2));\n% \n% if(minUT > maxUT)\n% continue;\n% end\n% \n% if(num_soi_search_attempts_per_rev > 1)\n% startPts = linspace(minUT,maxUT,num_soi_search_attempts_per_rev+1);\n% else\n% startPts = [minUT,maxUT];\n% end\n% crossingUTs = NaN(length(startPts)-1,1);\n% minDistFromSOI2s = crossingUTs;\n% for(j=1:length(startPts)-1)\n% minUT_Opt = startPts(j);\n% maxUT_Opt = startPts(j+1);\n% \n% [crossingUTs(j), ~,~,~] = fminbnd(findChildSoITransFunc,minUT_Opt,maxUT_Opt, options);\n% minDistFromSOI2s(j) = findChildSoITransFuncRealSoI(crossingUTs(j));\n% \n% if(minDistFromSOI2s(j) < 1)\n% break; %we found SoI transition, no need to keep going\n% end\n% end\n% \n% [minDistFromSOI2, minI] = min(minDistFromSOI2s);\n% crossingUT = crossingUTs(minI);\n% \n% if(minDistFromSOI2 > 100) \n% continue;\n% end\n% catch ME %#ok<*NASGU>\n% continue;\n% end \n% \n% if(abs(minDistFromSOI2) > 0)\n% minUT = crossingUT-1200;\n% maxUT = crossingUT+1200;\n% unrefinedCrossingUt = crossingUT;\n% \n% [crossingUT,minDistFromSOI2, exitFlag] = bisection(findChildSoITransFuncNoAbs, minUT, maxUT, 0.0, tolX2);\n% if(minDistFromSOI2 > 0.01)\n% continue;\n% end\n% \n% if(minDistFromSOI2 < 0.01 && isnan(crossingUT))\n% options = optimset('Display','off', 'TolX',tolX2);\n% [crossingUT,minDistFromSOI2, exitFlag] = fzero(findChildSoITransFuncNoAbs, unrefinedCrossingUt, options);\n% \n% if(minDistFromSOI2 > 0.01)\n% continue;\n% end\n% end\n% end\n% \n% if(isempty(crossingUT) || isnan(crossingUT) || ~isreal(crossingUT) || ~isfinite(crossingUT))\n% continue;\n% end\n% \n% if(abs(crossingUT-initialState(1)) <= 0.1)\n% crossingUT = initialState(1);\n% elseif(abs(crossingUT-initialState(1)) > 0.1)\n% if(crossingUT < initialState(1))\n% continue;\n% end\n% end\n% \n% if(abs(maxSearchUT - crossingUT) <= 0.1)\n% crossingUT = maxSearchUT;\n% elseif(abs(maxSearchUT - crossingUT) > 0.1)\n% if(crossingUT > maxSearchUT)\n% continue;\n% end\n% end\n% \n% tempEventLog = ma_executeCoast_goto_ut(crossingUT, initialState, -1, false, soiSkipIds, massLoss, orbitDecay, celBodyData);\n% \n% [rVectDown, vVectDown] = convertRVVectOnDownwardsSoITransition(childBodyInfo, celBodyData, crossingUT, tempEventLog(end,2:4), tempEventLog(end,5:7));\n% if(dot(rVectDown, vVectDown) > 0) %we found the outgoing part of the SoI transition \n% crossingUTTemp = crossingUT;\n% \n% [smaTd, eccTd, ~, ~, ~, truTd] = getKeplerFromState(rVectDown, vVectDown, childBodyInfo.gm);\n% [meanTd] = computeMeanFromTrueAnom(truTd, eccTd);\n% [meanMotionTd] = computeMeanMotion(smaTd, childBodyInfo.gm);\n% % [~,vVectTd] = getStatefromKepler(smaTd, eccTd, incTd, raanTd, argTd, 0.0, childBodyInfo.gm);\n% \n% maxUT = crossingUT - meanTd/meanMotionTd+100;\n% minUT = crossingUT - 6*meanTd/meanMotionTd;\n% minUT = max(minUT,initialState(1));\n% \n% if(maxUT < initialState(1))\n% continue;\n% end\n% \n% try\n% [crossingUT, ~,~,~] = fminbnd(findChildSoITransFunc,minUT,maxUT, options);\n% minDistFromSOI2 = findChildSoITransFuncRealSoI(crossingUT);\n% if(minDistFromSOI2 > 100) \n% continue;\n% end\n% catch ME %#ok<*NASGU>\n% continue;\n% end \n% \n% if(minDistFromSOI2 > 0)\n% minUT = crossingUT-1200;\n% minUT = max(minUT,initialState(1));\n% maxUT = crossingUT+1200;\n% [crossingUT,minDistFromSOI2] = bisection(findChildSoITransFuncRealSoI, minUT, maxUT, 0.0, tolX2);\n% if(minDistFromSOI2 > 0.01)\n% continue;\n% end\n% end\n% \n% if(isempty(crossingUT) || isnan(crossingUT) || ~isreal(crossingUT) || ~isfinite(crossingUT))\n% continue;\n% end\n% \n% if(abs(crossingUT-initialState(1)) <= 1)\n% crossingUT = initialState(1);\n% elseif(abs(crossingUT-initialState(1)) > 1)\n% if(crossingUT < initialState(1))\n% continue;\n% end\n% end\n% \n% if(abs(maxSearchUT - crossingUT) <= 1)\n% crossingUT = maxSearchUT;\n% elseif(abs(maxSearchUT - crossingUT) > 1)\n% if(crossingUT > maxSearchUT)\n% continue;\n% end\n% end\n% \n% tempEventLog = ma_executeCoast_goto_ut(crossingUT, initialState, -1, false, soiSkipIds, massLoss, orbitDecay, celBodyData);\n% [rVectDown, vVectDown] = convertRVVectOnDownwardsSoITransition(childBodyInfo, celBodyData, crossingUT, tempEventLog(end,2:4), tempEventLog(end,5:7));\n% end\n% % if(abs(norm(rVectDown) - soiRadius) >= 0.01)\n% % continue; %something wierd happened, go around\n% % end\n% if(crossingUT <= maxSearchUT)\n% downSoITrans(end+1,:) = [-1, crossingUT, bodyInfo.id, childBodyInfo.id, ...\n% tempEventLog(end,2:7), ...\n% rVectDown', vVectDown']; %#ok\n% end\n% break;\n% end\n% end\n% \n% soITrans = [upSoITrans;downSoITrans]; \n% end\n% \n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/propagation/soi_trans/findSoITransitions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3526875732678444}} {"text": "function [g1, g2] = disimXrbfKernGradient(disimKern, rbfKern, t1, t2, covGrad)\n\n% DISIMXRBFKERNGRADIENT Compute gradient between the DISIM and RBF kernels.\n% FORMAT\n% DESC computes the gradient of an objective function with respect\n% to cross kernel terms between DISIM and RBF kernels for\n% the multiple output kernel. \n% ARG disimKern : the kernel structure associated with the DISIM\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 DISIM 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 DISIM and RBF kernels for\n% the multiple output kernel. \n% ARG disimKern : the kernel structure associated with the DISIM\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 DISIM kernel.\n% RETURN g2 : gradient of objective function with respect to kernel\n% parameters of RBF kernel.\n%\n% SEEALSO : multiKernParamInit, multiKernCompute, disimKernParamInit, rbfKernParamInit\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n%\n% COPYRIGHT : Antti Honkela, 2007-2009\n\n% KERN\n\narg{1} = t1;\nif nargin < 5\n covGrad = t2;\n t2 = t1;\nelse\n arg{2} = t2; \nend\nif size(t1, 2) > 1 | size(t2, 2) > 1\n error('Input can only have one column');\nend\nif disimKern.inverseWidth ~= rbfKern.inverseWidth\n error('Kernels cannot be cross combined if they have different inverse widths.')\nend\nif disimKern.rbf_variance ~= rbfKern.variance\n error('Kernels cannot be cross combined if they have different RBF variances.');\nend\n\ndim1 = size(t1, 1);\ndim2 = size(t2, 1);\nt1Mat = t1(:, ones(1, dim2));\nt2Mat = t2(:, ones(1, dim1))';\ndiffT = (t1Mat - t2Mat);\nl = sqrt(2/disimKern.inverseWidth);\nl2 = l*l;\nC_0 = sqrt(disimKern.di_variance);\nC_i = sqrt(disimKern.variance);\nC_j = rbfKern.variance;\nD_i = disimKern.decay;\ndelta = disimKern.di_decay;\n\ninvLDiffT = 1/l*diffT;\nhalfLD_i = 0.5*l*D_i;\nhalfLDelta = 0.5*l*delta;\n\nprefact = C_0 * C_i * C_j * sqrt(pi)/2 * l;\n\nlnCommon = - log(delta - D_i);\n[lnPart1, sign1] = lnDiffErfs(halfLDelta - invLDiffT, halfLDelta + t2Mat/l);\n[lnPart2, sign2] = lnDiffErfs(halfLD_i + t2Mat/l, halfLD_i - invLDiffT);\n\nlnFact1 = halfLDelta^2 - delta * diffT;\nlnFact2 = halfLD_i^2 - D_i * diffT;\n\n\nk = sign1 .* exp(lnCommon + lnFact1 + lnPart1) ...\n + sign2 .* exp(lnCommon + lnFact2 + lnPart2);\n\nk = 0.5*sqrt(disimKern.variance)*sqrt(disimKern.di_variance)*rbfKern.variance*k*sqrt(pi)*l;\n\n\n\n[dlnPart1, m1] = gradLnDiffErfs(halfLDelta - invLDiffT, halfLDelta + t2Mat/l, ...\n\t\t\t\tl/2, l/2);\n[dlnPart2, m2] = gradLnDiffErfs(halfLD_i + t2Mat/l, halfLD_i - invLDiffT, ...\n\t\t\t\tl/2, l/2);\n\ndK_dD = k .* (1./(delta-D_i)) ...\n\t+ prefact ...\n\t.* ((l*halfLD_i - diffT) .* sign2 .* exp(lnCommon + lnFact2 + lnPart2) ...\n\t + dlnPart2 .* exp(lnCommon + lnFact2 - m2));\ndk_dD = sum(sum(dK_dD.*covGrad));\n\ndK_ddelta = k .* (-1./(delta-D_i)) ...\n + prefact ...\n .* ((l*halfLDelta - diffT) .* sign1 .* exp(lnCommon + lnFact1 + lnPart1) ...\n\t+ dlnPart1 .* exp(lnCommon + lnFact1 - m1));\ndk_ddelta = sum(sum(dK_ddelta.*covGrad));\n\n[dlnPart1, m1] = gradLnDiffErfs(halfLDelta - invLDiffT, halfLDelta + t2Mat/l, ...\n\t\t\t\tdelta/2 + invLDiffT/l, delta/2 - t2Mat/l2);\n[dlnPart2, m2] = gradLnDiffErfs(halfLD_i + t2Mat/l, halfLD_i - invLDiffT, ...\n\t\t\t\tD_i/2 - t2Mat/l2, D_i/2 + invLDiffT/l);\n\ndK_dl = k/l ...\n\t+ prefact ... \n\t.* (delta*halfLDelta .* sign1 .* exp(lnCommon + lnFact1 + lnPart1) ...\n\t + D_i*halfLD_i .* sign2 .* exp(lnCommon + lnFact2 + lnPart2) ...\n\t + dlnPart1 .* exp(lnCommon + lnFact1 - m1) ...\n\t + dlnPart2 .* exp(lnCommon + lnFact2 - m2));\ndk_dl = sum(sum(dK_dl.*covGrad));\n\ndk_dC_i = sum(sum(k.*covGrad))/C_i;\ndk_dC_0 = sum(sum(k.*covGrad))/C_0;\ndk_dRbfVariance = sum(sum(k.*covGrad))/rbfKern.variance;\n\ndk_dinvWidth = -0.5*sqrt(2)/(disimKern.inverseWidth* ...\n sqrt(disimKern.inverseWidth))*dk_dl;\ndk_dDisimVariance = dk_dC_i*0.5/C_i;\ndk_dDIVariance = dk_dC_0*0.5/C_0;\n\n\n% only pass the gradient with respect to the inverse width to one\n% of the gradient vectors ... otherwise it is counted twice.\ng1 = real([dk_ddelta dk_dinvWidth dk_dDIVariance dk_dD dk_dDisimVariance 0]);\ng2 = real([0 dk_dRbfVariance]);\n\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/disimXrbfKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.35241522330269315}} {"text": "function [results, success, raw] = opf_execute(om, mpopt)\n%OPF_EXECUTE Executes the OPF specified by an OPF model object.\n% [RESULTS, SUCCESS, RAW] = OPF_EXECUTE(OM, MPOPT)\n%\n% RESULTS are returned with internal indexing, all equipment\n% in-service, etc.\n%\n% See also OPF, OPF_SETUP.\n\n% MATPOWER\n% Copyright (c) 2009-2020, Power Systems Engineering Research Center (PSERC)\n% by 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\n%% define named indices into data matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n\n%%----- setup -----\n%% options\ndc = strcmp(upper(mpopt.model), 'DC');\nalg = upper(mpopt.opf.ac.solver);\nswitch alg\n case {'PDIPM', 'TRALM', 'MINOPF', 'SDPOPF'}\n legacy_solver = 1;\n otherwise\n legacy_solver = 0;\nend\nsdp = strcmp(alg, 'SDPOPF');\nvcart = ~dc && mpopt.opf.v_cartesian;\n\n%% get indexing\n[vv, ll, nne, nni] = om.get_idx();\n\nif mpopt.verbose > 0\n v = mpver('all');\n fprintf('\\nMATPOWER Version %s, %s', v.Version, v.Date);\nend\n\nif dc\n %%----- run DC OPF solver -----\n if mpopt.verbose > 0\n fprintf(' -- DC Optimal Power Flow\\n');\n end\n [results, success, raw] = dcopf_solver(om, mpopt);\nelse\n %%----- run AC OPF solver -----\n if mpopt.verbose > 0\n fprintf(' -- AC Optimal Power Flow\\n AC OPF formulation: ');\n if sdp\n fprintf('SDP relaxation\\n');\n else\n if vcart\n v = 'cartesian';\n else\n v = 'polar';\n end\n if mpopt.opf.current_balance\n v2 = 'current';\n else\n v2 = 'power';\n end\n fprintf('%s voltages, %s balance eqns\\n', v, v2);\n end\n end\n\n %% ZIP loads?\n if legacy_solver && ( ...\n (~isempty(mpopt.exp.sys_wide_zip_loads.pw) && ...\n any(mpopt.exp.sys_wide_zip_loads.pw(2:3))) || ...\n (~isempty(mpopt.exp.sys_wide_zip_loads.qw) && ...\n any(mpopt.exp.sys_wide_zip_loads.qw(2:3))) )\n warning('opf_execute: ''%s'' solver does not support ZIP load model. Converting to constant power loads.', alg)\n mpopt = mpoption(mpopt, 'exp.sys_wide_zip_loads', ...\n struct('pw', [], 'qw', []));\n end\n\n %% run specific AC OPF solver\n if legacy_solver\n switch alg\n case 'PDIPM'\n if mpopt.pdipm.step_control\n if ~have_feature('scpdipmopf')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires SCPDIPMOPF (see http://www.pserc.cornell.edu/tspopf/)', alg);\n end\n else\n if ~have_feature('pdipmopf')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires PDIPMOPF (see http://www.pserc.cornell.edu/tspopf/)', alg);\n end\n end\n [results, success, raw] = tspopf_solver(om, mpopt);\n case 'TRALM'\n if ~have_feature('tralmopf')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires TRALM (see http://www.pserc.cornell.edu/tspopf/)', alg);\n end\n [results, success, raw] = tspopf_solver(om, mpopt);\n case 'MINOPF'\n if ~have_feature('minopf')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires MINOPF (see http://www.pserc.cornell.edu/minopf/)', alg);\n end\n [results, success, raw] = mopf_solver(om, mpopt);\n case 'SDPOPF'\n if ~have_feature('yalmip')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires YALMIP (see https://yalmip.github.io)', alg);\n end\n [results, success, raw] = sdpopf_solver(om, mpopt);\n otherwise\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' is not a valid AC OPF solver selection', alg);\n end\n else %% not legacy solver\n switch alg\n case 'IPOPT'\n if ~have_feature('ipopt')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires IPOPT (see https://github.com/coin-or/Ipopt)', alg);\n end\n case 'FMINCON'\n if ~have_feature('fmincon')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires FMINCON (Optimization Toolbox 2.x or later)', alg);\n end\n case 'KNITRO'\n if ~have_feature('knitro')\n error('opf_execute: MPOPT.opf.ac.solver = ''%s'' requires Artelys Knitro (see https://www.artelys.com/solvers/knitro/)', alg);\n end\n end\n [results, success, raw] = nlpopf_solver(om, mpopt);\n end %% if legacy_solver\nend %% if dc\nif ~isfield(raw, 'output') || ~isfield(raw.output, 'alg') || isempty(raw.output.alg)\n raw.output.alg = alg;\nend\n\nif success\n if ~dc && ~sdp\n %% copy bus voltages back to gen matrix\n results.gen(:, VG) = results.bus(results.gen(:, GEN_BUS), VM);\n\n %% cartesian voltage magnitude multipliers\n if vcart\n results.bus(:, MU_VMIN) = results.bus(:, MU_VMIN) .* results.bus(:, VM) * 2;\n results.bus(:, MU_VMAX) = results.bus(:, MU_VMAX) .* results.bus(:, VM) * 2;\n end\n\n %% gen PQ capability curve multipliers\n if ll.N.PQh > 0 || ll.N.PQl > 0\n mu_PQh = results.mu.lin.l(ll.i1.PQh:ll.iN.PQh) - results.mu.lin.u(ll.i1.PQh:ll.iN.PQh);\n mu_PQl = results.mu.lin.l(ll.i1.PQl:ll.iN.PQl) - results.mu.lin.u(ll.i1.PQl:ll.iN.PQl);\n Apqdata = om.get_userdata('Apqdata');\n results.gen = update_mupq(results.baseMVA, results.gen, mu_PQh, mu_PQl, Apqdata);\n end\n\n %% compute g, dg, f, df, d2f if requested by opf.return_raw_der = 1\n if mpopt.opf.return_raw_der\n %% move from results to raw if using v4.0 of MINOPF or TSPOPF\n if isfield(results, 'dg')\n raw.dg = results.dg;\n raw.g = results.g;\n end\n %% compute g, dg, unless already done by post-v4.0 MINOPF or TSPOPF\n if ~isfield(raw, 'dg')\n [g, geq, dg, dgeq] = nlp_consfcn(om, results.x);\n raw.g = [ geq; g];\n raw.dg = [ dgeq'; dg']; %% true Jacobian organization\n end\n %% compute df, d2f\n [f, df, d2f] = nlp_costfcn(om, results.x);\n raw.df = df;\n raw.d2f = d2f;\n end\n end\n\n %% delete g and dg fields from results if using v4.0 of MINOPF or TSPOPF\n if isfield(results, 'dg')\n rmfield(results, 'dg');\n rmfield(results, 'g');\n end\n\n %% angle limit constraint multipliers\n iang = om.get_userdata('iang');\n if ~sdp && length(iang)\n if vcart\n iang = om.get_userdata('iang');\n results.branch(iang, MU_ANGMIN) = results.mu.nli(nni.i1.angL:nni.iN.angL) * pi/180;\n results.branch(iang, MU_ANGMAX) = results.mu.nli(nni.i1.angU:nni.iN.angU) * pi/180;\n else\n iang = om.get_userdata('iang');\n results.branch(iang, MU_ANGMIN) = results.mu.lin.l(ll.i1.ang:ll.iN.ang) * pi/180;\n results.branch(iang, MU_ANGMAX) = results.mu.lin.u(ll.i1.ang:ll.iN.ang) * pi/180;\n end\n end\nelse\n %% assign empty g, dg, f, df, d2f if requested by opf.return_raw_der = 1\n if ~dc && mpopt.opf.return_raw_der\n raw.dg = [];\n raw.g = [];\n raw.df = [];\n raw.d2f = [];\n end\nend\n\nif ~sdp\n %% assign values and limit shadow prices for variables\n om_var_order = om.get('var', 'order');\n for k = 1:length(om_var_order)\n name = om_var_order(k).name;\n if om.getN('var', name)\n idx = vv.i1.(name):vv.iN.(name);\n results.var.val.(name) = results.x(idx);\n results.var.mu.l.(name) = results.mu.var.l(idx);\n results.var.mu.u.(name) = results.mu.var.u(idx);\n end\n end\n\n %% assign shadow prices for linear constraints\n om_lin_order = om.get('lin', 'order');\n for k = 1:length(om_lin_order)\n name = om_lin_order(k).name;\n if om.getN('lin', name)\n idx = ll.i1.(name):ll.iN.(name);\n results.lin.mu.l.(name) = results.mu.lin.l(idx);\n results.lin.mu.u.(name) = results.mu.lin.u(idx);\n end\n end\n\n %% assign shadow prices for nonlinear constraints\n if ~dc\n om_nle_order = om.get('nle', 'order');\n for k = 1:length(om_nle_order)\n name = om_nle_order(k).name;\n if om.getN('nle', name)\n results.nle.lambda.(name) = results.mu.nle(nne.i1.(name):nne.iN.(name));\n end\n end\n\n om_nli_order = om.get('nli', 'order');\n for k = 1:length(om_nli_order)\n name = om_nli_order(k).name;\n if om.getN('nli', name)\n results.nli.mu.(name) = results.mu.nli(nni.i1.(name):nni.iN.(name));\n end\n end\n end\n\n %% assign values for components of quadratic cost\n om_qdc_order = om.get('qdc', 'order');\n for k = 1:length(om_qdc_order)\n name = om_qdc_order(k).name;\n if om.getN('qdc', name)\n results.qdc.(name) = om.eval_quad_cost(results.x, name);\n end\n end\n\n %% assign values for components of general nonlinear cost\n om_nlc_order = om.get('nlc', 'order');\n for k = 1:length(om_nlc_order)\n name = om_nlc_order(k).name;\n if om.getN('nlc', name)\n results.nlc.(name) = om.eval_nln_cost(results.x, name);\n end\n end\n\n %% assign values for components of legacy user cost\n om_cost_order = om.get('cost', 'order');\n for k = 1:length(om_cost_order)\n name = om_cost_order(k).name;\n if om.getN('cost', name)\n results.cost.(name) = om.eval_legacy_cost(results.x, name);\n end\n end\n\n %% if single-block PWL costs were converted to POLY, insert dummy y into x\n %% Note: The \"y\" portion of x will be nonsense, but everything should at\n %% least be in the expected locations.\n pwl1 = om.get_userdata('pwl1');\n if ~isempty(pwl1) && ~strcmp(alg, 'TRALM') && ~(strcmp(alg, 'PDIPM') && mpopt.pdipm.step_control)\n %% get indexing\n vv = om.get_idx();\n if dc\n nx = vv.iN.Pg;\n else\n nx = vv.iN.Qg;\n end\n y = zeros(length(pwl1), 1);\n raw.xr = [ raw.xr(1:nx); y; raw.xr(nx+1:end)];\n results.x = [ results.x(1:nx); y; results.x(nx+1:end)];\n end\nend", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/opf_execute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3519486114124266}} {"text": "function [g1, g2] = simwhiteXrbfwhiteKernGradient(simKern, rbfKern, t1, varargin)\n\n% SIMWHITEXRBFWHITEKERNGRADIENT Compute a cross gradient between a SIM-WHITE\n% and an RBF-WHITE kernels.\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 and an RBF-WHITE\n% 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 : 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% rbfwhiteKernParamInit, simwhiteKernExtractParam, rbfwhiteKernExtractParam\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\nif simKern.isStationary ~= rbfKern.isStationary\n error('Stationary and non-stationary kernels cannot be cross combined.')\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;\nindT = double(deltaT >= 0);\n\n% Parameters required for further computations\nisStationary = simKern.isStationary;\nvariance = simKern.variance;\ndecay = simKern.decay;\nsensitivity = simKern.sensitivity;\ninvWidth = rbfKern.inverseWidth;\n\n% Computing a normalised (i.e. variance = 1 and sensitivity = 1) kernel\nsimKern.variance = 1;\nsimKern.sensitivity = 1;\nrbfKern.variance = 1;\nK = simwhiteXrbfwhiteKernCompute(simKern, rbfKern, t1, t2);\n\n% Gradient w.r.t. the decay (simKern)\ng1(1) = variance * sensitivity * sum(sum( ((-deltaT+decay/invWidth) .* K ...\n + 1/sqrt(2*pi*invWidth) ...\n * exp(-decay*deltaT + 0.5*(decay^2)/invWidth) ...\n .* (exp(-0.5*invWidth*((T2+decay/invWidth).^2)) ...\n - exp(-0.5*invWidth*((abs(deltaT).*(1-indT)+decay/invWidth).^2)))) ...\n .* covGrad));\n\n% Gradient w.r.t. the inverse width (rbfKern)\ng2(1) = variance * sensitivity * sum(sum( (-0.5*((decay/invWidth)^2) .* K ...\n + 1/sqrt(8*pi*invWidth) ...\n * exp(-decay*deltaT + 0.5*(decay^2)/invWidth) ...\n .* ((T2-decay/invWidth).*exp(-0.5*invWidth*((T2+decay/invWidth).^2)) ...\n - (abs(deltaT).*(1-indT)-decay/invWidth) ...\n .* exp(-0.5*invWidth*((abs(deltaT).*(1-indT)+decay/invWidth).^2)))) ...\n .* covGrad));\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/simwhiteXrbfwhiteKernGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3512832380240314}} {"text": "classdef m_22_vic_10p_3s < MARRMoT_model\n% Class for hydrologic conceptual model: VIC\n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Model references\n% Clark, M. P., Slater, A. G., Rupp, D. E., Woods, R. A., Vrugt, J. A.,\n% Gupta, H. V., � Hay, L. E. (2008). Framework for Understanding Structural\n% Errors (FUSE): A modular framework to diagnose differences between\n% hydrological models. Water Resources Research, 44(12), W00B02.\n% http://doi.org/10.1029/2007WR006735\n%\n% Liang, X., Lettenmaier, D. P., Wood, E. F., & Burges, S. J. (1994). A\n% simple hydrologically based model of land surface water and energy fluxes\n% for general circulation models. Journal of Geophysical Research, 99,\n% 14415�14428.\n\n properties\n % model-specific attributes\n aux_theta % auxiliary parameter set\n end\n methods\n\n % creator method\n function obj = m_22_vic_10p_3s()\n obj.numStores = 3; % number of model stores\n obj.numFluxes = 11; % number of model fluxes\n obj.numParams = 10;\n\n obj.JacobPattern = [1,0,0;\n 1,1,0;\n 1,1,1]; % Jacobian matrix of model store ODEs\n\n obj.parRanges = [ 0.1 , 5; % ibar, Mean interception capacity [mm]\n 0 , 1; % idelta, Seasonal interception change as fraction of mean [-]\n 1 , 365; % ishift, Maximum interception peak timing [-]\n 1 , 2000; % stot, Maximum soil moisture capacity [mm]\n 0.01, 0.99; % fsm, Fraction of stot that constitutes maximum soil moisture smmax [-]\n 0 ,10; % b, Infiltration excess shape parameter [-]\n 0 , 1; % k1, Percolation time parameter [d-1]\n 0 ,10; % c1, Percolation non-linearity parameter [-]\n 0 ,1; % k2, Baseflow time parameter [d-1]\n 1 , 5]; % c2, Baseflow non-linearity parameter\n\n obj.StoreNames = {\"S1\", \"S2\" \"S3\"}; % Names for the stores\n obj.FluxNames = {\"ei\", \"peff\", \"iex\", \"qie\", \"inf\", \"et1\",...\n \"qex1\", \"pc\", \"et2\", \"qex2\", \"qb\"}; % Names for the fluxes\n\n obj.FluxGroups.Ea = [1 6 9]; % Index or indices of fluxes to add to Actual ET\n obj.FluxGroups.Q = [4 7 10 11]; % Index or indices of fluxes to add to Streamflow\n\n end\n\n % INITialisation function\n function obj = init(obj)\n %Parameters\n theta = obj.theta;\n stot = theta(4); % Total available storage [mm]\n fsm = theta(5); % Fraction of stot that constitutes maximum soil mositure storage [-]\n\n % Auxiliary parameter\n smmax = fsm*stot; % Maximum soil moisture capacity [mm]\n gwmax = (1-fsm)*stot; % Maximum groundwater storage [mm]\n tmax = 365.25; % Length of one growing cycle [d]\n obj.aux_theta = [smmax; gwmax; tmax];\n\n end\n\n % MODEL_FUN are the model governing equations in state-space formulation\n function [dS, fluxes] = model_fun(obj, S)\n % parameters\n theta = obj.theta;\n ibar = theta(1); % Mean interception capacity [mm]\n idelta = theta(2); % Seasonal interception change as fraction of mean [-]\n ishift = theta(3); % Maximum interception peak timing [-]\n b = theta(6); % Infiltration excess shape parameter [-]\n k1 = theta(7); % Percolation time parameter [d-1]\n c1 = theta(8); % Percolation non-linearity parameter [-]\n k2 = theta(9); % Baseflow time parameter [d-1]\n c2 = theta(10); % Baseflow non-linearity parameter\n\n aux_theta = obj.aux_theta;\n smmax = aux_theta(1);\n gwmax = aux_theta(2);\n tmax = aux_theta(3);\n\n % delta_t\n delta_t = obj.delta_t;\n\n % stores\n S1 = S(1);\n S2 = S(2);\n S3 = S(3);\n\n % climate input\n t = obj.t; % this time step\n climate_in = obj.input_climate(t,:); % climate at this step\n P = climate_in(1);\n Ep = climate_in(2);\n T = climate_in(3);\n\n % fluxes functions\n aux_imax = phenology_2(ibar,idelta,ishift,obj.t,tmax,delta_t);\n flux_ei = evap_7(S1,aux_imax,Ep,delta_t);\n flux_peff = interception_1(P,S1,aux_imax);\n flux_iex = excess_1(S1,aux_imax,delta_t);\n flux_qie = saturation_2(S2,smmax,b,flux_peff+flux_iex);\n flux_inf = effective_1(flux_peff+flux_iex,flux_qie);\n flux_et1 = evap_7(S2,smmax,max(0,Ep-flux_ei),delta_t);\n flux_qex1 = saturation_1(flux_inf,S2,smmax);\n flux_pc = percolation_5(k1,c1,S2,smmax,delta_t);\n flux_et2 = evap_7(S3,gwmax,max(0,Ep-flux_ei-flux_et1),delta_t);\n flux_qex2 = saturation_1(flux_pc,S3,gwmax);\n flux_qb = baseflow_5(k2,c2,S3,gwmax,delta_t);\n\n % stores ODEs\n dS1 = P - flux_ei - flux_peff - flux_iex;\n dS2 = flux_inf - flux_et1 - flux_qex1 - flux_pc;\n dS3 = flux_pc - flux_et2 - flux_qex2 - flux_qb;\n\n % outputs\n dS = [dS1 dS2 dS3];\n fluxes = [flux_ei flux_peff flux_iex flux_qie ...\n flux_inf flux_et1 flux_qex1 flux_pc ...\n flux_et2 flux_qex2 flux_qb];\n end\n\n % STEP runs at the end of every timestep\n function obj = step(obj)\n end\n end\nend\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Model files/m_22_vic_10p_3s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3512580594357267}} {"text": "function f = constructor(f, op, varargin)\n%CONSTRUCTOR CHEBFUN3 constructor.\n% Given a function OP of three variables, this code represents it as a\n% CHEBFUN3 object. A CHEBFUN3 object is a low-rank representation\n% expressing a function as a trilinear product of a discrete core tensor\n% and three quasimatrices consisting of univariate functions.\n%\n%\n% Since March 2023, chebfun3f is used by default to construct CHEBFUN3\n% objects. The legacy constructor chebfun3classic can be accessed by\n% providing the 'classic' flag as additional input argument.\n%\n% See also CHEBFUN2, CHEBFUN3T and CHEBFUN3V.\n\n% Copyright 2023 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Parse the inputs:\n[op, dom, pref, fiberDim, vectorize, isEqui, fixedRank] = ...\n parseInputs(op, varargin{:});\n\n% The 'equi' flag can be used only with numeric data:\nif ( isEqui && ~isa(op, 'double') )\n error('CHEBFUN:CHEBFUN3:constructor:equi', ...\n 'The EQUI flag is valid only when constructing from numeric data');\nend\n\nif ( isa(op, 'chebfun3') ) % CHEBFUN3( CHEBFUN3 )\n f = op;\n return\nelseif ( isa(op, 'double') ) % CHEBFUN3( DOUBLE )\n f = chebfun3.chebfun3double(f, op, dom, pref, isEqui);\nelseif ( strcmpi(pref.cheb3Prefs.constructor, 'classic') )\n f = chebfun3.chebfun3classic(f, op, pref, dom, vectorize, fiberDim);\nelse\n f = chebfun3.chebfun3f(f, op, pref, dom, vectorize);\nend\n\nif ( fixedRank )\n % Simplify the rank if requested.\n f = fixTheRank(f , fixedRank);\nend\nend\n%% End of constructor\n\n%%\nfunction [op, dom, pref, fiberDim, vectorize, isEqui, ...\n fixedRank] = parseInputs(op, varargin)\nvectorize = 0;\nisEqui = 0;\nisCoeffs = 0;\nfixedRank = 0;\npref = chebfunpref();\nfiberDim = [];\ndom = [-1 1 -1 1 -1 1];\n\n% Preferences structure given?\nisPref = find(cellfun(@(p) isa(p, 'chebfunpref'), varargin));\nif ( any(isPref) )\n pref = varargin{isPref};\n varargin(isPref) = [];\nend\n\nif ( isa(op, 'char') ) % CHEBFUN3( CHAR )\n op = str2op(op);\nend\n\nfor k = 1:length(varargin)\n if any(strcmpi(varargin{k}, {'trig', 'periodic'}))\n pref.tech = @trigtech;\n elseif strcmpi(varargin{k}, 'eps')\n pref.cheb3Prefs.chebfun3eps = varargin{k+1};\n elseif strcmpi(varargin{k}, 'classic')\n pref.cheb3Prefs.constructor = 'classic';\n elseif strcmpi(varargin{k}, 'chebfun3f')\n pref.cheb3Prefs.constructor = 'chebfun3f';\n elseif strcmpi(varargin{k}, 'rank') % rank is specified.\n fixedRank = varargin{k+1};\n elseif ( isnumeric(varargin{k}) )\n if ( numel(varargin{k}) == 6 ) % domain is specified.\n dom = varargin{k};\n elseif ( numel(varargin{k}) == 3 ) % length is specified.\n if ( k > 1 && strcmpi(varargin{k-1}, 'rank') )\n % Rank is specified, not length. Don't confuse them.\n continue\n else\n % Interpret this as the user wants a fixed degree chebfun3\n % on the domain DOM.\n len = varargin{k};\n [xx, yy, zz] = chebpts3(len(1), len(2), len(3), dom);\n op = op(xx, yy, zz);\n end\n end\n elseif strcmpi(varargin{k}, {'fiberDim'})\n fiberDim = varargin{k+1};\n elseif any(strcmpi(varargin{k}, {'vectorize', 'vectorise'}))\n vectorize = true;\n elseif strcmpi(varargin{k}, 'coeffs')\n isCoeffs = 1;\n elseif strcmpi(varargin{k}, 'equi')\n isEqui = 1;\n end\nend\n\nif ( isCoeffs )\n op = chebfun3.coeffs2vals(op);\nend\n\n% If the vectorize flag is off, do we need to give user a warning?\nif ( ~vectorize && ~isnumeric(op) ) % another check\n [vectorize, op] = vectorCheck(op, dom);\nend\n\nend\n\n%%\nfunction [vectorize, op] = vectorCheck(op, dom)\n% Check for cases like op = @(x,y,z) x*y^2*z\n\nvectorize = false;\n[xx, yy, zz] = ndgrid(dom(1:2), dom(3:4), dom(5:6));\ntry\n A = feval(op, xx, yy, zz);\ncatch\n throwVectorWarning();\n vectorize = true;\n return\nend\n\nA = feval(op, xx, yy, zz);\nif ( any(isinf(A(:) ) ) )\n error('CHEBFUN:CHEBFUN3:constructor:inf', ...\n 'Function returned INF when evaluated');\nelseif ( any(isnan(A(:)) ) )\n error('CHEBFUN:CHEBFUN3:constructor:nan', ...\n 'Function returned NaN when evaluated');\nend\n\nif ( isscalar(A) )\n op = @(x,y,z) op(x,y,z) + 0*x + 0*y + 0*z;\nend\n\nend\n\n%%\nfunction throwVectorWarning()\nwarning('CHEBFUN:CHEBFUN3:constructor:vectorize',...\n ['Function did not correctly evaluate on an array.\\n', ...\n 'Turning on the ''vectorize'' flag. Did you intend this?\\n', ...\n 'Use the ''vectorize'' flag in the CHEBFUN3 constructor\\n', ...\n 'call to avoid this warning message.']);\nend\n%%\nfunction op = str2op(op)\n% OP = STR2OP(OP), finds independent variables in a string and returns an\n% op handle than can be evaluated.\n\nvars = symvar(op); % Independent variables\nnumVars = numel(vars);\nif ( numVars == 0 )\n op = @(x,y,z) eval (op);\n \nelseif ( numVars == 1 )\n op = eval(['@(' vars{1} ', myVarBeta, myVarGamma)' op]);\n \nelseif ( numVars == 2 )\n op = eval(['@(' vars{1} ',' vars{2} ', myVarGamma)' op]);\n \nelseif ( numVars == 3 )\n op = eval(['@(' vars{1} ',' vars{2} ',' vars{3} ')' op]);\n \nelse\n error('CHEBFUN:CHEBFUN3:constructor:str2op:depvars', ...\n 'Too many independent variables in string input.');\nend\n\nend\n\n\n%%\nfunction f = fixTheRank(f , fixedRank)\n% Fix the rank of a CHEBFUN3. Used for calls to constructor with specified\n% rank.\n\nif ( any(fixedRank) < 0 )\n error('CHEBFUN:CHEBFUN3:constructor:fixTheRank:negative', ...\n 'Ranks should all be nonnegative.')\nelseif ( all(fixedRank) )\n [r1, r2, r3] = rank(f);\n t1 = fixedRank(1);\n t2 = fixedRank(2);\n t3 = fixedRank(3);\n \n % What to do with cols?\n if ( r1 > t1 )\n % Truncate cols:\n f.cols = f.cols(:, 1:t1);\n f.core = f.core(1:t1, :, :);\n r1 = t1; % New size of core\n elseif ( r1 < t1 )\n % Pad cols with approprate number of zero cols:\n zCols = chebfun(0, f.cols.domain);\n for jj = r1 : t1 - 1\n f.cols = [f.cols zCols];\n end\n % Pad mode 1 of the core tensor with zeros:\n tempCore = zeros(t1, r2, r3);\n tempCore(1:r1, :, :) = f.core;\n f.core = tempCore;\n r1 = t1; % New size of core\n end\n \n % What to do with rows?\n if ( r2 > t2 )\n % Truncate rows:\n f.rows = f.rows(:,1:t2);\n f.core = f.core(:, 1:t2, :);\n r2 = t2; % New size of core\n elseif ( r2 < t2 )\n % Pad rows with approprate number of zero rows:\n zRows = chebfun(0, f.rows.domain);\n for jj = r2 : t2 - 1\n f.rows = [f.rows zRows];\n end\n % Pad mode 2 of the core tensor with zeros:\n tempCore = zeros(r1, t2, r3);\n tempCore(:, 1:r2, :) = f.core;\n f.core = tempCore;\n r2 = t2; % New size of core\n end\n \n % What to do with tubes?\n if ( r3 > t3 )\n % Truncate tubes:\n f.tubes = f.tubes(:, 1:t3);\n f.core = f.core(:, :, 1:t3);\n elseif ( r3 < t3 )\n % Pad tubes with approprate number of zero tubes:\n zTubes = chebfun(0, f.tubes.domain);\n for jj = r3 : t3 - 1\n f.tubes = [f.tubes zTubes];\n end\n % Pad mode 3 of the core tensor with zeros:\n tempCore = zeros(r1, r2, t3);\n tempCore(:, :, 1:r3) = f.core;\n f.core = tempCore;\n end\nend\n\nend\n\n\n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/constructor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3512536987011174}} {"text": "%% Tilt and Twist Boundaries\n%\n%%\n% If a material deforms through the movement of dislocations, rearrangement\n% of dislocations to a low-energy configuration may happen during\n% deformation (i.e. in slow, geologic deformation) or or afterwards (in\n% many metals). In any case, the arrangement of dislocation walls can lead\n% to so-called subgrains boundaries. If such a boundary is composed of edge\n% dislocations, it is called a tilt boundary and the rotation axis relating\n% both parts of the grain at each side can be expected to be within the\n% boundary plane (ideally parallel to the edge dislocation line). If the\n% boundary is composed of screw dislocations, the rotation axis should be\n% normal to the boundary. Between those end-members, there are general\n% boundaries where the rotation axis is not easily related to the type of\n% dislocations unless further information is available.\n%\n% In this chapter we discuss the computation of the misorientation axes at\n% subgrain boundaries and discuss whether they vote for twist or tilt\n% boundaries. We start by importing an sample EBSD data set and computing\n% all subgrain boundaries as it is described in more detail in the chapter\n% .\n\n% load some test data\nmtexdata forsterite silent\n\n% remove one pixel grains\n[grains,ebsd.grainId] = calcGrains(ebsd('indexed'));\nebsd(grains(grains.grainSize<5)) = [];\n\n% compute subgrain boundaries with 1.5 degree threshold angle\n[grains,ebsd.grainId] = calcGrains(ebsd('indexed'),'threshold',[1*degree, 15*degree]);\n\n% lets smooth the grain boundaries a bit\ngrains = smooth(grains,5);\n\n% set up the ipf coloring\ncKey = ipfColorKey(ebsd('fo').CS.properGroup);\ncKey.inversePoleFigureDirection = xvector;\ncolor = cKey.orientation2color(ebsd('fo').orientations);\n\n% plot the forsterite phase\nplot(ebsd('fo'),color,'faceAlpha',0.5,'figSize','large')\n\n% init override mode\nhold on\n\n% plot grain boundares\nplot(grains.boundary,'linewidth',2)\n\n% compute transparency from misorientation angle\nalpha = grains('fo').innerBoundary.misorientation.angle / (5*degree);\n\n% plot the subgrain boundaries\nplot(grains('fo').innerBoundary,'linewidth',1.5,'edgeAlpha',alpha,'linecolor','b');\n\n% stop override mode\nhold off\n\n%%\n% In the above plot we have marked all subgrain boundaries in blue and\n% adjusted the transparency value according to the misorientation angle.\n%\n%% Misorientation Axes\n%\n% When analysing the misorientation axes of the subgrain boundary\n% misorientations we need to distinguish whether we look at the\n% misorientation axes in crystal coordinates or in specimen coordinates.\n% Lets start with the misorientation axes in crystal coordinates which can\n% directly be computed by the command .\n\n% extract the Forsterite subgrain boundaries\nsubGB = grains('fo').innerBoundary;\n\n% plot the misorientation axes in the fundamental sector\nplot(subGB.misorientation.axis,'fundamentalRegion','figSize','small')\n\n%%\n% Obviously from the above plot it is not easy to judge about prefered\n% misorientation axes. We get more insight if we of the misorientation axes and look for\n% .\n\n% compute the density distribution of misorientation axes\ndensity = calcDensity(subGB.misorientation.axis,'halfwidth',3*degree);\n\n% plot them\nplot(density,'figSize','small')\nmtexColorbar\n\n% find the two prefered misorientation axes\n[~,hkl] = max(density,'numLocal',2); round(hkl)\n\n%%\n% We find two preferred misorientation axes - (001) and (071). *TODO*: can\n% this be interpreted?\n% \n%% The misorientation axis in specimen coordinates\n%\n% The computation of the misorientation axis in specimen coordinates is a\n% little bit more complicated as it is impossible using only the\n% misoriention. In fact we require the adjacent orientations on both sides\n% of the subgrain boundaries. We can find those by making use of the\n% |ebsdId| stored in the grain boundaries. The command\n\noriGB = ebsd('id',subGB.ebsdId).orientations\n\n%%\n% results in a $N \\times 2$ matrix of orientations with rows corresponding\n% to the boundary segments and two columns for both sides of the boundary.\n% The misorientation axis in specimen coordinates is again computed by the\n% command \n\naxS = axis(oriGB(:,1),oriGB(:,2),'antipodal')\n\n% plot the misorientation axes\nplot(axS,'MarkerAlpha',0.2,'MarkerSize',2,'figSize','small')\n\n%%\n% We have used here the option |antipodal| as we have no fixed ordering of\n% the grains at the two sides of the grain boundaries. For a more\n% quantitative analysis we again compute the corresponding density\n% distribution and find the preferred misorientation axes in specimen\n% coordinates\n\ndensity = calcDensity(axS,'halfwidth',5*degree);\nplot(density,'figSize','small')\nmtexColorbar\n\n[~,pos] = max(density)\nannotate(pos)\n\n%% Tilt and Twist Boundaries\n%\n% Subgrain boundaries are often assumed to form during deformation by the\n% accumulation of edge or screw dislocations. In the first extremal case of\n% exclusive edge dislocations the misorientation axis is parallel to the\n% deformation line and within the boundary plane. Such boundaries are\n% called *tilt boundaries*. In the second extremal case of exclusive screw\n% dislocations the misorientation axis is the screw axis and is parallel to\n% the boundary normal. Such boundaries are called *twist boundaries*. \n%\n% In the case of 2d EBSD data one usually has not the full boundary\n% information, but only the trace of the boundary with the measurement\n% surface. Hence, it is impossible to distinguish tilt and twist\n% boundaries. However, for twist boundaries misorientation axis must be normal\n% to the boundary trace. This means, if the misorientation axis lays in the\n% measurement plane and normal to the boundary trace, the boundary is quite \n% likely to be a twist boundary. At the other hand, if the misorientation axis \n% is parallel to the trace of a boundary, the boundary is quite likely to be a\n% tilt boundary. \n% We can be easily check the latter situation from our EBSD data, which allows us to\n% exclude certain boundaries to be twist boundaries and to be most likely tilt\n% boundaries To do so, we colorize in the following plot all subgrain boundaries\n% according to the angle between the boundary trace and the misorientation axis.\n% Blue subgrain boundaries are very likely tilt boundaries, while red subgrain\n% boundaries are can be either tilt or twist boundaries.\n\nplot(ebsd('fo'),color,'faceAlpha',0.5,'figSize','large')\n\n% init override mode\nhold on\n\n% plot grain boundares\nplot(grains.boundary,'linewidth',2)\n\n% colorize the subgrain boundaries according the angle between boundary\n% trace and misorientation axis\nplot(subGB,angle(subGB.direction,axS)./degree,'linewidth',2)\nmtexColorMap blue2red\nmtexColorbar\n\nhold off\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/GrainBoundaries/TiltAndTwistBoundaries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3511709017424895}} {"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 CHANNEL_CHANNEL-EXAMPLE geometry and prints associated input files\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Channel_Channel()\n\n%\n% Grid Parameters (MAKE SURE MATCHES IN input2d !!!)\n%\nNx = 512; % # of Eulerian Grid Pts. in x-Direction (MUST BE EVEN!!!)\nNy = 512; % # 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 %\nds= min(Lx/(2*Nx),Ly/(2*Ny)); % Lagrangian spacing\nL = 0.9*Lx; % Length of Channel\nw = 0.2*Ly; % Width of Channel\nx0 = 0.3; % x-Center for Cylinder\ny0 = 0.5; % y-Center for Cylinder\nr = w/10; % Radii of Cylinder\nstruct_name = 'channel'; % Name for .vertex, .spring, etc files.\n\n\n% Call function to construct geometry\n[xLag,yLag] = give_Me_Channel_Immsersed_Boundary_Geometry(ds,L,w,Lx,Ly);\n[xLag_C,yLag_C] = give_Me_Cylinder_Immsersed_Boundary_Geometry(ds,r,x0,y0);\n[xLag_V,yLag_V] = give_Me_Piston_IB_Geometry(ds,w,Lx,Ly);\n\n\nNpts = length(xLag_C);\nNPistonStart = length(xLag);\nfprintf('\\n\\n POSSIBLE WARNING!!! \\n\\n');\nfprintf('# of pts in a cell: %d\\n',Npts); \nfprintf('If it is not EVEN...there will be a problem :)\\n'); \nfprintf('Change radius, r, or ds slightly to try to make it even\\n\\n\\n');\n\n% Compute Curvatures\nC = compute_Curvatures(xLag_C,yLag_C);\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_C,yLag_C,'r-'); hold on;\nplot(xLag_V,yLag_V,'k.-'); hold on;\n\nplot(xLag,yLag,'*'); hold on;\nplot(xLag_C,yLag_C,'g*'); hold on;\nxlabel('x'); ylabel('y');\naxis([0 Lx 0 Ly]);\n\n% Create different Bubbles\nxLag_C1 = xLag_C; yLag_C1 = yLag_C; % Bubble 1\nxLag_C2 = xLag_C+33.5*r; yLag_C2 = yLag_C+2*r; % Bubble 2\nxLag_C3 = xLag_C+1.5*r; yLag_C3 = yLag_C-2.5*r; % Bubble 3\n\n% Combine Geometry Files into ONE Vector\n%xLag = [xLag_C1 xLag_C2 xLag_C3 xLag xLag_V];\n%yLag = [yLag_C1 yLag_C2 yLag_C3 yLag yLag_V];\nxLag = [xLag_C1 xLag_C2 xLag_C3 xLag_V];\nyLag = [yLag_C1 yLag_C2 yLag_C3 yLag_V];\nyLag = yLag - 0.375;\n\n\nfirst_Index = 3*length(xLag_C1)+1;\nNcell_Lag_Pts = [length(xLag_C1) length(xLag_C2) length(xLag_C3)];\n\n% Combine CELL Geometry files into ONE vector for springs/beams (not necessary...just easier to count)\nxLag_Cells = [xLag_C1 xLag_C2 xLag_C3];\nyLag_Cells = [yLag_C1 yLag_C2 yLag_C3];\n\nplot(xLag_Cells,yLag_Cells,'k*'); hold on;\n\n%\n% Prints .vertex file!\n%\nprint_Lagrangian_Vertices(xLag,yLag,struct_name);\n\n%\n% Prints .spring file!\n%\nk_Spring = 2.5e7;\nNPistonStart = first_Index; % Gives starting index of piston instead of num of channel pts\nNPiston = length(xLag_V);\nprint_Lagrangian_Springs(xLag_C,yLag_C,xLag,yLag,k_Spring,ds,r,struct_name,NPistonStart,NPiston);\nplot(xLag(NPistonStart),yLag(NPistonStart),'r*'); hold on;\nplot(xLag(NPistonStart+NPiston-1),yLag(NPistonStart+NPiston-1),'g*'); hold on\n\n%\n% Prints .beam file!\n%\nk_Beam = 1e12; \nprint_Lagrangian_Beams(xLag_C,yLag_C,k_Beam,C,struct_name);\n\n\n%\n% Prints .coagulation file!\n%\nstarting_index = 1; % index of first cellular Lagrangian Pt.\nthreshold_radius = 0.075; % how close do cells need to be to form a bond\nbond_strength = 1e3; % bond strength\nfracture_force = 1e2; % how strong of force to break bond\nprint_Lagrangian_Coagulation_Inputs(struct_name,Ncell_Lag_Pts,starting_index,threshold_radius,fracture_force,bond_strength);\n\n\n%\n% Prints .target file!\n%\nk_Target = 1e7;\nfprintf('For update_target_pts: last target pt index before piston: %d\\n\\n\\n',0);\nprint_Lagrangian_Target_Pts(xLag,k_Target,struct_name,first_Index);\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 COAGULATION Parameters to the file struct.vertex\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Coagulation_Inputs(struct_name,Ncell_Lag_Pts,starting_index,threshold_radius,fracture_force,bond_strength)\n\n % Ncell_Lag_Pts: -gives # of Lag. Pts in each cell (# of Lag. Pts that compose each cell)\n % starting_index: -gives first index of first cell Lag. Pt. in vertex file\n % -NOTE: IB2d Assumes all cell Lag. Pts are next to each other in .vertex file\n % threshold_radius: -how close do cells need to be to form a bond\n % fracture_force: -how strong of force to break bond between cells\n\n Ncells = length(Ncell_Lag_Pts); % gives total number of cells\n\n coag_fid = fopen([struct_name '.coagulation'], 'w');\n\n fprintf(coag_fid, '%d\\n', starting_index ); % Prints first index of a Lag. Pt. associated to a Cell\n fprintf(coag_fid, '%d\\n', threshold_radius ); % Prints threshold radii \n fprintf(coag_fid, '%d\\n', bond_strength ); % Prints bond strength \n fprintf(coag_fid, '%d\\n', fracture_force ); % Prints fracture_force\n\n\n %Loops over all CELLs.\n for s = 1:Ncells\n fprintf(coag_fid, '%1.16e\\n', Ncell_Lag_Pts(s) );\n end\n\n fclose(coag_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,first_index)\n\n N = length(xLag) - first_index + 1; % # of target points (e.g., the walls of channel)\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 = 0:N-1 % Loops over N target pts...just starts at zero bc of how first_index is defined\n fprintf(target_fid, '%d %1.16e\\n', s+first_index, k_Target);\n end\n\n fclose(target_fid); \n \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints SPRING points to a file called struct.spring\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Lagrangian_Springs(xLag,yLag,xLagAll,yLagAll,k_Spring,ds,r,struct_name,NPistonStart,NPiston)\n\n N = length(xLag);\n \n spring_fid = fopen([struct_name '.spring'], 'w');\n\n fprintf(spring_fid, '%d\\n', 3*N + 3/2*N + (NPiston-1) ); %N MUST BE EVEN!\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %SPRINGS BETWEEN VERTICES\n for s = 1:3*N\n if s < N\n x1 = xLag(s); y1 = yLag(s);\n x2 = xLag(s+1); y2 = yLag(s+1);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n elseif s==N\n %Case s=N\n x1 = xLag(s); y1 = yLag(s);\n x2 = xLag(1); y2 = yLag(1);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, 1, k_Spring, ds_Rest); \n elseif ( ( s>N ) && ( s<2*N ) )\n x1 = xLagAll(s); y1 = yLagAll(s);\n x2 = xLagAll(s+1); y2 = yLagAll(s+1);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n elseif s==2*N\n x1 = xLagAll(s); y1 = yLagAll(s);\n x2 = xLagAll(N+1); y2 = yLagAll(N+1);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, N+1, k_Spring, ds_Rest); \n elseif ( ( s>2*N ) && ( s<3*N ) )\n x1 = xLagAll(s); y1 = yLagAll(s);\n x2 = xLagAll(s+1); y2 = yLagAll(s+1);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds_Rest); \n elseif s==3*N\n x1 = xLagAll(s); y1 = yLagAll(s);\n x2 = xLagAll(2*N+1); y2 = yLagAll(2*N+1);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, 2*N+1, k_Spring, ds_Rest); \n end\n end\n \n for s=1:N/2\n x1 = xLagAll(s); y1 = yLagAll(s);\n x2 = xLagAll(s+N/2); y2 = yLagAll(s+N/2);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+N/2, k_Spring/5000, ds_Rest); \n end\n \n for s=1:N/2\n x1 = xLagAll(N+s); y1 = yLagAll(N+s);\n x2 = xLagAll(N+s+N/2); y2 = yLagAll(N+s+N/2);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', N+s, N + s+N/2, k_Spring/5000, 2*r); \n end\n \n for s=1:N/2\n x1 = xLagAll(2*N+s); y1 = yLagAll(2*N+s);\n x2 = xLagAll(2*N+s+N/2); y2 = yLagAll(2*N+s+N/2);\n ds_Rest = sqrt( (x1-x2)^2 + (y1-y2)^2 );\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', 2*N+s, 2*N + s+N/2, k_Spring/5000, 2*r); \n end\n \n for s=NPistonStart:NPistonStart+NPiston-2\n fprintf(spring_fid, '%d %d %1.16e %1.16e\\n', s, s+1, k_Spring, ds);\n end\n fclose(spring_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', 3*N );\n\n %spring_force = kappa_spring*ds/(ds^2);\n\n %BEAMS BETWEEN VERTICES\n for s = 1:N\n if s==1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',N, s, s+1, k_Beam, C(s) ); \n elseif s <= N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C(s) ); \n elseif s==N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, 1, k_Beam, C(s) );\n end\n end\n \n for s = N+1:2*N\n if s==N+1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',2*N, s, s+1, k_Beam, C(s-N) ); \n elseif s <= 2*N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C(s-N) ); \n elseif s==2*N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, N+1, k_Beam, C(s-N) );\n end\n end\n \n for s = 2*N+1:3*N\n if s==2*N+1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',3*N, s, s+1, k_Beam, C(s-2*N) ); \n elseif s <= 3*N-1 \n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, s+1, k_Beam, C(s-2*N) ); \n elseif s==3*N\n fprintf(beam_fid, '%d %d %d %1.16e %1.16e\\n',s-1, s, 2*N+1, k_Beam, C(s-2*N) );\n end\n end\n fclose(beam_fid); \n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes \"curvature\" of ellipse\n% \n% NOTE: not curvature in the traditional geometric sense, in the 'discrete'\n% sense through cross product.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C = compute_Curvatures(xLag,yLag)\n\n%a-x component (rmin)\n%b-y component (rmax)\n%C = ab / ( sqrt( a^2*sin(t)^2 + b^2*cos(t)^2 ) )^3\n\nN = length(xLag);\nC = zeros( N );\n\n%Note: needs to be done same order as you print .beam file!\nfor i=1:N\n \n % Pts Xp -> Xq -> Xr (same as beam force calc.)\n \n if ( (i > 1) && (i < N) )\n \n Xp = xLag(i-1); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(i-1); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==1)\n \n Xp = xLag(N); Xq = xLag(i); Xr = xLag(i+1);\n Yp = yLag(N); Yq = yLag(i); Yr = yLag(i+1);\n \n elseif (i==N)\n \n Xp = xLag(N-1); Xq = xLag(N); Xr = xLag(1);\n Yp = yLag(N-1); Yq = yLag(N); Yr = yLag(1);\n \n end\n \n C(i) = (Xr-Xq)*(Yq-Yp) - (Yr-Yq)*(Xq-Xp); %Cross product btwn vectors\n \nend\n\n\n \n \n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for channel\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Channel_Immsersed_Boundary_Geometry(ds,L,w,Lx,Ly)\n\n% The immsersed structure is a channel %\nx = (Lx-L)/2:ds:(L+(Lx-L)/2); %xPts\nyBot = (Ly-w)/2; %yVal for bottom of Channel\nyTop = Ly - (Ly-w)/2; %yVal for top of Channel\n\nxLag = [x x];\nyLag = [yBot*ones(1,length(x)) yTop*ones(1,length(x))];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives Lag. Pts for Piston\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Piston_IB_Geometry(ds,w,Lx,Ly)\n\nyBot = (Ly-w)/2; %yVal for bottom of Channel\nyTop = Ly - (Ly-w)/2; %yVal for top of Channel\n\nyLag = Ly/2-0.05:ds:Ly/2+0.05;\nxLag = 0.25*ones(1,length(yLag));\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: creates the Lagrangian structure geometry for cylinder\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xLag,yLag] = give_Me_Cylinder_Immsersed_Boundary_Geometry(ds,r,x0,y0)\n\n% The immsersed structure is a cylinder %\n\ndtheta = ds/ (2.08*r);\ntheta = 0; i=1;\nwhile theta < 2*pi\n xLag(i) = x0 - r*cos(theta);\n yLag(i) = y0 - r*sin(theta);\n theta = theta + dtheta;\n i=i+1;\nend\n\n%ds_Rest = sqrt( ( xLag(2) - xLag(3) )^2 + ( xLag(2) - xLag(3) )^2 );\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_Coagulation/Example_Testing_Thru_Boundaries/Works_on_512x128/Channel_Channel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3510741188498443}} {"text": "% Copyright 2017 Lime Microsystems Ltd.\n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% http://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%\n% provide EVM for random sequences\n% W-CDMA does not enforce equal amplitude signals, so we need AGC for each signal\n% we assume we are dealing with BPSK or QAM, so rms amplitude should be unity\nfunction evm=WCDMAULevm(x,qam)\n agc=1/sqrt(sum(x.*conj(x))/length(x));\n y=x*agc;\n\tevmref2=sum(abs(qam))/length(qam);\n\t[evm,loc]=min(abs(repmat(conj(qam'),1,length(y))-repmat(y,length(qam),1))); % decode QAM symbols\n%\tevm=evm./abs(qam(loc)); % some EVMs define relative to desired symbol\n\tevm/=evmref2; % some EVMs define relative to rms of QAM symbol table\nend", "meta": {"author": "myriadrf", "repo": "LimeSDR_Workshop", "sha": "c3bfe944a89836d6eadc67a0352f2b5b7e1727a4", "save_path": "github-repos/MATLAB/myriadrf-LimeSDR_Workshop", "path": "github-repos/MATLAB/myriadrf-LimeSDR_Workshop/LimeSDR_Workshop-c3bfe944a89836d6eadc67a0352f2b5b7e1727a4/octave/WCDMA2.1/WCDMAULevm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3509611636480814}} {"text": "function f = compose(f, op)\n%COMPOSE Compose command for SPHEREFUNV objects.\n% F = COMPOSE(F, G) returns the composition G(F) of the SPHEREFUNV object\n% F and a CHEBFUN3 or CHEBFUN3V with three components G.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Deal with empty CHEBFUN objects:\nif ( isempty(f) || isempty(op) )\n if ( isa(op, 'chebfun3v') )\n f = spherefunv();\n else\n f = spherefun();\n end\nend\n\n% F is real and has three components, so we can compose with a CHEBFUN3 or\n% CHEBFUN3V.\n% TODO? compose when op is a spherefun object?\n\nif ( isa(op, 'chebfun3') )\n % Get components of F:\n f1 = f.components{1};\n f2 = f.components{2};\n f3 = f.components{3};\n \n % Check that image(f) is in domain(op):\n rangef = minandmax2est(f); % Estimate of image(f).\n tol = 100 * chebfun2eps * max(vscale(f), vscale(op)) * ...\n norm(f1.domain, inf); % Tolerance.\n if ( ~isSubset(rangef, op.domain, tol) )\n error('CHEBFUN:SPHEREFUNV:COMPOSE:DomainMismatch3', ...\n 'OP(F) is not defined, since image(F) is not contained in domain(OP).')\n end\n \n % Call constructor:\n f = spherefun(@(x,y,z) op(feval(f1, x, y, z), feval(f2, x, y, z), ...\n feval(f3, x, y, z)));\n \nelseif ( isa(op, 'chebfun3v') )\n % Check that OP has three components:\n if ( op.nComponents ~= 3 )\n error('CHEBFUN:SPHEREFUNV:compose:nComponents', ...\n 'CHEBFUN3V(SPHEREFUNV) is defined for CHEBFUN3V objects with 3 components.')\n end\n \n % Get components of op:\n op1 = op(1);\n op2 = op(2);\n op3 = op(3);\n \n % Get components of f:\n f1 = f.components{1};\n f2 = f.components{2};\n f3 = f.components{3};\n \n % Check that image(f) is in domain(op):\n rangef = minandmax2est(f); % Estimate of image(f).\n tol = 100 * chebfun2eps * max(vscale(f), vscale(op)) * ...\n norm(f1.domain, inf); % Tolerance.\n if ( ~isSubset(rangef, op1.domain, tol) )\n error('CHEBFUN:SPHEREFUNV:COMPOSE:DomainMismatch3v', ...\n 'OP(F) is not defined, since image(F) is not contained in domain(OP).')\n end\n \n % Calling directly the constructor for [ op1(f), op2(f), op3(f) ] as below\n % seems to be slightly faster than building a spherefun for each component\n % and then calling the spherefunv constructor on the three spherefuns.\n \n % Call constructor:\n f = spherefunv(@(x,y,z) op1(feval(f1, x, y, z), feval(f2, x, y, z), ...\n feval(f3, x, y, z)), ...\n @(x,y,z) op2(feval(f1, x, y, z), feval(f2, x, y, z), ...\n feval(f3, x, y, z)), ...\n @(x,y,z) op3(feval(f1, x, y, z), feval(f2, x, y, z), ...\n feval(f3, x, y, z)));\n \nelse\n error('CHEBFUN:SPHEREFUNV:COMPOSE:OP', ...\n 'Can compose a SPHEREFUNV with a CHEBFUN3 or CHEBFUN3V.')\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/@spherefunv/compose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.35088198245842517}} {"text": "function op = linop_handles( sz, Af, At, cmode )\n%LINOP_HANDLES Linear operator from user-supplied function handles.\n%OP = LINOP_HANDLES( SZ, AF, AT, CMODE )\n% Constructs a TFOCS-compatible linear operator from separate function\n% handles that compute the forward and adjoint operations. The first\n% argument, SZ, gives the size of the linear operator; and the forward\n% and adjoint handles are AF and AT, respectively.\n% \n% If the inputs and outputs are simple vectors, then SZ can take the\n% standard Matlab form [M,N], where N is the input length and M is the\n% output length. If the input or output is a matrix or array, then SZ\n% should take the form { S_in, S_out }, where S_in is the size of the\n% input and S_out is the size of the output.\n%\n% If the input or output space of the operator is complex, then the\n% CMODE string must be supplied, which describes the forward operation:\n% 'R2R': real input and output\n% 'R2C': real input, complex output\n% 'C2R': complex input, real output\n% 'C2C': complex input, complex output\n% If CMODE is not supplied, then 'R2R' is assumed. If the operator\n% detects a complex input or output when it is not expected, then an\n% error results. Therefore, you must make sure that your operators \n% return real values when they are expected to do so.\n\nerror(nargchk(3,4,nargin));\nif numel( sz ) ~= 2,\n error( 'Size must have two elements.' );\nelseif isnumeric( sz ),\n sz = { [sz(2),1], [sz(1),1] };\nelseif ~isa( sz, 'cell' ),\n error( 'Invalid operator size specification.' );\nend\nif ~isa( Af, 'function_handle' ) || ~isa( At, 'function_handle' ),\n error( 'Second and third arguments must be function handles.' );\nend\nif nargin < 4 || isempty( cmode ),\n cmode = 'R2R';\nelseif ~ischar( cmode ) || size( cmode, 1 ) ~= 1,\n error( 'Fourth argument must be a string.' );\nelse\n cmode = upper( cmode );\nend\n\nswitch cmode,\n case 'R2R', op = @(x,mode)linop_handles_r2r( sz, Af, At, x, mode );\n case {'R2C','R2CC'}, op = @(x,mode)linop_handles_r2c( sz, Af, At, x, mode );\n case {'C2R','CC2R'}, op = @(x,mode)linop_handles_c2r( sz, Af, At, x, mode );\n case 'C2C', op = @(x,mode)linop_handles_c2c( sz, Af, At, x, mode );\n otherwise,\n error( 'Invalid complex mode: %s', cmode );\nend\n\nfunction y = linop_handles_r2r(sz, Af, At, x, mode )\nswitch mode,\n case 0, y = sz;\n case 1, y = realcheck( Af( realcheck( x ) ) );\n case 2, y = realcheck( At( realcheck( x ) ) );\nend\n\nfunction y = linop_handles_r2c(sz, Af, At, x, mode )\nswitch mode,\n case 0, y = sz;\n case 1, y = Af( realcheck( x ) );\n case 2, y = realcheck( At( x ) );\nend\n\nfunction y = linop_handles_c2r(sz, Af, At, x, mode )\nswitch mode,\n case 0, y = sz;\n case 1, y = realcheck( Af( x ) );\n case 2, y = At( realcheck( x ) );\nend\n\nfunction y = linop_handles_c2c(sz, Af, At, x, mode )\nswitch mode,\n case 0, y = sz;\n case 1, y = Af( x );\n case 2, y = At( x );\nend\n\nfunction y = realcheck( y )\nif ~isreal( y ), \n error( 'Unexpected complex value in linear operation.' );\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/linop_handles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.350509454305113}} {"text": "function [nb] = find_triangle_neighbours(pnt, tri)\n\n% FIND_TRIANGLE_NEIGHBOURS determines the three neighbours for each triangle\n% in a mesh. It returns NaN's if the triangle does not have a neighbour on \n% that particular side.\n% \n% [nb] = find_triangle_neighbours(pnt, tri)\n\n% Copyright (C) 2003, 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\nnpnt = size(pnt,1);\nntri = size(tri,1);\n\n% each triangle has maximally three neighbours, assuming that the \n% surface mesh is not degenerate\nnb = nan(size(tri));\n\n% for i=1:ntri\n% for j=setdiff(1:ntri, i)\n% if length(intersect(tri(i,[1 2]), tri(j,:)))==2\n% nb(i,1) = j;\n% continue;\n% end\n% if length(intersect(tri(i,[2 3]), tri(j,:)))==2\n% nb(i,2) = j;\n% continue;\n% end\n% if length(intersect(tri(i,[3 1]), tri(j,:)))==2\n% nb(i,3) = j;\n% continue;\n% end\n% end\n% if all(~isnan(nb(i,:)))\n% continue;\n% end\n% end\n\nfor i=1:ntri\n % find all neighbouring triangles\n tmp1 = (tri==tri(i,1));\n tmp2 = (tri==tri(i,2));\n tmp3 = (tri==tri(i,3));\n tmp = (tmp1|tmp2|tmp3);\n sel = find(sum(tmp,2)==2);\n\n % ensure that each neighbour is assigned to the proper edge\n if length(sel)>3\n ft_error('more than three neighbours found for triangle %d', i);\n else\n for j=1:length(sel)\n if isempty(setdiff(intersect(tri(i,:), tri(sel(j),:)), tri(i,[1 2])))\n nb(i,1) = sel(j);\n elseif isempty(setdiff(intersect(tri(i,:), tri(sel(j),:)), tri(i,[2 3])))\n nb(i,2) = sel(j);\n elseif isempty(setdiff(intersect(tri(i,:), tri(sel(j),:)), tri(i,[3 1])))\n nb(i,3) = sel(j);\n end\n end\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/forward/private/find_triangle_neighbours.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3502600633702492}} {"text": "\nclassdef ARdrone < quadcopter\n properties\n config = 'OUTDOOR'; % Indoor/outdoor dynamics\n % Performance Parameters\n battery_capacity = 1000;\t% Maximum battery capacity (mAh)\n battery_voltage = 11.1;\t% Maximum battery voltage (V)\n flight_time = 720; \t% Rated flight time (s)\n end\n methods\n % Constructor\n function [this] = ARdrone(varargin)\n % Call the super class\n this@quadcopter(varargin);\n \n % Create the dynamics of a quadcopter\n this.SENSORS = this.CreateSENSORS(); % Get the sensor parameters\n this.DYNAMICS = this.CreateDYNAMICS();\n this.GEOMETRY = this.CreateGEOMETRY();\n this.radius = this.GEOMETRY.length/2; % Use the \"length\" to define the radius\n \n % //////////////// Check for user overrides ///////////////////\n this = this.ApplyUserOverrides(varargin); % Recursive overrides\n % /////////////////////////////////////////////////////////////\n end\n % Setup\n function [this] = setup(this,localXYZVelocity,localXYZrotations)\n % This function calculates the intial state for a quadrotor\n % object.\n \n % For a state vector defined as x_k:\n % [x,y,z,phi,theta,psi,dx,dy,dz,wx,wy,wz]\n \n % THIS MODEL OPERATES IN THE GLOBAL FRAME\n % p0 = this.GetGLOBAL('position'); % True global position\n % v0 = this.GetGLOBAL('velocity'); % True global velocity\n % % GET THE ROTATION MATRIX fixed local axes -> rotated global pose\n % eta0 = OMAS_geometry.eulersToRotationMatrix(localXYZrotations);\n % % Build an initial (global) state vector\n % vecR0 = reshape(R0',9,1); % Defines local vector to global vector\n % omega0 = zeros(3,1);\n % x0 = [p0;v0;vecR0;omega0];\n \n p0 = this.GetGLOBAL('position'); % True global position\n v0 = this.GetGLOBAL('velocity'); % True global velocity\n eta0 = localXYZrotations;\n omega0 = zeros(3,1);\n x0 = [p0;eta0;v0;omega0];\n \n % ASSIGN THE LOCAL FRD STATE\n this.SetGLOBAL('priorState',x0);\n this.localState = x0;\n end\n % Main\n function [this] = main(this,ENV,varargin)\n \n % //////////// CHECK FOR NEW INFORMATION UPDATE ///////////////\n % Update the agent with the environmental data\n [this,~,~] = this.GetAgentUpdate(ENV,varargin{1});\n % /////////////////////////////////////////////////////////////\n \n % The state reference\n desiredPosition = [1;1;0];\n \n % Call the controller loop\n this = this.Controller(ENV,desiredPosition);\n \n % /////////////// RECORD THE AGENT-SIDE DATA //////////////////\n this.DATA.inputNames = {'$\\dot{x}$ (m/s)','$\\dot{y}$ (m/s)','$\\dot{z}$ (m/s)',...\n '$p$ (rad/s)','$q$ (rad/s)','$r$ (rad/s)'};\n % Record the control inputs\n this.DATA.inputs(1:length(this.DATA.inputNames),ENV.currentStep) = this.localState(7:end); \n end\n end\n %% ////////////////////// AUXILLARY METHODS ///////////////////////////\n methods\n % Get the state update (using ode45)\n function [x_k_plus] = UpdateLocalState(this,ENV,x_k,y_desired)\n % This function computes the state update for the current agent\n % using the ode45 function.\n \n % Integrate across the time delta \"dt\"\n opts = odeset('RelTol',1e-2,'AbsTol',ENV.dt*1E-1);\n \n [~,Xset] = ode45(@(t,X) this.ClosedLoopDynamics_position(X,y_desired),[0 ENV.dt],x_k,opts);\n % [~,Xset] = ode45(@(t,X) this.ClosedLoopDynamics_velocity(X,y_desired),[0 ENV.dt],x_k,opts);\n \n % Assign the integral state\n x_k_plus = Xset(end,:)';\n end\n % ARdrone Dynamics (Closed-loop)\n function [dxdt] = ClosedLoopDynamics_position(this,x_k,p_desired)\n \n % Extract the current state properties\n % p_k = x_k(1:3,1);\n % eta_k = x_k(4:6,1);\n % v_k = x_k(7:9,1);\n % w_k = x_k(10:12,1);\n % x_k = [p_desired(1:3);zeros(3,1);[0;0;psi_desired];zeros(3,1)];\n \n psi_desired = 0;\n % Define the desired state\n x_desired = [...\n p_desired(1:3);...\n [0;0;psi_desired];...\n zeros(3,1);...\n zeros(3,1)];\n \n % Extract DYNAMIC parameters\n e3 = this.DYNAMICS.e3;\n g = this.DYNAMICS.g;\n m = this.DYNAMICS.m;\n I = this.DYNAMICS.I;\n \n % X = [dx dy dz wx wy wz ddx ddy ddz dwx dwy dwz]\n % State matrix\n A = this.DYNAMICS.A;\n A(1:6,7:12) = eye(6);\n A(7:9,4:6) = g*[ sin(psi_desired), cos(psi_desired), 0;\n -cos(psi_desired), sin(psi_desired), 0;\n 0, 0, 0];\n% A_prev = zeros(12);\n% A_prev(1:3,4:6) = eye(3);\n% A_prev(4:6,7:9) = g*[ sin(psi_desired), cos(psi_desired), 0;\n% -cos(psi_desired), sin(psi_desired), 0;\n% 0, 0, 0];\n% A_prev(7:9,10:12)=eye(3);\n \n % Input matrix\n B = this.DYNAMICS.B;\n B(7:9,1) = e3/m;\n B(10:12,2:4) = inv(I);\n \n % LQR control gain\n [K,~,~] = lqr(A,B,eye(12),eye(4));\n % Calculate the error\n e_k = x_k - x_desired;\n du_k = -K*e_k;\n % Calculate the inputs\n u_k = [m*g;0;0;0] + du_k;\n \n % Provide the inputs to the open-loop dynamics\n [dxdt] = this.OpenLoopDynamics(x_k,u_k);\n end\n % Quadcopter Dynamics (Open-loop)\n function [dxdt] = OpenLoopDynamics(this,x_k,u_k)\n % Designed for a state vector defined as:\n % x_k = [x,y,z,phi,theta,psi,dx,dy,dz,p,q,r]\n \n % Extract the state parameters\n eta_k = x_k(4:6,1);\n v_k = x_k(7:9,1);\n w_k = x_k(10:12,1);\n \n % Define the rotation matrix from the euler angles\n% R_k = reshape(x_k(7:15),3,3);\n R_k = OMAS_geometry.eulersToRotationMatrix(eta_k);\n\n % Extract the inputs\n f = u_k(1);\n tau = u_k(2:4);\n \n % Get the constants\n m = this.DYNAMICS.m;\n g = this.DYNAMICS.g;\n I = this.DYNAMICS.I;\n e3 = this.DYNAMICS.e3;\n \n % nonlinear dynamics based on rotation dynamics\n p_dot = v_k;\n v_dot = f/m*R_k*e3-g*e3;\n % Euler angles\n %R_dot = R_k*skew(w_k);\n %eta_dot = OMAS_geometry.rotationMatrixToEulers(R_dot);\n eta_dot = w_k;\n %vecR_dot = reshape(R_dot,9,1);\n \n w_dot = inv(I)*(tau-skew(w_k)*I*w_k);\n \n % THE STATE DIFFERENCE\n dxdt = [p_dot;eta_dot;v_dot;w_dot];\n end\n % Global update from the new state\n function [this] = GlobalUpdate(this,x_k_plus)\n % This function updates the global structure from the new state\n % definition: [p_k;eta_k;v_k;omega_k]\n \n % Sanity Check\n assert(IsColumn(x_k_plus,12),\"Expecting a 12DOF state vector.\");\n \n % Define the rotation matrix from the euler angles\n R_k_plus = OMAS_geometry.eulersToRotationMatrix(x_k_plus(4:6,1));\n % Define the new quaternion from R\n q_k_plus = OMAS_geometry.rotationMatrixToQuaternion(R_k_plus');\n \n % //////////////// UPDATE GLOBAL PROPERTIES ///////////////////\n [this] = this.GlobalUpdate_direct(...\n x_k_plus(1:3),... % The global position is within the state\n x_k_plus(7:9),... % The global velocity is within the state\n q_k_plus); % Append the global quaternion\n \n % Ensure the local state is re-assigned\n this.localState = x_k_plus;\n end\n end\n methods (Static)\n % Define the open-loop dynamics\n function [dxdt] = ARdrone_OpenLoopDynamics(x_k,u_k)\n %#codegen\n \n % This function was generated by the Symbolic Math Toolbox version 8.1.\n % 17-Jul-2018 15:13:41\n \n PHI_t = x_k(4,:);\n PHI_dot = x_k(10,:);\n PSI_dot = x_k(12,:);\n THETA_t = x_k(5,:);\n THETA_dot = x_k(11,:);\n omega_1 = u_k(1,:);\n omega_2 = u_k(2,:);\n omega_3 = u_k(3,:);\n omega_4 = u_k(4,:);\n x_dot = x_k(7,:);\n y_dot = x_k(8,:);\n z_dot = x_k(9,:);\n t2 = cos(PHI_t);\n t3 = cos(THETA_t);\n t4 = sin(PHI_t);\n t5 = sin(THETA_t);\n t6 = omega_1.^2;\n t7 = sqrt(2.0);\n t8 = omega_2.^2;\n t9 = omega_3.^2;\n t10 = omega_4.^2;\n t11 = t7.*t9.*8.516167950913242e-5;\n t12 = t7.*t10.*8.516167950913242e-5;\n t13 = PSI_dot.^2;\n dxdt = [x_dot;y_dot;z_dot;PHI_dot;THETA_dot;PSI_dot;t5.*(-9.81e2./1.0e2)+THETA_dot.*t4.*y_dot+THETA_dot.*t2.*z_dot-PSI_dot.*t2.*t3.*y_dot+PSI_dot.*t3.*t4.*z_dot;-PHI_dot.*z_dot+t3.*t4.*(9.81e2./1.0e2)+PSI_dot.*t5.*z_dot-THETA_dot.*t4.*x_dot+PSI_dot.*t2.*t3.*x_dot;t6.*(-3.73475e-5)-t8.*3.73475e-5-t9.*3.73475e-5-t10.*3.73475e-5+PHI_dot.*y_dot+t2.*t3.*(9.81e2./1.0e2)-PSI_dot.*t5.*y_dot-THETA_dot.*t2.*x_dot-PSI_dot.*t3.*t4.*x_dot;t11+t12+THETA_dot.*omega_1.*3.231842180365297e-3-THETA_dot.*omega_2.*3.231842180365297e-3+THETA_dot.*omega_3.*3.231842180365297e-3-THETA_dot.*omega_4.*3.231842180365297e-3-t6.*t7.*8.516167950913242e-5-t7.*t8.*8.516167950913242e-5-THETA_dot.^2.*t4.*9.996789383561644e-1-PSI_dot.*THETA_dot.*t2-t3.*t4.*t13+PSI_dot.*THETA_dot.*t2.*t3.*9.996789383561644e-1;-t11+t12+PHI_dot.*PSI_dot-PHI_dot.*omega_1.*3.231842180365297e-3+PHI_dot.*omega_2.*3.231842180365297e-3-PHI_dot.*omega_3.*3.231842180365297e-3+PHI_dot.*omega_4.*3.231842180365297e-3+t6.*t7.*8.516167950913242e-5-t7.*t8.*8.516167950913242e-5-t5.*t13+PHI_dot.*THETA_dot.*t4.*9.996789383561644e-1-PHI_dot.*PSI_dot.*t2.*t3.*9.996789383561644e-1;t6.*4.175141847767905e-4-t8.*4.175141847767905e-4+t9.*4.175141847767905e-4-t10.*4.175141847767905e-4-PHI_dot.*THETA_dot.*1.000321164757521+PHI_dot.*THETA_dot.*t2.*1.000321164757521+PSI_dot.*THETA_dot.*t5.*1.000321164757521+PHI_dot.*PSI_dot.*t3.*t4.*1.000321164757521];\n end\n end\n % Properties\n methods\n % Get the (ARdrone) SENSOR structure\n function [SENSORS] = CreateSENSORS(this)\n % This function gets the ARdrone 2.0's sensor-specific data and\n % imports them to OMAS's obj.SENSOR structure.\n \n % Get the default SENSOR structure\n SENSORS = this.SENSORS;\n SENSORS.ultrasound_freq = 40E3; % Ultrasonic range-finder frequency (Hz)\n SENSORS.ultrasound_range = 6; % Ultrasonic range-fidner range (m)\n SENSORS.camera_freq = 30; % Camera capture frequency (fps)\n end\n % Get the (generic) quadcopter dynamic properties\n function [DYNAMICS] = CreateDYNAMICS(this)\n \n % Import the default properties of a simple quadcopter\n DYNAMICS = this.CreateDYNAMICS_default();\n \n % ALTER THE DYNAMICS BASED ON THE CONFIGURATION\n switch upper(this.config)\n case 'NONE'\n DYNAMICS.m = 0.366;\n case 'OUTDOOR'\n DYNAMICS.m = 0.400; % Arm length equiv : 0.3196\n case 'INDOOR'\n DYNAMICS.m = 0.436;\n otherwise\n error('Configuration not recognised');\n end\n % Assign the ARdrone properties\n% DYNAMICS.I = 1.0E-06.*[...\n% 2.8032E+04,0.0000E+00,0.0000E+00;\n% 0.0000E+00,2.8032E+04,0.0000E+00;\n% 0.0000E+00,0.0000E+00,2.8023E+04];\n% \n % Control properties\n % Plant matrix\n DYNAMICS.A = zeros(12); \n% DYNAMICS.A(4:6,7:9) = eye(3)*DYNAMICS.g;\n% DYNAMICS.A(1:3,4:6) = eye(3);\n% DYNAMICS.A(7:9,10:12) = eye(3);\n % Input matrix\n DYNAMICS.B = zeros(12,4);\n% DYNAMICS.B(4:6,1) = DYNAMICS.e3/DYNAMICS.m;\n% DYNAMICS.B(10:12,2:4) = inv(DYNAMICS.I);\n % Observation matrix\n DYNAMICS.C = eye(12);\n % Feed-forward matrix\n DYNAMICS.D = eye(4); \n end\n % Get the (ARdrone) GEOMETRY structure\n function [GEOMETRY] = CreateGEOMETRY(this)\n \n % Parse the geometry associated with the object\n [GEOMETRY] = this.GetObjectGeometry(this);\n \n % ALTER THE DYNAMICS BASED ON THE CONFIGURATION\n switch upper(this.config)\n case 'NONE'\n GEOMETRY.width = 0.450;\n GEOMETRY.length = 0.290;\n case 'OUTDOOR'\n GEOMETRY.width = 0.452;\n GEOMETRY.length = 0.452; % Arm length equiv : 0.3196\n case 'INDOOR'\n GEOMETRY.width = 0.515;\n GEOMETRY.length = 0.515;\n otherwise\n error('Configuration not recognised');\n end\n end\n end\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/objects/ARdrone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3501355911027218}} {"text": "%%*******************************************************************\n%% schurmat_sblk: compute Schur complement matrix corresponding to \n%% SDP blocks. \n%%\n%% symm = 0, HKM\n%% = 1, NT\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 schur = schurmat_sblk(blk,At,par,schur,p,X,Y) \n\n global nnzschur nzlistschur\n\n iter = par.iter; \n smallblkdim = par.smallblkdim; \n\n if isempty(smallblkdim); smallblkdim = 50; end\n if (nargin == 7); symm = 0; else; symm = 1; Y = X; end; \n m = length(schur); \n pblk = blk(p,:); \n if (iter == 1)\n nnzschur(size(blk,1),1) = m*m; \n nzlistschur = cell(size(blk,1),1); \n end\n%%\n if (max(pblk{2}) > smallblkdim) | (length(pblk{2}) <= 10)\n %%\n %% compute schur for matrices that are very sparse. \n %%\n m1 = size(At{p,1},2); \n if issparse(schur); schur = full(schur); end; \n J = min(m1, max(find(par.nzlistA{p,1} < inf))-1); \n if (J > 0)\n if issparse(X{p}) & ~issparse(Y{p}); X{p} = full(X{p}); end\n if ~issparse(X{p}) & issparse(Y{p}); Y{p} = full(Y{p}); end\n if (iter <= 3) \n [schur,nnzschur(p),nzlisttmp] = mexschur(pblk,At{p,1},par.nzlistA{p,1},...\n par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur); \n if (nnzschur(p) == mexnnz(nzlisttmp)) \n nzlistschur{p} = nzlisttmp;\n else\n nzlistschur{p} = []; \n end\n else\n if isempty(nzlistschur{p})\n schur = mexschur(pblk,At{p,1},par.nzlistA{p,1},...\n par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur);\n else\n schur = mexschur(pblk,At{p,1},par.nzlistA{p,1},...\n par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur,nzlistschur{p});\n end \n end\n end \n %%\n %% compute schur for matrices that are not so sparse or dense.\n %% \n if (m1 < m) %% for low rank constraints\n ss = [0, cumsum(pblk{3})]; \n len = sum(pblk{3});\n dd = At{p,3};\n DD = spconvert([dd(:,2:4); len,len,0]);\n XVD = X{p}*At{p,2}*DD; \n YVD = Y{p}*At{p,2}*DD;\n end\n L = max(find(par.nzlistAsum{p,1} < inf)) -1; \n if (J < L)\n len = par.nzlistAsum{p,1}(J+1); list = par.nzlistAsum{p,2}(1:len,:); \n end \n if (m1 > 0)\n for k = J+1:m \n if (k<=m1) \n isspAk = par.isspA(p,k);\n Ak = mexsmat(blk,At,isspAk,p,k);\n if (k <= L) \n idx1 = par.nzlistAsum{p,1}(k)+1; idx2 = par.nzlistAsum{p,1}(k+1);\n list = [list; par.nzlistAsum{p,2}(idx1:idx2,:)]; \n list = sortrows(list,[2 1]); \n tmp = Prod3(pblk,X{p},Ak,Y{p},symm,list); \n else\n tmp = Prod3(pblk,X{p},Ak,Y{p},symm);\n end\n else %%--- for low rank constraints\n idx = [ss(k-m1)+1 :ss(k-m1+1)]; \n tmp = XVD(:,idx)* (Y{p}*At{p,2}(:,idx))';\n end\n if (~symm)\n tmp = 0.5*(mexsvec(pblk,tmp) + mexsvec(pblk,tmp'));\n else\n tmp = mexsvec(pblk,tmp); \n end \n permk = par.permA(p,k); \n idx = par.permA(p,1:min(k,m1)); \n tmp2 = schur(idx,permk) + mexinprod(blk,At,tmp,min(k,m1),p);\n schur(idx,permk) = tmp2; \n schur(permk,idx) = tmp2';\n end \n end\n if (m1 < m) %% for low rank constraints\n m2 = m - m1;\n XVtmp = XVD'*At{p,2};\n YVtmp = At{p,2}'*YVD;\n for k = 1:m2\n idx0 = [ss(k)+1 : ss(k+1)]; \n tmp = XVtmp(:,idx0) .* YVtmp(:,idx0); \n tmp = tmp*ones(length(idx0),1); \n tmp3 = schur(m1+[1:m2],m1+k) + mexqops(pblk{3},tmp,ones(length(tmp),1),1); \n schur(m1+[1:m2],m1+k) = tmp3; \n end\n end\n else \n %%--- for SDP block where each sub-block is small dimensional\n if issparse(X{p}) & ~issparse(Y{p}); Y{p} = sparse(Y{p}); end\n if ~issparse(X{p}) & issparse(Y{p}); X{p} = sparse(X{p}); end\n tmp = mexskron(pblk,X{p},Y{p});\n schurtmp = At{p,1}'*tmp*At{p,1}; \n %% schurtmp = 0.5*(schurtmp + schurtmp');\n if (norm(par.permA(p,:)-[1:m]) > 0)\n Perm = spconvert([(1:m)', par.permA(p,:)', ones(m,1)]); \n schur = schur + Perm'*schurtmp*Perm;\n else\n schur = schur + schurtmp;\n end \n end\n%%*******************************************************************\n\n\n", "meta": {"author": "shamilmamedov", "repo": "dynamic_calibration", "sha": "11af40e7deb758ec080a175fed8fcdd6c99aca29", "save_path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration", "path": "github-repos/MATLAB/shamilmamedov-dynamic_calibration/dynamic_calibration-11af40e7deb758ec080a175fed8fcdd6c99aca29/utils/SDPT3-4.0/Solver/schurmat_sblk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3500375703179442}}